context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// network-sriov which connects logical pif and physical pif /// First published in XenServer 7.5. /// </summary> public partial class Network_sriov : XenObject<Network_sriov> { #region Constructors public Network_sriov() { } public Network_sriov(string uuid, XenRef<PIF> physical_PIF, XenRef<PIF> logical_PIF, bool requires_reboot, sriov_configuration_mode configuration_mode) { this.uuid = uuid; this.physical_PIF = physical_PIF; this.logical_PIF = logical_PIF; this.requires_reboot = requires_reboot; this.configuration_mode = configuration_mode; } /// <summary> /// Creates a new Network_sriov from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Network_sriov(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Network_sriov from a Proxy_Network_sriov. /// </summary> /// <param name="proxy"></param> public Network_sriov(Proxy_Network_sriov proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Network_sriov. /// </summary> public override void UpdateFrom(Network_sriov update) { uuid = update.uuid; physical_PIF = update.physical_PIF; logical_PIF = update.logical_PIF; requires_reboot = update.requires_reboot; configuration_mode = update.configuration_mode; } internal void UpdateFrom(Proxy_Network_sriov proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; physical_PIF = proxy.physical_PIF == null ? null : XenRef<PIF>.Create(proxy.physical_PIF); logical_PIF = proxy.logical_PIF == null ? null : XenRef<PIF>.Create(proxy.logical_PIF); requires_reboot = (bool)proxy.requires_reboot; configuration_mode = proxy.configuration_mode == null ? (sriov_configuration_mode) 0 : (sriov_configuration_mode)Helper.EnumParseDefault(typeof(sriov_configuration_mode), (string)proxy.configuration_mode); } public Proxy_Network_sriov ToProxy() { Proxy_Network_sriov result_ = new Proxy_Network_sriov(); result_.uuid = uuid ?? ""; result_.physical_PIF = physical_PIF ?? ""; result_.logical_PIF = logical_PIF ?? ""; result_.requires_reboot = requires_reboot; result_.configuration_mode = sriov_configuration_mode_helper.ToString(configuration_mode); return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Network_sriov /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("physical_PIF")) physical_PIF = Marshalling.ParseRef<PIF>(table, "physical_PIF"); if (table.ContainsKey("logical_PIF")) logical_PIF = Marshalling.ParseRef<PIF>(table, "logical_PIF"); if (table.ContainsKey("requires_reboot")) requires_reboot = Marshalling.ParseBool(table, "requires_reboot"); if (table.ContainsKey("configuration_mode")) configuration_mode = (sriov_configuration_mode)Helper.EnumParseDefault(typeof(sriov_configuration_mode), Marshalling.ParseString(table, "configuration_mode")); } public bool DeepEquals(Network_sriov other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._physical_PIF, other._physical_PIF) && Helper.AreEqual2(this._logical_PIF, other._logical_PIF) && Helper.AreEqual2(this._requires_reboot, other._requires_reboot) && Helper.AreEqual2(this._configuration_mode, other._configuration_mode); } internal static List<Network_sriov> ProxyArrayToObjectList(Proxy_Network_sriov[] input) { var result = new List<Network_sriov>(); foreach (var item in input) result.Add(new Network_sriov(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, Network_sriov server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given network_sriov. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network_sriov">The opaque_ref of the given network_sriov</param> public static Network_sriov get_record(Session session, string _network_sriov) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_sriov_get_record(session.opaque_ref, _network_sriov); else return new Network_sriov(session.XmlRpcProxy.network_sriov_get_record(session.opaque_ref, _network_sriov ?? "").parse()); } /// <summary> /// Get a reference to the network_sriov instance with the specified UUID. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Network_sriov> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_sriov_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Network_sriov>.Create(session.XmlRpcProxy.network_sriov_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given network_sriov. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network_sriov">The opaque_ref of the given network_sriov</param> public static string get_uuid(Session session, string _network_sriov) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_sriov_get_uuid(session.opaque_ref, _network_sriov); else return session.XmlRpcProxy.network_sriov_get_uuid(session.opaque_ref, _network_sriov ?? "").parse(); } /// <summary> /// Get the physical_PIF field of the given network_sriov. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network_sriov">The opaque_ref of the given network_sriov</param> public static XenRef<PIF> get_physical_PIF(Session session, string _network_sriov) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_sriov_get_physical_pif(session.opaque_ref, _network_sriov); else return XenRef<PIF>.Create(session.XmlRpcProxy.network_sriov_get_physical_pif(session.opaque_ref, _network_sriov ?? "").parse()); } /// <summary> /// Get the logical_PIF field of the given network_sriov. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network_sriov">The opaque_ref of the given network_sriov</param> public static XenRef<PIF> get_logical_PIF(Session session, string _network_sriov) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_sriov_get_logical_pif(session.opaque_ref, _network_sriov); else return XenRef<PIF>.Create(session.XmlRpcProxy.network_sriov_get_logical_pif(session.opaque_ref, _network_sriov ?? "").parse()); } /// <summary> /// Get the requires_reboot field of the given network_sriov. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network_sriov">The opaque_ref of the given network_sriov</param> public static bool get_requires_reboot(Session session, string _network_sriov) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_sriov_get_requires_reboot(session.opaque_ref, _network_sriov); else return (bool)session.XmlRpcProxy.network_sriov_get_requires_reboot(session.opaque_ref, _network_sriov ?? "").parse(); } /// <summary> /// Get the configuration_mode field of the given network_sriov. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network_sriov">The opaque_ref of the given network_sriov</param> public static sriov_configuration_mode get_configuration_mode(Session session, string _network_sriov) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_sriov_get_configuration_mode(session.opaque_ref, _network_sriov); else return (sriov_configuration_mode)Helper.EnumParseDefault(typeof(sriov_configuration_mode), (string)session.XmlRpcProxy.network_sriov_get_configuration_mode(session.opaque_ref, _network_sriov ?? "").parse()); } /// <summary> /// Enable SR-IOV on the specific PIF. It will create a network-sriov based on the specific PIF and automatically create a logical PIF to connect the specific network. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_pif">PIF on which to enable SR-IOV</param> /// <param name="_network">Network to connect SR-IOV virtual functions with VM VIFs</param> public static XenRef<Network_sriov> create(Session session, string _pif, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_sriov_create(session.opaque_ref, _pif, _network); else return XenRef<Network_sriov>.Create(session.XmlRpcProxy.network_sriov_create(session.opaque_ref, _pif ?? "", _network ?? "").parse()); } /// <summary> /// Enable SR-IOV on the specific PIF. It will create a network-sriov based on the specific PIF and automatically create a logical PIF to connect the specific network. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_pif">PIF on which to enable SR-IOV</param> /// <param name="_network">Network to connect SR-IOV virtual functions with VM VIFs</param> public static XenRef<Task> async_create(Session session, string _pif, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_network_sriov_create(session.opaque_ref, _pif, _network); else return XenRef<Task>.Create(session.XmlRpcProxy.async_network_sriov_create(session.opaque_ref, _pif ?? "", _network ?? "").parse()); } /// <summary> /// Disable SR-IOV on the specific PIF. It will destroy the network-sriov and the logical PIF accordingly. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network_sriov">The opaque_ref of the given network_sriov</param> public static void destroy(Session session, string _network_sriov) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_sriov_destroy(session.opaque_ref, _network_sriov); else session.XmlRpcProxy.network_sriov_destroy(session.opaque_ref, _network_sriov ?? "").parse(); } /// <summary> /// Disable SR-IOV on the specific PIF. It will destroy the network-sriov and the logical PIF accordingly. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network_sriov">The opaque_ref of the given network_sriov</param> public static XenRef<Task> async_destroy(Session session, string _network_sriov) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_network_sriov_destroy(session.opaque_ref, _network_sriov); else return XenRef<Task>.Create(session.XmlRpcProxy.async_network_sriov_destroy(session.opaque_ref, _network_sriov ?? "").parse()); } /// <summary> /// Get the number of free SR-IOV VFs on the associated PIF /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network_sriov">The opaque_ref of the given network_sriov</param> public static long get_remaining_capacity(Session session, string _network_sriov) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_sriov_get_remaining_capacity(session.opaque_ref, _network_sriov); else return long.Parse(session.XmlRpcProxy.network_sriov_get_remaining_capacity(session.opaque_ref, _network_sriov ?? "").parse()); } /// <summary> /// Get the number of free SR-IOV VFs on the associated PIF /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network_sriov">The opaque_ref of the given network_sriov</param> public static XenRef<Task> async_get_remaining_capacity(Session session, string _network_sriov) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_network_sriov_get_remaining_capacity(session.opaque_ref, _network_sriov); else return XenRef<Task>.Create(session.XmlRpcProxy.async_network_sriov_get_remaining_capacity(session.opaque_ref, _network_sriov ?? "").parse()); } /// <summary> /// Return a list of all the network_sriovs known to the system. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Network_sriov>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_sriov_get_all(session.opaque_ref); else return XenRef<Network_sriov>.Create(session.XmlRpcProxy.network_sriov_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the network_sriov Records at once, in a single XML RPC call /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Network_sriov>, Network_sriov> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_sriov_get_all_records(session.opaque_ref); else return XenRef<Network_sriov>.Create<Proxy_Network_sriov>(session.XmlRpcProxy.network_sriov_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// The PIF that has SR-IOV enabled /// </summary> [JsonConverter(typeof(XenRefConverter<PIF>))] public virtual XenRef<PIF> physical_PIF { get { return _physical_PIF; } set { if (!Helper.AreEqual(value, _physical_PIF)) { _physical_PIF = value; NotifyPropertyChanged("physical_PIF"); } } } private XenRef<PIF> _physical_PIF = new XenRef<PIF>(Helper.NullOpaqueRef); /// <summary> /// The logical PIF to connect to the SR-IOV network after enable SR-IOV on the physical PIF /// </summary> [JsonConverter(typeof(XenRefConverter<PIF>))] public virtual XenRef<PIF> logical_PIF { get { return _logical_PIF; } set { if (!Helper.AreEqual(value, _logical_PIF)) { _logical_PIF = value; NotifyPropertyChanged("logical_PIF"); } } } private XenRef<PIF> _logical_PIF = new XenRef<PIF>(Helper.NullOpaqueRef); /// <summary> /// Indicates whether the host need to be rebooted before SR-IOV is enabled on the physical PIF /// </summary> public virtual bool requires_reboot { get { return _requires_reboot; } set { if (!Helper.AreEqual(value, _requires_reboot)) { _requires_reboot = value; NotifyPropertyChanged("requires_reboot"); } } } private bool _requires_reboot = false; /// <summary> /// The mode for configure network sriov /// </summary> [JsonConverter(typeof(sriov_configuration_modeConverter))] public virtual sriov_configuration_mode configuration_mode { get { return _configuration_mode; } set { if (!Helper.AreEqual(value, _configuration_mode)) { _configuration_mode = value; NotifyPropertyChanged("configuration_mode"); } } } private sriov_configuration_mode _configuration_mode = sriov_configuration_mode.unknown; } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using WireMock.Serialization; namespace WireMock.Util { internal static class JsonUtils { public static bool TryParseAsComplexObject(string strInput, out JToken token) { token = null; if (string.IsNullOrWhiteSpace(strInput)) { return false; } strInput = strInput.Trim(); if ((!strInput.StartsWith("{") || !strInput.EndsWith("}")) && (!strInput.StartsWith("[") || !strInput.EndsWith("]"))) { return false; } try { // Try to convert this string into a JToken token = JToken.Parse(strInput); return true; } catch { return false; } } public static string Serialize<T>(T value) { return JsonConvert.SerializeObject(value, JsonSerializationConstants.JsonSerializerSettingsIncludeNullValues); } /// <summary> /// Load a Newtonsoft.Json.Linq.JObject from a string that contains JSON. /// Using : DateParseHandling = DateParseHandling.None /// </summary> /// <param name="json">A System.String that contains JSON.</param> /// <returns>A Newtonsoft.Json.Linq.JToken populated from the string that contains JSON.</returns> public static JToken Parse(string json) { return JsonConvert.DeserializeObject<JToken>(json, JsonSerializationConstants.JsonDeserializerSettingsWithDateParsingNone); } /// <summary> /// Deserializes the JSON to a .NET object. /// Using : DateParseHandling = DateParseHandling.None /// </summary> /// <param name="json">A System.String that contains JSON.</param> /// <returns>The deserialized object from the JSON string.</returns> public static object DeserializeObject(string json) { return JsonConvert.DeserializeObject(json, JsonSerializationConstants.JsonDeserializerSettingsWithDateParsingNone); } /// <summary> /// Deserializes the JSON to the specified .NET type. /// Using : DateParseHandling = DateParseHandling.None /// </summary> /// <param name="json">A System.String that contains JSON.</param> /// <returns>The deserialized object from the JSON string.</returns> public static T DeserializeObject<T>(string json) { return JsonConvert.DeserializeObject<T>(json, JsonSerializationConstants.JsonDeserializerSettingsWithDateParsingNone); } public static T ParseJTokenToObject<T>(object value) { switch (value) { case JToken tokenValue: return tokenValue.ToObject<T>(); default: return default(T); } } public static string GenerateDynamicLinqStatement(JToken jsonObject) { var lines = new List<string>(); WalkNode(jsonObject, null, null, lines); return lines.First(); } private static void WalkNode(JToken node, string path, string propertyName, List<string> lines) { if (node.Type == JTokenType.Object) { ProcessObject(node, propertyName, lines); } else if (node.Type == JTokenType.Array) { ProcessArray(node, propertyName, lines); } else { ProcessItem(node, path ?? "it", propertyName, lines); } } private static void ProcessObject(JToken node, string propertyName, List<string> lines) { var items = new List<string>(); var text = new StringBuilder("new ("); // In case of Object, loop all children. Do a ToArray() to avoid `Collection was modified` exceptions. foreach (JProperty child in node.Children<JProperty>().ToArray()) { WalkNode(child.Value, child.Path, child.Name, items); } text.Append(string.Join(", ", items)); text.Append(")"); if (!string.IsNullOrEmpty(propertyName)) { text.AppendFormat(" as {0}", propertyName); } lines.Add(text.ToString()); } private static void ProcessArray(JToken node, string propertyName, List<string> lines) { var items = new List<string>(); var text = new StringBuilder("(new [] { "); // In case of Array, loop all items. Do a ToArray() to avoid `Collection was modified` exceptions. int idx = 0; foreach (JToken child in node.Children().ToArray()) { WalkNode(child, $"{node.Path}[{idx}]", null, items); idx++; } text.Append(string.Join(", ", items)); text.Append("})"); if (!string.IsNullOrEmpty(propertyName)) { text.AppendFormat(" as {0}", propertyName); } lines.Add(text.ToString()); } private static void ProcessItem(JToken node, string path, string propertyName, List<string> lines) { string castText; switch (node.Type) { case JTokenType.Boolean: castText = $"bool({path})"; break; case JTokenType.Date: castText = $"DateTime({path})"; break; case JTokenType.Float: castText = $"double({path})"; break; case JTokenType.Guid: castText = $"Guid({path})"; break; case JTokenType.Integer: castText = $"long({path})"; break; case JTokenType.Null: castText = "null"; break; case JTokenType.String: castText = $"string({path})"; break; case JTokenType.TimeSpan: castText = $"TimeSpan({path})"; break; case JTokenType.Uri: castText = $"Uri({path})"; break; default: throw new NotSupportedException($"JTokenType '{node.Type}' cannot be converted to a Dynamic Linq cast operator."); } if (!string.IsNullOrEmpty(propertyName)) { castText += $" as {propertyName}"; } lines.Add(castText); } } }
using System; using System.Collections.Generic; using System.Text; using gView.Framework.GeoProcessing; using gView.Framework.UI; using gView.Framework.system; using System.Reflection; using gView.Framework.Data; using gView.Framework.FDB; using gView.Framework.Geometry; using gView.Framework.SpatialAlgorithms; using gView.DataSources.Fdb.MSAccess; using gView.DataSources.Fdb.MSSql; namespace gView.Framework.GeoProcessing.ActivityBase { public abstract class SimpleActivity : IActivity, IDirtyEvent { private string _errMsg = String.Empty; private ActivityFeatureData _sourceData = new ActivityFeatureData("Source Data"); private ActivityFeatureData _targetData = new ActivityFeatureData("Destination Data"); private CancelTracker _cancelTracker; public SimpleActivity() { _sourceData.DirtyEvent += new EventHandler(_sourceData_DirtyEvent); _targetData.DirtyEvent += new EventHandler(_targetData_DirtyEvent); _cancelTracker = new CancelTracker(); } void _targetData_DirtyEvent(object sender, EventArgs e) { if (DirtyEvent != null) DirtyEvent(this, e); } void _sourceData_DirtyEvent(object sender, EventArgs e) { if (DirtyEvent != null) DirtyEvent(this, e); } #region IActivity Member public List<IActivityData> Sources { get { List<IActivityData> list = new List<IActivityData>(); list.Add(_sourceData); return list; } } public List<IActivityData> Targets { get { List<IActivityData> list = new List<IActivityData>(); list.Add(_targetData); return list; } } public abstract string DisplayName { get ; } public abstract string CategoryName { get ; } public abstract List<IActivityData> Process(); #endregion #region IErrorMessage Member public string lastErrorMsg { get { return _errMsg; } } #endregion #region IDirtyEvent Member public event EventHandler DirtyEvent = null; #endregion #region IProgressReporter Member virtual public event ProgressReporterEvent ReportProgress; public ICancelTracker CancelTracker { get { return _cancelTracker; } } #endregion #region Helper protected IActivityData SourceData { get { return _sourceData; } } protected IDatasetElement SourceDatasetElement { get { if (_sourceData.Data == null) throw new ArgumentException("No Sourcedata selected..."); return _sourceData.Data; } } protected IFeatureClass SourceFeatureClass { get { IDatasetElement sElement = this.SourceDatasetElement; if (!(sElement.Class is IFeatureClass)) throw new ArgumentException("No Sourcefeatureclass available..."); return (IFeatureClass)sElement.Class; } } protected TargetDatasetElement TargetDatasetElement { get { if (!(_targetData.Data is TargetDatasetElement)) throw new ArgumentException("No Targetdata selected..."); return _targetData.Data as TargetDatasetElement; } } protected IDataset TargetDataset { get { TargetDatasetElement tElement = this.TargetDatasetElement; if (tElement.Class == null) throw new ArgumentException("No Targetfeatureclass..."); if (tElement.Class.Dataset == null) throw new ArgumentException("No Targetdataset..."); return tElement.Class.Dataset; } } protected IFeatureDatabase TargetFeatureDatabase { get { TargetDatasetElement tElement = this.TargetDatasetElement; if (tElement.Class == null) throw new ArgumentException("No Targetfeatureclass..."); if (tElement.Class.Dataset == null) throw new ArgumentException("No Targetdataset..."); if (!(tElement.Class.Dataset.Database is IFeatureDatabase)) throw new ArgumentException("No Targetdatabase..."); return (IFeatureDatabase)tElement.Class.Dataset.Database; } } protected IFeatureDatabase FeatureDatabase(IFeatureClass fc) { if (fc == null) throw new ArgumentException("No Targetfeatureclass..."); if (fc.Dataset == null) throw new ArgumentException("No Targetdataset..."); if (!(fc.Dataset.Database is IFeatureDatabase)) throw new ArgumentException("No Targetdatabase..."); return (IFeatureDatabase)fc.Dataset.Database; } protected IFeatureClass CreateTargetFeatureclass(IGeometryDef geomDef, IFields fields) { IFeatureClass sFc = SourceFeatureClass; BinaryTreeDef sDef = null; if (sFc.Dataset != null && sFc.Dataset.Database is AccessFDB) { AccessFDB sFdb = (AccessFDB)sFc.Dataset.Database; sDef = sFdb.BinaryTreeDef(sFc.Name); } TargetDatasetElement e = this.TargetDatasetElement; IDataset ds = this.TargetDataset; IFeatureDatabase db = this.TargetFeatureDatabase; if (db.CreateFeatureClass(ds.DatasetName, e.Title, geomDef, fields) == -1) throw new Exception("Can't create target featureclass:\n" + db.lastErrorMsg); IDatasetElement element = ds[e.Title]; if(element==null || !(element.Class is IFeatureClass)) throw new Exception("Can't open created featureclass"); IFeatureClass tFc = element.Class as IFeatureClass; if (db is AccessFDB) { int maxAllowedLevel = ((db is SqlFDB) ? 62 : 30); if (sDef == null) { IEnvelope sEnv = sFc.Envelope; sDef = (sEnv != null) ? new BinaryTreeDef(sFc.Envelope, 10, 200, 0.55) : new BinaryTreeDef(new Envelope()); } if (sDef.Bounds != null && sDef.SpatialReference != null && !sDef.SpatialReference.Equals(tFc.SpatialReference)) { if (!sDef.ProjectTo(tFc.SpatialReference)) throw new Exception("Can't project SpatialIndex Boundaries..."); } ((AccessFDB)db).SetSpatialIndexBounds(tFc.Name, "BinaryTree2", sDef.Bounds, sDef.SplitRatio, sDef.MaxPerNode, Math.Min(sDef.MaxLevel, maxAllowedLevel)); ((AccessFDB)db).SetFeatureclassExtent(tFc.Name, sDef.Bounds); } return tFc; } protected bool FlushFeatureClass(IFeatureClass fc) { IFeatureDatabase db = (IFeatureDatabase)fc.Dataset.Database; bool ret = true; if (db is IFileFeatureDatabase) { ret = ((IFileFeatureDatabase)db).Flush(fc); } else if (db is AccessFDB) { ret = ((AccessFDB)db).CalculateExtent(fc); } return ret; } protected List<IActivityData> ToProcessResult(IFeatureClass fc) { ActivityFeatureData aData = new ActivityFeatureData("Result"); aData.Data = new DatasetElement(fc); List<IActivityData> list = new List<IActivityData>(); list.Add(aData); return list; } private ProgressReport _report = new ProgressReport(); protected ProgressReport Report { get { return _report; } } protected void ReportProgess() { ReportProgess(String.Empty); } protected void ReportProgess(string msg) { if (!String.IsNullOrEmpty(msg)) _report.Message = msg; if (ReportProgress != null) ReportProgress(_report); } #endregion } [gView.Framework.system.RegisterPlugIn("FC814EC6-3E09-44e6-9E8E-3286FAD26B8A")] public class Merger : SimpleActivity, IPropertyPage { private static IFormatProvider _nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat; private IField _mergeField = null; private object [] _values = null; public Merger() : base() { } #region Properties public IField MergeField { get { return _mergeField; } set { _mergeField = value; } } public object[] Values { get { return _values; } set { _values = value; } } #endregion #region IActivity Member override public string DisplayName { get { return "Merge Features"; } } override public string CategoryName { get { return "Base"; } } override public List<IActivityData> Process() { #region Where Clauses List<string> whereClauses = new List<string>(); if (_mergeField == null) { whereClauses.Add(String.Empty); } else { foreach (object val in _values) { if (val == null) continue; switch (_mergeField.type) { case FieldType.smallinteger: case FieldType.integer: case FieldType.biginteger: whereClauses.Add(_mergeField.name + "=" + val.ToString()); break; case FieldType.Float: case FieldType.Double: whereClauses.Add(_mergeField.name + "=" + Convert.ToDouble(val).ToString(_nhi)); break; case FieldType.boolean: whereClauses.Add(_mergeField.name + "=" + val.ToString()); break; case FieldType.String: whereClauses.Add(_mergeField.name + "='" + val.ToString() + "'"); break; default: throw new Exception("Can't merge this fieldtype: " + _mergeField.type.ToString()); } } } #endregion IDatasetElement sElement = base.SourceDatasetElement; IFeatureClass sFc = base.SourceFeatureClass; TargetDatasetElement tElement = base.TargetDatasetElement; IDataset tDs = base.TargetDataset; //IFeatureDatabase tDatabase = base.TargetFeatureDatabase; Fields fields = new Fields(); if (_mergeField != null) fields.Add(_mergeField); IFeatureClass tFc = base.CreateTargetFeatureclass(sFc, fields); IFeatureDatabase tDatabase = FeatureDatabase(tFc); Report.featureMax = sFc.CountFeatures; Report.featurePos = 0; bool isPolygonFc = (sFc.GeometryType == geometryType.Polygon); foreach (string whereClause in whereClauses) { ReportProgess("Query Filter: " + SourceData.FilterClause + (String.IsNullOrEmpty(whereClause) ? " AND " + whereClause : String.Empty)); Feature mergeFeature = null; ; bool attributeAdded = false; using (IFeatureCursor cursor = SourceData.GetFeatures(whereClause)) { IFeature feature; List<IPolygon> polygons = new List<IPolygon>(); while ((feature = cursor.NextFeature) != null) { if (mergeFeature == null) mergeFeature = new Feature(); Report.featurePos++; if (!CancelTracker.Continue) break; if (_mergeField != null && attributeAdded == false) { mergeFeature.Fields.Add(new FieldValue(_mergeField.name, feature[_mergeField.name])); attributeAdded = true; } if (isPolygonFc) { if (feature.Shape != null) { if (!(feature.Shape is IPolygon)) { throw new Exception("Wrong argument type :" + feature.Shape.GeometryType.ToString()); } polygons.Add(feature.Shape as IPolygon); } } else { if (mergeFeature.Shape == null) { mergeFeature.Shape = feature.Shape; } else { mergeFeature.Shape = Algorithm.Merge(mergeFeature.Shape, feature.Shape, false); } } ReportProgess(); } if (isPolygonFc && mergeFeature != null) { ProgressReporterEvent r = new ProgressReporterEvent(MergePolygonReport); mergeFeature.Shape = Algorithm.FastMergePolygon(polygons, CancelTracker, r); } } if (mergeFeature != null) { if (!tDatabase.Insert(tFc, mergeFeature)) throw new Exception(tDatabase.lastErrorMsg); } if (!CancelTracker.Continue) break; } ReportProgess("Flush Features"); base.FlushFeatureClass(tFc); return base.ToProcessResult(tFc); } #endregion #region IPropertyPage Member public object PropertyPage(object initObject) { string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Assembly uiAssembly = Assembly.LoadFrom(appPath + @"\gView.GeoProcessing.UI.dll"); IPlugInParameter p = uiAssembly.CreateInstance("gView.Framework.GeoProcessing.ActivityBase.MergeFeaturesControl") as IPlugInParameter; if (p != null) { p.Parameter = this; return p; } return null; } public object PropertyPageObject() { return this; } #endregion public override event ProgressReporterEvent ReportProgress; protected void MergePolygonReport(ProgressReport report) { if (ReportProgress != null) ReportProgress(report); } } [gView.Framework.system.RegisterPlugIn("718BDF02-3CC2-46a2-B1D3-886B85A66A89")] public class Dissolve : SimpleActivity { override public string DisplayName { get { return "Dissolve Features"; } } public override string CategoryName { get { return "Base"; } } public override List<IActivityData> Process() { IDatasetElement sElement = base.SourceDatasetElement; IFeatureClass sFc = base.SourceFeatureClass; TargetDatasetElement tElement = base.TargetDatasetElement; IDataset tDs = base.TargetDataset; //IFeatureDatabase tDatabase = base.TargetFeatureDatabase; IFeatureClass tFc = base.CreateTargetFeatureclass(sFc, sFc.Fields); IFeatureDatabase tDatabase = FeatureDatabase(tFc); Report.featureMax = sFc.CountFeatures; Report.featurePos = 0; ReportProgess("Query Filter: " + SourceData.FilterClause); using (IFeatureCursor cursor = SourceData.GetFeatures(String.Empty)) { IFeature feature; List<IFeature> features = new List<IFeature>(); ReportProgess("Read/Write Features..."); while ((feature = cursor.NextFeature) != null) { if (feature.Shape == null) continue; List<IGeometry> geometries = new List<IGeometry>(); #region Dissolve if (feature.Shape is IPolygon) { foreach (IPolygon polygon in Algorithm.SplitPolygonToDonutsAndPolygons((IPolygon)feature.Shape)) { geometries.Add(polygon); } } else if (feature.Shape is IPolyline) { foreach (IPath path in Algorithm.GeometryPaths((IPolyline)feature.Shape)) { Polyline pLine = new Polyline(); pLine.AddPath(path); geometries.Add(pLine); } } else if (feature.Shape is IMultiPoint) { for (int i = 0; i < ((IMultiPoint)feature.Shape).PointCount; i++) { IPoint p = ((IMultiPoint)feature.Shape)[i]; if (p != null) geometries.Add(p); } } #endregion if (geometries.Count > 0) { foreach (IGeometry geometry in geometries) { Feature f = new Feature(feature); f.Shape = geometry; if(!tDatabase.Insert(tFc,f)) throw new Exception(tDatabase.lastErrorMsg); } } } } ReportProgess("Flush Features"); base.FlushFeatureClass(tFc); return base.ToProcessResult(tFc); } } [gView.Framework.system.RegisterPlugIn("62B9E36C-BA60-42A4-8B3E-E7156A018A25")] public class Filter : SimpleActivity { public Filter() : base() { } #region IActivity Member override public string DisplayName { get { return "Filter Features"; } } override public string CategoryName { get { return "Base"; } } override public List<IActivityData> Process() { IDatasetElement sElement = base.SourceDatasetElement; IFeatureClass sFc = base.SourceFeatureClass; TargetDatasetElement tElement = base.TargetDatasetElement; IDataset tDs = base.TargetDataset; //IFeatureDatabase tDatabase = base.TargetFeatureDatabase; IFeatureClass tFc = base.CreateTargetFeatureclass(sFc, sFc.Fields); IFeatureDatabase tDatabase = FeatureDatabase(tFc); Report.featureMax = sFc.CountFeatures; Report.featurePos = 0; ReportProgess("Query Filter: " + SourceData.FilterClause); using (IFeatureCursor cursor = SourceData.GetFeatures(String.Empty)) { IFeature feature; List<IFeature> features = new List<IFeature>(); ReportProgess("Read/Write Features..."); while ((feature = cursor.NextFeature) != null) { features.Add(feature); Report.featurePos++; if (!CancelTracker.Continue) break; if (features.Count > 100) { ReportProgess(); if (!tDatabase.Insert(tFc, features)) throw new Exception(tDatabase.lastErrorMsg); features.Clear(); } } if (features.Count > 0) { ReportProgess(); if (!tDatabase.Insert(tFc, features)) throw new Exception(tDatabase.lastErrorMsg); } ReportProgess("Flush Features"); base.FlushFeatureClass(tFc); return base.ToProcessResult(tFc); } } #endregion } [gView.Framework.system.RegisterPlugIn("6C053A99-6A9E-4BCE-9E5E-A7F46495347D")] public class Buffer : SimpleActivity, IPropertyPage { private double _bufferDistance = 30; public Buffer() : base() { } public double BufferDistance { get { return _bufferDistance; } set { _bufferDistance = value; } } #region IActivity Member override public string DisplayName { get { return "Buffer Features"; } } override public string CategoryName { get { return "Base"; } } override public List<IActivityData> Process() { IDatasetElement sElement = base.SourceDatasetElement; IFeatureClass sFc = base.SourceFeatureClass; TargetDatasetElement tElement = base.TargetDatasetElement; IDataset tDs = base.TargetDataset; //IFeatureDatabase tDatabase = base.TargetFeatureDatabase; GeometryDef geomDef = new GeometryDef( geometryType.Polygon, null, false); IFeatureClass tFc = base.CreateTargetFeatureclass(geomDef, sFc.Fields); IFeatureDatabase tDatabase = FeatureDatabase(tFc); Report.featureMax = sFc.CountFeatures; Report.featurePos = 0; ReportProgess("Query Filter: " + SourceData.FilterClause); using (IFeatureCursor cursor = SourceData.GetFeatures(String.Empty)) { IFeature feature; List<IFeature> features = new List<IFeature>(); ReportProgess("Read/Write Features..."); while ((feature = cursor.NextFeature) != null) { if (feature.Shape is ITopologicalOperation) feature.Shape = ((ITopologicalOperation)feature.Shape).Buffer(_bufferDistance); else continue; if (feature.Shape == null) continue; features.Add(feature); Report.featurePos++; ReportProgess(); if (!CancelTracker.Continue) break; if (features.Count > 100) { if (!tDatabase.Insert(tFc, features)) throw new Exception(tDatabase.lastErrorMsg); features.Clear(); } } if (features.Count > 0) { ReportProgess(); if (!tDatabase.Insert(tFc, features)) throw new Exception(tDatabase.lastErrorMsg); } ReportProgess("Flush Features"); base.FlushFeatureClass(tFc); return base.ToProcessResult(tFc); } } #endregion #region IPropertyPage Member public object PropertyPage(object initObject) { string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Assembly uiAssembly = Assembly.LoadFrom(appPath + @"\gView.GeoProcessing.UI.dll"); IPlugInParameter p = uiAssembly.CreateInstance("gView.Framework.GeoProcessing.ActivityBase.BufferControl") as IPlugInParameter; if (p != null) { p.Parameter = this; return p; } return null; } public object PropertyPageObject() { return this; } #endregion } [gView.Framework.system.RegisterPlugIn("BCCE9584-9E2E-432d-8DA5-15D8AC7350DD")] public class Clip : SimpleActivity { private bool _mergeClipper = true; #region IActivity Member override public string DisplayName { get { return "Clip Features"; } } override public string CategoryName { get { return "Base"; } } override public List<IActivityData> Process() { IDatasetElement sElement = base.SourceDatasetElement; IFeatureClass sFc = base.SourceFeatureClass; TargetDatasetElement tElement = base.TargetDatasetElement; IDataset tDs = base.TargetDataset; //IFeatureDatabase tDatabase = base.TargetFeatureDatabase; IFeatureClass tFc = base.CreateTargetFeatureclass(sFc, sFc.Fields); IFeatureDatabase tDatabase = FeatureDatabase(tFc); return null; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using System.Security.Permissions; namespace Aga.Controls.Tree { [Serializable] public sealed class TreeNodeAdv : ISerializable { #region NodeCollection private class NodeCollection : Collection<TreeNodeAdv> { private TreeNodeAdv _owner; public NodeCollection(TreeNodeAdv owner) { _owner = owner; } protected override void ClearItems() { while (this.Count != 0) this.RemoveAt(this.Count - 1); } protected override void InsertItem(int index, TreeNodeAdv item) { if (item == null) throw new ArgumentNullException("item"); if (item.Parent != _owner) { if (item.Parent != null) item.Parent.Nodes.Remove(item); item._parent = _owner; item._index = index; for (int i = index; i < Count; i++) this[i]._index++; base.InsertItem(index, item); } if (_owner.Tree != null && _owner.Tree.Model == null) { _owner.Tree.SmartFullUpdate(); } } protected override void RemoveItem(int index) { TreeNodeAdv item = this[index]; item._parent = null; item._index = -1; for (int i = index + 1; i < Count; i++) this[i]._index--; base.RemoveItem(index); if (_owner.Tree != null && _owner.Tree.Model == null) { _owner.Tree.UpdateSelection(); _owner.Tree.SmartFullUpdate(); } } protected override void SetItem(int index, TreeNodeAdv item) { if (item == null) throw new ArgumentNullException("item"); RemoveAt(index); InsertItem(index, item); } } #endregion #region Events public event EventHandler<TreeViewAdvEventArgs> Collapsing; internal void OnCollapsing() { if (Collapsing != null) Collapsing(this, new TreeViewAdvEventArgs(this)); } public event EventHandler<TreeViewAdvEventArgs> Collapsed; internal void OnCollapsed() { if (Collapsed != null) Collapsed(this, new TreeViewAdvEventArgs(this)); } public event EventHandler<TreeViewAdvEventArgs> Expanding; internal void OnExpanding() { if (Expanding != null) Expanding(this, new TreeViewAdvEventArgs(this)); } public event EventHandler<TreeViewAdvEventArgs> Expanded; internal void OnExpanded() { if (Expanded != null) Expanded(this, new TreeViewAdvEventArgs(this)); } #endregion #region Properties private TreeViewAdv _tree; public TreeViewAdv Tree { get { return _tree; } } private int _row; public int Row { get { return _row; } internal set { _row = value; } } private int _index = -1; public int Index { get { return _index; } } private bool _isSelected; public bool IsSelected { get { return _isSelected; } set { if (_isSelected != value) { if (Tree.IsMyNode(this)) { //_tree.OnSelectionChanging if (value) { if (!_tree.Selection.Contains(this)) _tree.Selection.Add(this); if (_tree.Selection.Count == 1) _tree.CurrentNode = this; } else _tree.Selection.Remove(this); _tree.UpdateView(); _tree.OnSelectionChanged(); } _isSelected = value; } } } /// <summary> /// Returns true if all parent nodes of this node are expanded. /// </summary> internal bool IsVisible { get { TreeNodeAdv node = _parent; while (node != null) { if (!node.IsExpanded) return false; node = node.Parent; } return true; } } private bool _isLeaf; public bool IsLeaf { get { return _isLeaf; } internal set { _isLeaf = value; } } private bool _isExpandedOnce; public bool IsExpandedOnce { get { return _isExpandedOnce; } internal set { _isExpandedOnce = value; } } private bool _isExpanded; public bool IsExpanded { get { return _isExpanded; } set { if (value) Expand(); else Collapse(); } } internal void AssignIsExpanded(bool value) { _isExpanded = value; } private TreeNodeAdv _parent; public TreeNodeAdv Parent { get { return _parent; } } public int Level { get { if (_parent == null) return 0; else return _parent.Level + 1; } } public TreeNodeAdv PreviousNode { get { if (_parent != null) { int index = Index; if (index > 0) return _parent.Nodes[index - 1]; } return null; } } public TreeNodeAdv NextNode { get { if (_parent != null) { int index = Index; if (index < _parent.Nodes.Count - 1) return _parent.Nodes[index + 1]; } return null; } } internal TreeNodeAdv BottomNode { get { TreeNodeAdv parent = this.Parent; if (parent != null) { if (parent.NextNode != null) return parent.NextNode; else return parent.BottomNode; } return null; } } internal TreeNodeAdv NextVisibleNode { get { if (IsExpanded && Nodes.Count > 0) return Nodes[0]; else { TreeNodeAdv nn = NextNode; if (nn != null) return nn; else return BottomNode; } } } public bool CanExpand { get { return (Nodes.Count > 0 || (!IsExpandedOnce && !IsLeaf)); } } private object _tag; public object Tag { get { return _tag; } } private Collection<TreeNodeAdv> _nodes; internal Collection<TreeNodeAdv> Nodes { get { return _nodes; } } private ReadOnlyCollection<TreeNodeAdv> _children; public ReadOnlyCollection<TreeNodeAdv> Children { get { return _children; } } private int? _rightBounds; internal int? RightBounds { get { return _rightBounds; } set { _rightBounds = value; } } private int? _height; internal int? Height { get { return _height; } set { _height = value; } } private bool _isExpandingNow; internal bool IsExpandingNow { get { return _isExpandingNow; } set { _isExpandingNow = value; } } private bool _autoExpandOnStructureChanged = false; public bool AutoExpandOnStructureChanged { get { return _autoExpandOnStructureChanged; } set { _autoExpandOnStructureChanged = value; } } #endregion public TreeNodeAdv(object tag) : this(null, tag) { } internal TreeNodeAdv(TreeViewAdv tree, object tag) { _row = -1; _tree = tree; _nodes = new NodeCollection(this); _children = new ReadOnlyCollection<TreeNodeAdv>(_nodes); _tag = tag; } public override string ToString() { if (Tag != null) return Tag.ToString(); else return base.ToString(); } public void Collapse() { if (_isExpanded) Collapse(true); } public void CollapseAll() { Collapse(false); } public void Collapse(bool ignoreChildren) { SetIsExpanded(false, ignoreChildren); } public void Expand() { if (!_isExpanded) Expand(true); } public void ExpandAll() { Expand(false); } public void Expand(bool ignoreChildren) { SetIsExpanded(true, ignoreChildren); } private void SetIsExpanded(bool value, bool ignoreChildren) { if (Tree == null) _isExpanded = value; else Tree.SetIsExpanded(this, value, ignoreChildren); } #region ISerializable Members private TreeNodeAdv(SerializationInfo info, StreamingContext context) : this(null, null) { int nodesCount = 0; nodesCount = info.GetInt32("NodesCount"); _isExpanded = info.GetBoolean("IsExpanded"); _tag = info.GetValue("Tag", typeof(object)); for (int i = 0; i < nodesCount; i++) { TreeNodeAdv child = (TreeNodeAdv)info.GetValue("Child" + i, typeof(TreeNodeAdv)); Nodes.Add(child); } } [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("IsExpanded", IsExpanded); info.AddValue("NodesCount", Nodes.Count); if ((Tag != null) && Tag.GetType().IsSerializable) info.AddValue("Tag", Tag, Tag.GetType()); for (int i = 0; i < Nodes.Count; i++) info.AddValue("Child" + i, Nodes[i], typeof(TreeNodeAdv)); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Security.Cryptography; using System.Text; using Microsoft.CodeAnalysis; using Orleans.CodeGenerator.Utilities; namespace Orleans.CodeGenerator.Compatibility { internal static class OrleansLegacyCompat { public static int GetMethodId(this WellKnownTypes wellKnownTypes, IMethodSymbol methodInfo) { if (GetAttribute(methodInfo, wellKnownTypes.MethodIdAttribute) is AttributeData attr) { return (int)attr.ConstructorArguments.First().Value; } var result = FormatMethodForMethodIdComputation(methodInfo); return CalculateIdHash(result); } internal static string FormatMethodForMethodIdComputation(IMethodSymbol methodInfo) { var result = new StringBuilder(methodInfo.Name); if (methodInfo.IsGenericMethod) { result.Append('<'); var first = true; foreach (var arg in methodInfo.TypeArguments) { if (!first) result.Append(','); else first = false; result.Append(RoslynTypeNameFormatter.Format(arg, RoslynTypeNameFormatter.Style.RuntimeTypeNameFormatter)); } result.Append('>'); } { result.Append('('); var parameters = methodInfo.Parameters; var first = true; foreach (var parameter in parameters) { if (!first) result.Append(','); var parameterType = parameter.Type; switch (parameterType) { case ITypeParameterSymbol _: result.Append(parameterType.Name); break; default: result.Append(RoslynTypeNameFormatter.Format(parameterType, RoslynTypeNameFormatter.Style.RuntimeTypeNameFormatter)); break; } first = false; } } result.Append(')'); return result.ToString(); } public static int GetTypeId(this WellKnownTypes wellKnownTypes, INamedTypeSymbol type) { if (GetAttribute(type, wellKnownTypes.TypeCodeOverrideAttribute) is AttributeData attr) { return (int)attr.ConstructorArguments.First().Value; } var fullName = FormatTypeForIdComputation(type); return CalculateIdHash(fullName); } private static AttributeData GetAttribute(ISymbol type, ITypeSymbol attributeType) { var attrs = type.GetAttributes(); foreach (var attr in attrs) { if (attr.AttributeClass.Equals(attributeType)) { return attr; } } return null; } private static int CalculateIdHash(string text) { var sha = SHA256.Create(); var hash = 0; try { var data = Encoding.Unicode.GetBytes(text); var result = sha.ComputeHash(data); for (var i = 0; i < result.Length; i += 4) { var tmp = (result[i] << 24) | (result[i + 1] << 16) | (result[i + 2] << 8) | result[i + 3]; hash = hash ^ tmp; } } finally { sha.Dispose(); } return hash; } internal static string FormatTypeForIdComputation(INamedTypeSymbol symbol) => GetTemplatedName( GetFullName(symbol), symbol, symbol.TypeArguments, t => false); public static ushort GetVersion(this WellKnownTypes wellKnownTypes, ISymbol symbol) { if (GetAttribute(symbol, wellKnownTypes.VersionAttribute) is AttributeData attr) { return (ushort)attr.ConstructorArguments.First().Value; } // Return the default version return 0; } /// <summary> /// Returns true if the provided type is a grain interface. /// </summary> public static bool IsGrainInterface(this WellKnownTypes types, INamedTypeSymbol type) { if (type.TypeKind != TypeKind.Interface) return false; var orig = type.OriginalDefinition; return orig.AllInterfaces.Contains(types.IAddressable) && !IsGrainMarkerInterface(types, orig); bool IsGrainMarkerInterface(WellKnownTypes l, INamedTypeSymbol t) { return Equals(t, l.IGrainObserver) || Equals(t, l.IAddressable) || Equals(t, l.IGrainExtension) || Equals(t, l.IGrain) || Equals(t, l.IGrainWithGuidKey) || Equals(t, l.IGrainWithIntegerKey) || Equals(t, l.IGrainWithStringKey) || Equals(t, l.IGrainWithGuidCompoundKey) || Equals(t, l.IGrainWithIntegerCompoundKey) || Equals(t, l.ISystemTarget); } } /// <summary> /// Returns true if the provided type is a grain implementation. /// </summary> public static bool IsGrainClass(this WellKnownTypes types, INamedTypeSymbol type) { if (type.TypeKind != TypeKind.Class) return false; var orig = type.OriginalDefinition; return HasBase(orig, types.Grain) && !IsMarkerType(types, orig); bool IsMarkerType(WellKnownTypes l, INamedTypeSymbol t) { return Equals(t, l.Grain) || Equals(t, l.GrainOfT); } bool HasBase(INamedTypeSymbol t, INamedTypeSymbol baseType) { if (Equals(t.BaseType, baseType)) return true; if (t.BaseType != null) return HasBase(t.BaseType, baseType); return false; } } public static string OrleansTypeKeyString(this ITypeSymbol t) { var sb = new StringBuilder(); OrleansTypeKeyString(t, sb); return sb.ToString(); } private static void OrleansTypeKeyString(ITypeSymbol t, StringBuilder sb) { var namedType = t as INamedTypeSymbol; // Check if the type is a non-constructed generic type. if (namedType != null && IsGenericTypeDefinition(namedType, out var typeParamsLength)) { GetBaseTypeKey(t, sb); sb.Append('\''); sb.Append(typeParamsLength); } else if (namedType != null && namedType.IsGenericType) { GetBaseTypeKey(t, sb); sb.Append('<'); var first = true; foreach (var genericArgument in namedType.GetHierarchyTypeArguments()) { if (!first) { sb.Append(','); } first = false; OrleansTypeKeyString(genericArgument, sb); } sb.Append('>'); } else if (t is IArrayTypeSymbol arrayType) { OrleansTypeKeyString(arrayType.ElementType, sb); sb.Append('['); if (arrayType.Rank > 1) { sb.Append(',', arrayType.Rank - 1); } sb.Append(']'); } else if (t is IPointerTypeSymbol pointerType) { OrleansTypeKeyString(pointerType.PointedAtType, sb); sb.Append("*"); } else { GetBaseTypeKey(t, sb); } } private static void GetBaseTypeKey(ITypeSymbol type, StringBuilder sb) { var namespacePrefix = ""; var ns = type.ContainingNamespace?.ToString(); if (ns != null && !ns.StartsWith("System.") && !ns.Equals("System")) { namespacePrefix = ns + '.'; } if (type.DeclaredAccessibility == Accessibility.Public && type.ContainingType != null) { sb.Append(namespacePrefix); OrleansTypeKeyString(type.OriginalDefinition?.ContainingType ?? type.ContainingType, sb); sb.Append('.').Append(type.Name); } else { sb.Append(namespacePrefix).Append(type.Name); } if (type is INamedTypeSymbol namedType && namedType.IsGenericType && namedType.TypeArguments.Length > 0) { sb.Append('`').Append(namedType.TypeArguments.Length); } } public static string GetTemplatedName(ITypeSymbol type, Func<ITypeSymbol, bool> fullName = null) { if (fullName == null) fullName = _ => true; switch (type) { case IArrayTypeSymbol array: return GetTemplatedName(array.ElementType, fullName) + "[" + new string(',', array.Rank - 1) + "]"; case INamedTypeSymbol named when named.IsGenericType: return GetTemplatedName(GetSimpleTypeName(named, fullName), named, named.TypeArguments, fullName); case INamedTypeSymbol named: return GetSimpleTypeName(named, fullName); case ITypeParameterSymbol parameter: return parameter.Name; default: throw new NotSupportedException($"Symbol {type} of type {type.GetType()} is not supported."); } } public static string GetTemplatedName(string baseName, INamedTypeSymbol type, ImmutableArray<ITypeSymbol> genericArguments, Func<ITypeSymbol, bool> fullName) { if (!type.IsGenericType || type.ContainingType != null && type.ContainingType.IsGenericType) return baseName; var s = baseName; s += "<"; s += GetGenericTypeArgs(genericArguments, fullName); s += ">"; return s; } public static string GetGenericTypeArgs(IEnumerable<ITypeSymbol> args, Func<ITypeSymbol, bool> fullName) { var result = string.Empty; var first = true; foreach (var genericParameter in args) { if (!first) { result += ","; } if (genericParameter is INamedTypeSymbol named && !named.IsGenericType) { result += GetSimpleTypeName(named, fullName); } else { result += GetTemplatedName(genericParameter, fullName); } first = false; } return result; } public static string GetSimpleTypeName(ITypeSymbol type, Func<ITypeSymbol, bool> fullName = null) { var named = type as INamedTypeSymbol; if (type.ContainingType != null) { if (type.ContainingType.IsGenericType) { return GetTemplatedName( GetUntemplatedTypeName(type.ContainingType.Name), type.ContainingType, named?.TypeArguments ?? default(ImmutableArray<ITypeSymbol>), _ => true) + "." + GetUntemplatedTypeName(type.Name); } return GetTemplatedName(type.ContainingType) + "." + GetUntemplatedTypeName(type.Name); } if (named == null || named.IsGenericType) return GetSimpleTypeName(fullName != null && fullName(type) ? GetFullName(type) : type.Name); return fullName != null && fullName(type) ? GetFullName(type) : type.Name; } public static string GetUntemplatedTypeName(string typeName) { var i = typeName.IndexOf('`'); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('<'); if (i > 0) { typeName = typeName.Substring(0, i); } return typeName; } public static string GetSimpleTypeName(string typeName) { var i = typeName.IndexOf('`'); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('['); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('<'); if (i > 0) { typeName = typeName.Substring(0, i); } return typeName; } public static string GetFullName(ITypeSymbol t) { if (t == null) throw new ArgumentNullException(nameof(t)); if (t.ContainingType != null && !(t is ITypeParameterSymbol)) { return $"{t.GetNamespaceName()}.{t.ContainingType.Name}.{t.Name}{GetArity(t)}"; } if (t is IArrayTypeSymbol array) { return GetFullName(array.ElementType) + "[" + new string(',', array.Rank - 1) + "]"; } return RoslynTypeNameFormatter.Format(t, RoslynTypeNameFormatter.Style.FullName); // ?? (t is ITypeParameterSymbol) ? t.Name : t.GetNamespaceName() + "." + t.Name; string GetArity(ITypeSymbol type) { if (!(type is INamedTypeSymbol named)) return string.Empty; if (named.TypeArguments.Length > 0) return $"`{named.TypeArguments.Length}"; return string.Empty; } } static bool IsGenericTypeDefinition(INamedTypeSymbol type, out int typeParamsLength) { if (type.IsUnboundGenericType) { typeParamsLength = type.GetHierarchyTypeArguments().Count(); return true; } if (type.IsGenericType && type.GetNestedHierarchy().All(t => t.ConstructedFrom == t)) { typeParamsLength = type.GetHierarchyTypeArguments().Count(); return true; } typeParamsLength = 0; return false; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim 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. * * (PORTED FROM DotNetEngine) */ using System; using System.Collections.Generic; using System.Reflection; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules; using OpenSim.Region; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using log4net; using OpenSim.Region.ScriptEngine.Interfaces; namespace InWorldz.Phlox.Engine { internal class EventRouter { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IScriptEngine myScriptEngine; public EventRouter(IScriptEngine scriptEngine) { myScriptEngine = scriptEngine; this.HookUpEvents(); } public void HookUpEvents() { m_log.Info("[" + myScriptEngine.ScriptEngineName + "]: Attaching to object events"); myScriptEngine.World.EventManager.OnObjectGrab += touch_start; myScriptEngine.World.EventManager.OnObjectDeGrab += touch_end; myScriptEngine.World.EventManager.OnScriptChangedEvent += changed; myScriptEngine.World.EventManager.OnScriptAtTargetEvent += at_target; myScriptEngine.World.EventManager.OnScriptNotAtTargetEvent += not_at_target; myScriptEngine.World.EventManager.OnBotPathUpdateEvent += bot_update; myScriptEngine.World.EventManager.OnScriptControlEvent += control; myScriptEngine.World.EventManager.OnScriptColliderStart += collision_start; myScriptEngine.World.EventManager.OnScriptColliding += collision; myScriptEngine.World.EventManager.OnScriptCollidingEnd += collision_end; myScriptEngine.World.EventManager.OnScriptLandCollidingStart += land_collision_start; myScriptEngine.World.EventManager.OnScriptLandCollidingEnd += land_collision_end; myScriptEngine.World.EventManager.OnScriptLandColliding += land_collision; myScriptEngine.World.EventManager.OnObjectGrabUpdate += new EventManager.ObjectGrabUpdateDelegate(EventManager_OnObjectGrabUpdate); myScriptEngine.World.EventManager.OnAttachObject += new EventManager.AttachObject(EventManager_OnAttachObject); myScriptEngine.World.EventManager.OnDetachObject += new EventManager.DetachObject(EventManager_OnDetachObject); myScriptEngine.World.EventManager.OnScriptAtRotTargetEvent += EventManager_OnScriptAtRotTargetEvent; myScriptEngine.World.EventManager.OnScriptNotAtRotTargetEvent += EventManager_OnScriptNotAtRotTargetEvent; IMoneyModule money = myScriptEngine.World.RequestModuleInterface<IMoneyModule>(); if (money != null) money.OnObjectPaid += HandleObjectPaid; } void EventManager_OnScriptNotAtRotTargetEvent(uint localID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "not_at_rot_target", new object[0], new DetectParams[0])); } void EventManager_OnScriptAtRotTargetEvent(uint localID, int handle, Quaternion targetRot, Quaternion atRot) { myScriptEngine.PostObjectEvent(localID, new EventParams( "at_rot_target", new object[] { handle, targetRot, atRot}, new DetectParams[0])); } void EventManager_OnObjectGrabUpdate(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { // Add to queue for all scripts in ObjectID object DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = remoteClient.AgentId; det[0].Populate(myScriptEngine.World); det[0].OffsetPos = offsetPos; if (originalID == 0) { SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID); if (part == null) return; det[0].LinkNum = part.LinkNum; } else { SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID); det[0].LinkNum = originalPart.LinkNum; } if (surfaceArgs != null) { det[0].SurfaceTouchArgs = surfaceArgs; } myScriptEngine.UpdateTouchData(localID, det); } void EventManager_OnDetachObject(uint localId) { myScriptEngine.PostObjectEvent(localId, new EventParams( "attach", new object[] { UUID.Zero.ToString() }, new DetectParams[0])); } void EventManager_OnAttachObject(UUID avatarId, uint localId) { myScriptEngine.PostObjectEvent(localId, new EventParams( "attach", new object[] { avatarId.ToString() }, new DetectParams[0])); } public void ReadConfig() { } private void HandleObjectPaid(UUID objectID, UUID agentID, int amount) { SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(objectID); if (part == null) return; int paidLink = part.LinkNum; // Check if this part has a money handler, if not, pass it to the root part if ((part.ScriptEvents & ScriptEvents.money) == 0) if (!part.IsRootPart()) part = part.ParentGroup.RootPart; if (part == null) return; // Okay now send the money event to the appropriate/selected part money(part, agentID, amount, paidLink); } public void changed(uint localID, uint change) { // Add to queue for all scripts in localID, Object pass change. myScriptEngine.PostObjectEvent(localID, new EventParams( "changed", new object[] { (int)change }, new DetectParams[0])); } public void state_entry(uint localID, UUID itemID) { // Add to queue for all scripts in ObjectID object /*myScriptEngine.PostObjectEvent(localID, new EventParams( "state_entry",new object[] { }, new DetectParams[0]));*/ //state changes are NOT object events myScriptEngine.PostScriptEvent(itemID, new EventParams( "state_entry", new object[] { }, new DetectParams[0])); } public void touch_start(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { // Add to queue for all scripts in ObjectID object DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = remoteClient.AgentId; det[0].Populate(myScriptEngine.World); if (originalID == 0) { SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID); if (part == null) return; det[0].LinkNum = part.LinkNum; } else { SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID); det[0].LinkNum = originalPart.LinkNum; } if (surfaceArgs != null) { det[0].SurfaceTouchArgs = surfaceArgs; } myScriptEngine.PostObjectEvent(localID, new EventParams( "touch_start", new Object[] { 1 }, det)); } public void touch(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient) { // Add to queue for all scripts in ObjectID object DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = remoteClient.AgentId; det[0].Populate(myScriptEngine.World); det[0].OffsetPos = offsetPos; if (originalID == 0) { SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID); if (part == null) return; det[0].LinkNum = part.LinkNum; } else { SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID); det[0].LinkNum = originalPart.LinkNum; } myScriptEngine.PostObjectEvent(localID, new EventParams( "touch", new Object[] { 1 }, det)); } public void touch_end(uint localID, uint originalID, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { // Add to queue for all scripts in ObjectID object DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = remoteClient.AgentId; det[0].Populate(myScriptEngine.World); if (originalID == 0) { SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID); if (part == null) return; det[0].LinkNum = part.LinkNum; } else { SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID); if (originalPart == null) return; det[0].LinkNum = originalPart.LinkNum; } if (surfaceArgs != null) { det[0].SurfaceTouchArgs = surfaceArgs; } myScriptEngine.PostObjectEvent(localID, new EventParams( "touch_end", new Object[] { 1 }, det)); } public void money(SceneObjectPart part, UUID agentID, int amount, int paidLinkNum) { DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = agentID; det[0].LinkNum = paidLinkNum; myScriptEngine.PostObjectEvent(part.LocalId, new EventParams( "money", new object[] { agentID.ToString(), amount }, det)); } // TODO: Replace placeholders below // NOTE! THE PARAMETERS FOR THESE FUNCTIONS ARE NOT CORRECT! // These needs to be hooked up to OpenSim during init of this class // then queued in EventQueueManager. // When queued in EventQueueManager they need to be LSL compatible (name and params) public void state_exit(uint localID, UUID itemID) { myScriptEngine.PostScriptEvent(itemID, new EventParams( "state_exit", new object[] { }, new DetectParams[0])); } public void collision_start(uint localID, ColliderArgs col) { // Add to queue for all scripts in ObjectID object List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = DetectParams.FromDetectedObject(detobj); det.Add(d); } if (det.Count > 0) myScriptEngine.PostObjectEvent(localID, new EventParams( "collision_start", new Object[] { det.Count }, det.ToArray())); } public void collision(uint localID, ColliderArgs col) { // Add to queue for all scripts in ObjectID object List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = DetectParams.FromDetectedObject(detobj); det.Add(d); } if (det.Count > 0) { myScriptEngine.PostObjectEvent(localID, new EventParams( "collision", new Object[] { det.Count }, det.ToArray())); } } public void collision_end(uint localID, ColliderArgs col) { // Add to queue for all scripts in ObjectID object List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = DetectParams.FromDetectedObject(detobj); det.Add(d); } if (det.Count > 0) myScriptEngine.PostObjectEvent(localID, new EventParams( "collision_end", new Object[] { det.Count }, det.ToArray())); } public void land_collision_start(uint localID, Vector3 pos) { myScriptEngine.PostObjectEvent(localID, new EventParams( "land_collision_start", new object[] { pos }, new DetectParams[0])); } public void land_collision(uint localID, Vector3 pos) { myScriptEngine.PostObjectEvent(localID, new EventParams( "land_collision", new object[] { pos }, new DetectParams[0])); } public void land_collision_end(uint localID, Vector3 pos) { myScriptEngine.PostObjectEvent(localID, new EventParams( "land_collision_end", new object[] { pos }, new DetectParams[0])); } // Handled by long commands public void timer(uint localID, UUID itemID) { } public void listen(uint localID, UUID itemID) { } public void control(uint localID, UUID itemID, UUID agentID, uint held, uint change) { //if ((change == 0) && (myScriptEngine.m_EventQueueManager.CheckEeventQueueForEvent(localID, "control"))) return; myScriptEngine.PostObjectEvent(localID, new EventParams( "control", new object[] { agentID.ToString(), (int)held, (int)change}, new DetectParams[0])); } public void email(uint localID, UUID itemID, string timeSent, string address, string subject, string message, int numLeft) { myScriptEngine.PostObjectEvent(localID, new EventParams( "email", new object[] { timeSent, address, subject, message, numLeft}, new DetectParams[0])); } public void at_target(uint localID, int handle, Vector3 targetpos, Vector3 atpos) { myScriptEngine.PostObjectEvent(localID, new EventParams( "at_target", new object[] { handle, targetpos, atpos }, new DetectParams[0])); } public void not_at_target(uint localID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "not_at_target", new object[0], new DetectParams[0])); } public void bot_update(UUID itemID, UUID botID, int flag, List<object> parameters) { myScriptEngine.PostScriptEvent(itemID, new EventParams( "bot_update", new object[] { botID.ToString(), flag, new InWorldz.Phlox.Types.LSLList(parameters) }, new DetectParams[0])); } public void at_rot_target(uint localID, UUID itemID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "at_rot_target", new object[0], new DetectParams[0])); } public void not_at_rot_target(uint localID, UUID itemID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "not_at_rot_target", new object[0], new DetectParams[0])); } public void attach(uint localID, UUID itemID) { } public void dataserver(uint localID, UUID itemID) { } public void link_message(uint localID, UUID itemID) { } public void moving_start(uint localID, UUID itemID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "moving_start", new object[0], new DetectParams[0])); } public void moving_end(uint localID, UUID itemID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "moving_end", new object[0], new DetectParams[0])); } public void object_rez(uint localID, UUID itemID) { } public void remote_data(uint localID, UUID itemID) { } // Handled by long commands public void http_response(uint localID, UUID itemID) { } /// <summary> /// If set to true then threads and stuff should try to make a graceful exit /// </summary> public bool PleaseShutdown { get { return _PleaseShutdown; } set { _PleaseShutdown = value; } } private bool _PleaseShutdown = false; } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation usages. (see /// http://aka.ms/azureautomationsdk/usageoperations for more information) /// </summary> internal partial class UsageOperations : IServiceOperations<AutomationManagementClient>, IUsageOperations { /// <summary> /// Initializes a new instance of the UsageOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal UsageOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Retrieve the usage for the account id. (see /// http://aka.ms/azureautomationsdk/usageoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get usage operation. /// </returns> public async Task<UsageListResponse> ListAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/usages"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result UsageListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new UsageListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Usage usageInstance = new Usage(); result.Usage.Add(usageInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); usageInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { UsageCounterName nameInstance = new UsageCounterName(); usageInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { string unitInstance = ((string)unitValue); usageInstance.Unit = unitInstance; } JToken currentValueValue = valueValue["currentValue"]; if (currentValueValue != null && currentValueValue.Type != JTokenType.Null) { double currentValueInstance = ((double)currentValueValue); usageInstance.CurrentValue = currentValueInstance; } JToken limitValue = valueValue["limit"]; if (limitValue != null && limitValue.Type != JTokenType.Null) { long limitInstance = ((long)limitValue); usageInstance.Limit = limitInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Xml; using OLDDM = LearningRegistryCache2.App_Code.DataManagers; using Isle.BizServices; using LRWarehouse.Business; namespace LearningRegistryCache2 { public class LrmiHandler : MetadataController { private AuditReportingServices auditReportingManager; private LR_Import.ResourceVersionController versionManager; public LrmiHandler() { auditReportingManager = new AuditReportingServices(); versionManager = new LR_Import.ResourceVersionController(); } public bool LrmiMap(string docId, string url, string payloadPlacement, XmlDocument record) { // Begin common logic for all metadata schemas XmlDocument payload = new XmlDocument(); bool isValid = true; string title = ""; string description = ""; Resource resource = LoadCommonMetadata(docId, ref url, payloadPlacement, record, payload, ref isValid); if (!isValid) { // Check to see if Resource.Version record exists. If not, remove it. Then skip this record VerifyResourceVersionRecordExists(resource); return false; } // End common logic for all metadata schemas XmlNodeList list = payload.GetElementsByTagName("name"); foreach (XmlNode titleNode in list) { XmlDocument doc2 = new XmlDocument(); XmlNodeList list2 = null; if (titleNode.ChildNodes != null && titleNode.ChildNodes.Count > 0) { doc2.LoadXml("<root>" + titleNode.InnerXml + "</root>"); list2 = doc2.GetElementsByTagName("name"); } if (titleNode.ParentNode.Name.ToLower() == "resource_data") { if (list2 != null && list2.Count > 0) { title = TrimWhitespace(list2[0].InnerText); } else { title = TrimWhitespace(titleNode.InnerText); } if (title.Length > resource.Version.Title.Length) { resource.Version.Title = StripTrailingPeriod(title); } break; } else if (titleNode.ParentNode.Name.ToLower() == "items") { if (list2 != null && list2.Count > 0) { title = TrimWhitespace(list2[0].InnerText); } else { title = TrimWhitespace(titleNode.InnerText); } if (title.Length > resource.Version.Title.Length) { resource.Version.Title = StripTrailingPeriod(title); } break; } else if (titleNode.ParentNode.Name.ToLower() == "properties" && (titleNode.ParentNode.ParentNode.Name.ToLower() == "items" || titleNode.ParentNode.ParentNode.Name.ToLower() == "resource_data")) { if (list2 != null && list2.Count > 0) { title = TrimWhitespace(list2[0].InnerText); } else { title = TrimWhitespace(titleNode.InnerText); } if (title.Length > resource.Version.Title.Length) { resource.Version.Title = StripTrailingPeriod(title); } break; } } // if no title, reject the record with an error message if (resource.Version.Title == null || resource.Version.Title == "") { VerifyResourceVersionRecordExists(resource); reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Program, "No title found for resource. Resource skipped."); return false; } //If title does not meet minimum requirements, make record inactive and log it. string status = "OK"; if (!IsGoodTitle(resource.Version.Title, ref status)) { resource.Version.IsActive = false; reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Program, status); } list = payload.GetElementsByTagName("description"); foreach (XmlNode node in list) { description = CleanseDescription(TrimWhitespace(node.InnerText)); if (description.Length > resource.Version.Description.Length) { resource.Version.Description = description; } break; } list = payload.GetElementsByTagName("publisher"); foreach (XmlNode node in list) { XmlDocument doc2 = new XmlDocument(); doc2.LoadXml(node.OuterXml); XmlNodeList list2 = doc2.GetElementsByTagName("name"); if (list2 != null && list2.Count > 0) { resource.Version.Publisher = TrimWhitespace(list2[0].InnerText); } else { resource.Version.Publisher = TrimWhitespace(node.InnerText); } break; } list = payload.GetElementsByTagName("author"); foreach (XmlNode node in list) { XmlDocument doc2 = new XmlDocument(); doc2.LoadXml(node.OuterXml); XmlNodeList list2 = doc2.GetElementsByTagName("name"); if (list2 != null && list2.Count > 0) { resource.Version.Creator = TrimWhitespace(list2[0].InnerText); } else { resource.Version.Creator = TrimWhitespace(node.InnerText); } break; } if ((resource.Version.Publisher == null || resource.Version.Publisher == "") && (resource.Version.Creator == null || resource.Version.Creator == "")) { try { Uri tempUri = new Uri(resource.ResourceUrl); resource.Version.Publisher = resource.Version.Creator = tempUri.Host; } catch (Exception ex) { resource.Version.Publisher = resource.Version.Creator = "Unknown"; reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, docId, resource.ResourceUrl, ErrorType.Warning, ErrorRouting.Technical, "Unknown publisher/bad URL"); } } if (resource.Version.Publisher == null || resource.Version.Publisher == "") { resource.Version.Publisher = resource.Version.Creator; } if (resource.Version.Creator == null || resource.Version.Creator == "") { resource.Version.Creator = resource.Version.Publisher; } list = payload.GetElementsByTagName("useRightsUrl"); foreach (XmlNode node in list) { if (node.InnerText.IndexOf("useRightsUrl") == -1) { resource.Version.Rights = TrimWhitespace(node.InnerText); break; } } // Access Rights - ISLE extension to LRMI list = payload.GetElementsByTagName("accessRestrictions"); if (list.Count == 0) { list = payload.GetElementsByTagName("accessRights"); } foreach (XmlNode node in list) { string accessRights = TrimWhitespace(node.InnerText); string rvAccessRights = string.Empty; resource.Version.AccessRightsId = importManager.MapAccessRights(accessRights, ref rvAccessRights); resource.Version.AccessRights = rvAccessRights; break; } list = payload.GetElementsByTagName("timeRequired"); foreach (XmlNode node in list) { resource.Version.TypicalLearningTime = TrimWhitespace(node.InnerText); break; } list = payload.GetElementsByTagName("payload_schema"); foreach (XmlNode node in list) { resource.Version.Schema = TrimWhitespace(node.InnerText); break; } list = payload.GetElementsByTagName("requires"); foreach (XmlNode node in list) { resource.Version.Requirements = TrimWhitespace(node.InnerText); break; } list = payload.GetElementsByTagName("interactivityType"); foreach (XmlNode node in list) { resource.Version.InteractivityType = TrimWhitespace(node.InnerText); resource.Version.InteractivityTypeId = 0; break; } try { if (resource.Version.RowId == null || resource.Version.RowId == new Guid(ImportServices.DEFAULT_GUID)) { if (AddResource(resource) == false) { //REJECT WHOLE RESOURCE!!! and end. Need to add to a summary count VerifyResourceVersionRecordExists(resource); return false; } } else { UpdateResource(resource); } // Now do name/value pairs AddKeywords(resource, record, payload, ref status); if (status != "") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, docId, url, ErrorType.Warning, ErrorRouting.Program, status); } AddSubjects(resource, payload); AddStandards(resource, payload); string ageRange = ""; bool hasAgeRange = false; bool hasGradeLevels = false; AddAgeRange(resource, payload, ref ageRange, ref hasAgeRange); string[] gradeLevels = AddGradeLevels(resource, payload, ref hasGradeLevels); if (hasAgeRange && !hasGradeLevels) { ConvertAgeToGrade(resource, ageRange, ref status); } if (hasGradeLevels && !hasAgeRange) { ConvertGradesToAgeRange(resource, gradeLevels); } AddAccessibility(resource, payload); AddAudiences(resource, payload); AddResourceFormats(resource, payload); AddResourceTypes(resource, payload); AddLanguages(resource, payload); AddEducationalUse(resource, payload); AddGroupType(resource, payload); AddItemType(resource, payload); AddAssessmentType(resource, payload); if (CheckForGoodLanguage(resource.Id) == true) { // Add to Elastic Search Index LearningRegistry.resourceIdList.Add(resource.Id); } else { // Deactivate resource resource.IsActive = false; importManager.ResourceSetActiveState( resource.Id, false ); } } catch (Exception ex) { } return isValid; }// LrmiMap protected void AddKeywords(Resource resource, XmlDocument record, XmlDocument payload, ref string status) { string internalStatus = ""; base.AddKeywords(resource, record, "keys", ref internalStatus); status += internalStatus; internalStatus = ""; base.AddKeywords(resource, payload, "keywords", ref internalStatus); status += internalStatus; } protected void AddAccessibility(Resource resource, XmlDocument payload) { string status = "successful"; // Accessibility Features XmlNodeList list = payload.GetElementsByTagName("accessibilityFeature"); foreach (XmlNode node in list) { ResourceChildItem feature = new ResourceChildItem(); feature.ResourceIntId = resource.Id; feature.OriginalValue = TrimWhitespace(node.InnerText); importManager.ImportAccessibilityFeature(feature); } // Accessibility Hazards list = payload.GetElementsByTagName("accessibilityHazard"); foreach (XmlNode node in list) { ResourceAccessibilityHazard hazard = new ResourceAccessibilityHazard(); hazard.ResourceIntId = resource.Id; hazard.OriginalValue = TrimWhitespace(node.InnerText); importManager.ImportAccessibilityHazard(hazard); } // Accessibility APIs list = payload.GetElementsByTagName("accessibilityAPI"); foreach (XmlNode node in list) { ResourceChildItem api = new ResourceChildItem(); api.ResourceIntId = resource.Id; api.OriginalValue = TrimWhitespace(node.InnerText); importManager.ImportAccessibilityApi(api); } // Accessibility Controls list = payload.GetElementsByTagName("accessibilityControl"); foreach (XmlNode node in list) { ResourceChildItem control = new ResourceChildItem(); control.ResourceIntId = resource.Id; control.OriginalValue = TrimWhitespace(node.InnerText); importManager.ImportAccessibilityControl(control); } } protected void AddSubjects(Resource resource, XmlDocument payload) { string status = "successful"; int nbrSubjects = 0; int maxSubjects = int.Parse(ConfigurationManager.AppSettings["maxSubjectsToProcess"]); // Process subjects from the schema.org "about" property. XmlNodeList list = payload.GetElementsByTagName("about"); XmlDocument doc2 = new XmlDocument(); XmlNodeList list2 = null; foreach (XmlNode node in list) { if (node.ChildNodes != null && node.ChildNodes.Count > 0) { doc2.LoadXml("<root>" + node.InnerXml + "</root>"); list2 = doc2.GetElementsByTagName("name"); } string subject = ""; if (list2 != null && list2.Count > 0) { subject = TrimWhitespace(list2[0].InnerText); } else { subject = TrimWhitespace(node.InnerText); } int amp = subject.IndexOf("&"); int scolon = subject.IndexOf(";"); if (scolon > -1 && amp == -1) { // Subject contains ; but does not contain & (ie contains semicolon but no HTML entities), so split by semicolon string[] subjectList = subject.Split(';'); foreach (string subjectItem in subjectList) { if (!SkipSubject(subjectItem)) { if (maxSubjects > 0 && nbrSubjects > maxSubjects) { break; } ResourceSubject resSubject = new ResourceSubject(); resSubject.ResourceIntId = resource.Id; resSubject.Subject = ApplySubjectEditRules(subjectItem); resSubject.Subject = TrimWhitespace(resSubject.Subject); status = importManager.CreateSubject(resSubject); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } nbrSubjects++; } } } else if (!SkipSubject(subject)) { if (maxSubjects > 0 && nbrSubjects > maxSubjects) { break; } subject = ApplySubjectEditRules(subject); subject = TrimWhitespace(subject); ResourceSubject resSubject = new ResourceSubject(); resSubject.ResourceIntId = resource.Id; resSubject.Subject = subject; status = importManager.CreateSubject(resSubject); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } } // Process subjects from the LRMI 1.1 alignmentObject property list = payload.GetElementsByTagName("educationalAlignment"); foreach (XmlNode node in list) { XmlDocument xdoc2 = new XmlDocument(); xdoc2.LoadXml(node.OuterXml); list2 = xdoc2.GetElementsByTagName("alignmentType"); foreach (XmlNode node2 in list2) { string alignmentType = TrimWhitespace(node2.InnerText); if (alignmentType.ToLower() == "educationalsubject") { XmlNodeList list3 = xdoc2.GetElementsByTagName("targetName"); if (list3.Count == 0) { list3 = xdoc2.GetElementsByTagName("targetDescription"); } foreach (XmlNode node3 in list3) { string subject = TrimWhitespace(node3.InnerText); int amp = subject.IndexOf("&"); int scolon = subject.IndexOf(";"); if (scolon > -1 && amp == -1) { // Subject contains ';' but does not contain '&' (ie contains semicolon but no HTML entities), so split by ';' string[] subjectList = subject.Split(';'); foreach (string subjectItem in subjectList) { if (!SkipSubject(subjectItem)) { if (maxSubjects > 0 && nbrSubjects > maxSubjects) { break; } ResourceSubject resSubject = new ResourceSubject(); resSubject.ResourceIntId = resource.Id; resSubject.Subject = ApplySubjectEditRules(subjectItem); resSubject.Subject = TrimWhitespace(resSubject.Subject); status = importManager.CreateSubject(resSubject); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } nbrSubjects++; } } } else if (!SkipSubject(subject)) { if (maxSubjects > 0 && nbrSubjects > maxSubjects) { break; } subject = ApplySubjectEditRules(subject); subject = TrimWhitespace(subject); ResourceSubject resSubject = new ResourceSubject(); resSubject.ResourceIntId = resource.Id; resSubject.Subject = subject; status = importManager.CreateSubject(resSubject); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } nbrSubjects++; } } } } } if (nbrSubjects > maxSubjects) { string message = string.Format("Number of subjects exceeds {0}. First {0} subjects processed, remainder ignored.", maxSubjects); reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Warning, ErrorRouting.Program, message); } }// AddSubjects protected void AddStandards(Resource resource, XmlDocument payload) { int maxDetailStandards = 0; if (!int.TryParse(ConfigurationManager.AppSettings["maxDetailedStandardsToProcess"], out maxDetailStandards)) { maxDetailStandards = 25; } if (maxDetailStandards == 0) { maxDetailStandards = int.MaxValue; } int nbrStandards = CountStandards(payload); bool hasTooManyStandards = false; if (nbrStandards > maxDetailStandards) { hasTooManyStandards = true; } XmlNodeList list = payload.GetElementsByTagName("educationalAlignment"); foreach (XmlNode node in list) { XmlDocument doc2 = new XmlDocument(); doc2.LoadXml(node.OuterXml); XmlNodeList list2 = doc2.GetElementsByTagName("targetUrl"); string targetUrl = ""; foreach (XmlNode node2 in list2) { string value = TrimWhitespace(node2.InnerText); if (value != null && value.Substring(0, 4).ToLower() == "http") { targetUrl = value; break; } } XmlNodeList list3 = doc2.GetElementsByTagName("targetName"); string targetName = ""; foreach (XmlNode node3 in list3) { string value = TrimWhitespace(node3.InnerText); if (value != null && value != string.Empty) { targetName = value; break; } } XmlNodeList list4 = doc2.GetElementsByTagName("alignmentType"); string alignmentType = ""; foreach (XmlNode node4 in list4) { string value = TrimWhitespace(node4.InnerText); if (value != null && value != string.Empty) { alignmentType = value; break; } } ProcessStandard(resource, targetUrl, targetName, alignmentType, hasTooManyStandards); }// foreach }// AddStandards protected int CountStandards(XmlDocument payload) { int nbrStandards = 0; XmlNodeList list = payload.GetElementsByTagName("educationalAlignment"); foreach (XmlNode node in list) { XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(node.OuterXml); XmlNodeList list2 = xdoc.GetElementsByTagName("alignmentType"); foreach (XmlNode node2 in list2) { string value = TrimWhitespace(node2.InnerText); if (value == "teaches" || value == "assesses" || value == "requires" || value == "") { nbrStandards++; } } } return nbrStandards; } protected void ProcessStandard(Resource resource, string targetUrl, string targetName, string alignmentType, bool processToDomain) { if (processToDomain && alignmentType.ToLower() != "educationlevel") { GetStandardsDomain(ref targetUrl, ref targetName); } string status = "successful"; ResourceStandard standard = new ResourceStandard(); standard.ResourceIntId = resource.Id; if (targetUrl.Length > 300) { standard.StandardUrl = targetUrl.Substring(0, 300); } else { standard.StandardUrl = targetUrl; } if (targetName.Length > 300) { standard.StandardNotationCode = targetName.Substring(0, 300); } else { standard.StandardNotationCode = targetName; } standard.AlignmentTypeValue = alignmentType; // educationLevel denotes grade level, which is not a standard - skip educationLevels! if (standard.AlignmentTypeValue.ToLower() != "educationlevel") { importManager.ImportStandard(standard, ref status); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } } protected void GetStandardsDomain(ref string targetUrl, ref string targetName) { StandardItem si = importManager.StandardItem_Get(0, "", targetName, ""); if (si == null) { si = importManager.StandardItem_Get(0, targetUrl, "", ""); if (si == null) { si = importManager.StandardItem_Get(0, "", "", targetUrl); } } if (si != null) { StandardItem itemToTest = importManager.StandardItem_Get(si.Id); while (itemToTest.ParentId != null && (itemToTest.LevelType.ToLower() != "domain" && itemToTest.LevelType.ToLower() != "domain?")) { itemToTest = importManager.StandardItem_Get(itemToTest.ParentId); } if (itemToTest.IsValid && (itemToTest.LevelType.ToLower() == "domain" || itemToTest.LevelType.ToLower() == "domain?")) { targetUrl = ""; targetName = itemToTest.NotationCode; } /* string[] dotNotationParts = si.NotationCode.Split('.'); // Search for domain string domainNotation = ""; bool foundDomain = false; for (int i = 0; i < dotNotationParts.Length; i++) { domainNotation = ""; for (int j = 0; j < (dotNotationParts.Length - i); j++) { domainNotation += dotNotationParts[j] + "."; } domainNotation = domainNotation.Substring(0, domainNotation.Length - 1); StandardItem itemToTest = sdm.StandardItem_Get(0, "", domainNotation, ""); if (itemToTest.IsValid && (itemToTest.LevelType.ToLower() == "domain" || itemToTest.LevelType.ToLower() == "domain?")) { targetUrl = ""; targetName = domainNotation; foundDomain = true; break; } if (foundDomain) { break; } } */ } } protected void AddAgeRange(Resource resource, XmlDocument payload, ref string ageRange, ref bool hasAgeRange) { string status = "successful"; hasAgeRange = false; XmlNodeList list = payload.GetElementsByTagName("typicalAgeRange"); foreach (XmlNode node in list) { ResourceAgeRange level = new ResourceAgeRange(); level.ResourceIntId = resource.Id; level.OriginalValue = CleanUpAgeRange(TrimWhitespace(node.InnerText)); int dashIndex = level.OriginalValue.IndexOf("-"); int length = level.OriginalValue.Length; if (length >= 3) { level.FromAge = int.Parse(level.OriginalValue.Substring(0, dashIndex)); level.ToAge = int.Parse(level.OriginalValue.Substring(dashIndex + 1, length - dashIndex - 1)); hasAgeRange = true; status = importManager.ImportAgeRange(level); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } } ResourceAgeRange finalLevel = importManager.GetAgeRangeByIntId(resource.Id); ageRange = finalLevel.FromAge.ToString() + "-" + finalLevel.ToAge.ToString(); }// AddAgeRange protected string[] AddGradeLevels(Resource resource, XmlDocument payload, ref bool hasGradeLevels) { string status = "successful"; ArrayList grades = new ArrayList(); hasGradeLevels = false; XmlNodeList list = payload.GetElementsByTagName("educationalAlignment"); foreach (XmlNode node in list) { XmlDocument xdoc2 = new XmlDocument(); xdoc2.LoadXml(node.OuterXml); XmlNodeList list2 = xdoc2.GetElementsByTagName("alignmentType"); foreach (XmlNode node2 in list2) { string alignmentType = TrimWhitespace(node2.InnerText); if (alignmentType.ToLower() == "educationlevel") { XmlNodeList list3 = xdoc2.GetElementsByTagName("targetName"); if (list3.Count == 0) { list3 = xdoc2.GetElementsByTagName("targetDescription"); } foreach (XmlNode node3 in list3) { hasGradeLevels = true; string[] gradez = TrimWhitespace(node3.InnerText).Split(','); foreach (string grade in gradez) { ResourceChildItem level = new ResourceChildItem(); level.ResourceIntId = resource.Id; level.OriginalValue = TrimWhitespace(grade); importManager.ImportGradeLevel(level, ref status); if (status != "successful") { auditReportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } grades.Add(level.OriginalValue); } } } } } if (grades.Count > 0) { string[] retVal = new string[grades.Count]; for (int i = 0; i < grades.Count; i++) { retVal[i] = grades[i].ToString(); } return retVal; } else { return new string[0]; } }// AddGradeLevels protected void AddAudiences(Resource resource, XmlDocument payload) { string status = "successful"; XmlNodeList list = payload.GetElementsByTagName("educationalRole"); foreach (XmlNode node in list) { ResourceChildItem audience = new ResourceChildItem(); audience.ResourceIntId = resource.Id; audience.OriginalValue = TrimWhitespace(node.InnerText); importManager.ImportAudience(audience, ref status); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } }// AddAudiences protected void AddResourceFormats(Resource resource, XmlDocument payload) { string status = "successful"; XmlNodeList list = payload.GetElementsByTagName("mediaType"); foreach (XmlNode node in list) { ResourceChildItem format = new ResourceChildItem(); format.ResourceIntId = resource.Id; format.OriginalValue = TrimWhitespace(node.InnerText); importManager.ImportFormat(format, ref status); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } if (resource.Version.Requirements == "" && format.OriginalValue.Length > 20) { resource.Version.Requirements = TrimWhitespace(node.InnerText); versionManager.Update(resource.Version); } } }// AddResourceFormats protected void AddResourceTypes(Resource resource, XmlDocument payload) { string status = "successful"; XmlNodeList list = payload.GetElementsByTagName("learningResourceType"); foreach (XmlNode node in list) { ResourceChildItem type = new ResourceChildItem(); type.ResourceIntId = resource.Id; type.OriginalValue = TrimWhitespace(node.InnerText); importManager.ImportType(type, ref status); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } }// AddResourceTypes protected void AddLanguages(Resource resource, XmlDocument payload) { string status = "successful"; XmlNodeList list = payload.GetElementsByTagName("inLanguage"); if (list == null || list.Count == 0) { list = payload.GetElementsByTagName("language"); } foreach (XmlNode node in list) { XmlDocument xdoc2 = new XmlDocument(); xdoc2.LoadXml(node.OuterXml); XmlNodeList list2 = xdoc2.GetElementsByTagName("name"); if (list2.Count == 0) { ResourceChildItem language = new ResourceChildItem(); language.ResourceIntId = resource.Id; language.OriginalValue = TrimWhitespace(node.InnerText); importManager.ImportLanguage(language, ref status); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } else { foreach (XmlNode node2 in list2) { ResourceChildItem language = new ResourceChildItem(); language.ResourceIntId = resource.Id; language.OriginalValue = TrimWhitespace(node2.InnerText); importManager.ImportLanguage(language, ref status); if (status != "successful") { reportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } }// foreach node2 in list2 } }// foreach node in list resource.Language = importManager.SelectLanguage(resource.Id, ""); if (resource.Language == null || resource.Language.Count == 0) { // If no languages found, assume English but log it. ResourceChildItem language = new ResourceChildItem(); language.ResourceIntId = resource.Id; language.OriginalValue = "English"; importManager.ImportLanguage(language, ref status); if (status == "successful") { auditReportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Warning, ErrorRouting.Program, "No language was found for resource. English language assumed. Please verify this resource's language."); } else { auditReportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } }// AddLanguages protected void AddEducationalUse(Resource resource, XmlDocument payload) { string status = "successful"; XmlNodeList list = payload.GetElementsByTagName("educationalUse"); foreach (XmlNode node in list) { ResourceChildItem edUse = new ResourceChildItem(); edUse.ResourceIntId = resource.Id; edUse.OriginalValue = TrimWhitespace(node.InnerText); importManager.ImportEducationalUse(edUse, ref status); if (status != "successful") { auditReportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } }// AddEducationalUse protected void AddGroupType(Resource resource, XmlDocument payload) { string status = "successful"; XmlNodeList list = payload.GetElementsByTagName("groupType"); foreach (XmlNode node in list) { ResourceChildItem groupType = new ResourceChildItem(); groupType.ResourceIntId = resource.Id; groupType.OriginalValue = TrimWhitespace(node.InnerText); importManager.ImportGroupType(groupType, ref status); if (status != "successful") { auditReportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } status = "successful"; } }// AddGroupType protected void AddItemType(Resource resource, XmlDocument payload) { string status = "successful"; XmlNodeList list = payload.GetElementsByTagName("itemType"); foreach (XmlNode node in list) { ResourceChildItem itemType = new ResourceChildItem(); itemType.ResourceIntId = resource.Id; itemType.OriginalValue = TrimWhitespace(node.InnerText); status = importManager.ImportItemType(itemType); if (status != "successful") { auditReportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } status = "successful"; } }// AddItemType protected void AddAssessmentType(Resource resource, XmlDocument payload) { string status = "successful"; XmlNodeList list = payload.GetElementsByTagName("assessmentType"); foreach (XmlNode node in list) { ResourceChildItem asmtType = new ResourceChildItem(); asmtType.ResourceIntId = resource.Id; asmtType.OriginalValue = TrimWhitespace(node.InnerText); status = importManager.ImportAssessmentType(asmtType); if (status != "successful") { auditReportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } status = "successful"; } }// AddAssessmentType } }
/* * 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 Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using System; using System.Collections; using System.Collections.Generic; using System.Net; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Server.Handlers.Hypergrid { public class UserAgentServerConnector : ServiceConnector { // private static readonly ILog m_log = // LogManager.GetLogger( // MethodBase.GetCurrentMethod().DeclaringType); private IUserAgentService m_HomeUsersService; public IUserAgentService HomeUsersService { get { return m_HomeUsersService; } } private string[] m_AuthorizedCallers; private bool m_VerifyCallers = false; public UserAgentServerConnector(IConfigSource config, IHttpServer server) : this(config, server, (IFriendsSimConnector)null) { } public UserAgentServerConnector(IConfigSource config, IHttpServer server, string configName) : this(config, server) { } public UserAgentServerConnector(IConfigSource config, IHttpServer server, IFriendsSimConnector friendsConnector) : base(config, server, String.Empty) { IConfig gridConfig = config.Configs["UserAgentService"]; if (gridConfig != null) { string serviceDll = gridConfig.GetString("LocalServiceModule", string.Empty); Object[] args = new Object[] { config, friendsConnector }; m_HomeUsersService = ServerUtils.LoadPlugin<IUserAgentService>(serviceDll, args); } if (m_HomeUsersService == null) throw new Exception("UserAgent server connector cannot proceed because of missing service"); string loginServerIP = gridConfig.GetString("LoginServerIP", "127.0.0.1"); bool proxy = gridConfig.GetBoolean("HasProxy", false); m_VerifyCallers = gridConfig.GetBoolean("VerifyCallers", false); string csv = gridConfig.GetString("AuthorizedCallers", "127.0.0.1"); csv = csv.Replace(" ", ""); m_AuthorizedCallers = csv.Split(','); server.AddXmlRPCHandler("agent_is_coming_home", AgentIsComingHome, false); server.AddXmlRPCHandler("get_home_region", GetHomeRegion, false); server.AddXmlRPCHandler("verify_agent", VerifyAgent, false); server.AddXmlRPCHandler("verify_client", VerifyClient, false); server.AddXmlRPCHandler("logout_agent", LogoutAgent, false); server.AddXmlRPCHandler("status_notification", StatusNotification, false); server.AddXmlRPCHandler("get_online_friends", GetOnlineFriends, false); server.AddXmlRPCHandler("get_user_info", GetUserInfo, false); server.AddXmlRPCHandler("get_server_urls", GetServerURLs, false); server.AddXmlRPCHandler("locate_user", LocateUser, false); server.AddXmlRPCHandler("get_uui", GetUUI, false); server.AddXmlRPCHandler("get_uuid", GetUUID, false); server.AddStreamHandler(new HomeAgentHandler(m_HomeUsersService, loginServerIP, proxy)); } public XmlRpcResponse GetHomeRegion(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)request.Params[0]; //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; string userID_str = (string)requestData["userID"]; UUID userID = UUID.Zero; UUID.TryParse(userID_str, out userID); Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY; GridRegion regInfo = m_HomeUsersService.GetHomeRegion(userID, out position, out lookAt); Hashtable hash = new Hashtable(); if (regInfo == null) hash["result"] = "false"; else { hash["result"] = "true"; hash["uuid"] = regInfo.RegionID.ToString(); hash["x"] = regInfo.RegionLocX.ToString(); hash["y"] = regInfo.RegionLocY.ToString(); hash["size_x"] = regInfo.RegionSizeX.ToString(); hash["size_y"] = regInfo.RegionSizeY.ToString(); hash["region_name"] = regInfo.RegionName; hash["hostname"] = regInfo.ExternalHostName; hash["http_port"] = regInfo.HttpPort.ToString(); hash["internal_port"] = regInfo.InternalEndPoint.Port.ToString(); hash["position"] = position.ToString(); hash["lookAt"] = lookAt.ToString(); } XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } public XmlRpcResponse AgentIsComingHome(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)request.Params[0]; //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; string sessionID_str = (string)requestData["sessionID"]; UUID sessionID = UUID.Zero; UUID.TryParse(sessionID_str, out sessionID); string gridName = (string)requestData["externalName"]; bool success = m_HomeUsersService.IsAgentComingHome(sessionID, gridName); Hashtable hash = new Hashtable(); hash["result"] = success.ToString(); XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } public XmlRpcResponse VerifyAgent(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)request.Params[0]; //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; string sessionID_str = (string)requestData["sessionID"]; UUID sessionID = UUID.Zero; UUID.TryParse(sessionID_str, out sessionID); string token = (string)requestData["token"]; bool success = m_HomeUsersService.VerifyAgent(sessionID, token); Hashtable hash = new Hashtable(); hash["result"] = success.ToString(); XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } public XmlRpcResponse VerifyClient(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)request.Params[0]; //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; string sessionID_str = (string)requestData["sessionID"]; UUID sessionID = UUID.Zero; UUID.TryParse(sessionID_str, out sessionID); string token = (string)requestData["token"]; bool success = m_HomeUsersService.VerifyClient(sessionID, token); Hashtable hash = new Hashtable(); hash["result"] = success.ToString(); XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } public XmlRpcResponse LogoutAgent(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)request.Params[0]; //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; string sessionID_str = (string)requestData["sessionID"]; UUID sessionID = UUID.Zero; UUID.TryParse(sessionID_str, out sessionID); string userID_str = (string)requestData["userID"]; UUID userID = UUID.Zero; UUID.TryParse(userID_str, out userID); m_HomeUsersService.LogoutAgent(userID, sessionID); Hashtable hash = new Hashtable(); hash["result"] = "true"; XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } public XmlRpcResponse StatusNotification(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable hash = new Hashtable(); hash["result"] = "false"; Hashtable requestData = (Hashtable)request.Params[0]; //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; if (requestData.ContainsKey("userID") && requestData.ContainsKey("online")) { string userID_str = (string)requestData["userID"]; UUID userID = UUID.Zero; UUID.TryParse(userID_str, out userID); List<string> ids = new List<string>(); foreach (object key in requestData.Keys) { if (key is string && ((string)key).StartsWith("friend_") && requestData[key] != null) ids.Add(requestData[key].ToString()); } bool online = false; bool.TryParse(requestData["online"].ToString(), out online); // let's spawn a thread for this, because it may take a long time... List<UUID> friendsOnline = m_HomeUsersService.StatusNotification(ids, userID, online); if (friendsOnline.Count > 0) { int i = 0; foreach (UUID id in friendsOnline) { hash["friend_" + i.ToString()] = id.ToString(); i++; } } else hash["result"] = "No Friends Online"; } XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } [Obsolete] public XmlRpcResponse GetOnlineFriends(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable hash = new Hashtable(); Hashtable requestData = (Hashtable)request.Params[0]; //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; if (requestData.ContainsKey("userID")) { string userID_str = (string)requestData["userID"]; UUID userID = UUID.Zero; UUID.TryParse(userID_str, out userID); List<string> ids = new List<string>(); foreach (object key in requestData.Keys) { if (key is string && ((string)key).StartsWith("friend_") && requestData[key] != null) ids.Add(requestData[key].ToString()); } //List<UUID> online = m_HomeUsersService.GetOnlineFriends(userID, ids); //if (online.Count > 0) //{ // int i = 0; // foreach (UUID id in online) // { // hash["friend_" + i.ToString()] = id.ToString(); // i++; // } //} //else // hash["result"] = "No Friends Online"; } XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } public XmlRpcResponse GetUserInfo(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable hash = new Hashtable(); Hashtable requestData = (Hashtable)request.Params[0]; // This needs checking! if (requestData.ContainsKey("userID")) { string userID_str = (string)requestData["userID"]; UUID userID = UUID.Zero; UUID.TryParse(userID_str, out userID); //int userFlags = m_HomeUsersService.GetUserFlags(userID); Dictionary<string,object> userInfo = m_HomeUsersService.GetUserInfo(userID); if (userInfo.Count > 0) { foreach (KeyValuePair<string, object> kvp in userInfo) { hash[kvp.Key] = kvp.Value; } } else { hash["result"] = "failure"; } } XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } public XmlRpcResponse GetServerURLs(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable hash = new Hashtable(); Hashtable requestData = (Hashtable)request.Params[0]; //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; if (requestData.ContainsKey("userID")) { string userID_str = (string)requestData["userID"]; UUID userID = UUID.Zero; UUID.TryParse(userID_str, out userID); Dictionary<string, object> serverURLs = m_HomeUsersService.GetServerURLs(userID); if (serverURLs.Count > 0) { foreach (KeyValuePair<string, object> kvp in serverURLs) hash["SRV_" + kvp.Key] = kvp.Value.ToString(); } else hash["result"] = "No Service URLs"; } XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } /// <summary> /// Locates the user. /// This is a sensitive operation, only authorized IP addresses can perform it. /// </summary> /// <param name="request"></param> /// <param name="remoteClient"></param> /// <returns></returns> public XmlRpcResponse LocateUser(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable hash = new Hashtable(); bool authorized = true; if (m_VerifyCallers) { authorized = false; foreach (string s in m_AuthorizedCallers) if (s == remoteClient.Address.ToString()) { authorized = true; break; } } if (authorized) { Hashtable requestData = (Hashtable)request.Params[0]; //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; if (requestData.ContainsKey("userID")) { string userID_str = (string)requestData["userID"]; UUID userID = UUID.Zero; UUID.TryParse(userID_str, out userID); string url = m_HomeUsersService.LocateUser(userID); if (url != string.Empty) hash["URL"] = url; else hash["result"] = "Unable to locate user"; } } XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } /// <summary> /// Returns the UUI of a user given a UUID. /// </summary> /// <param name="request"></param> /// <param name="remoteClient"></param> /// <returns></returns> public XmlRpcResponse GetUUI(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable hash = new Hashtable(); Hashtable requestData = (Hashtable)request.Params[0]; //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; if (requestData.ContainsKey("userID") && requestData.ContainsKey("targetUserID")) { string userID_str = (string)requestData["userID"]; UUID userID = UUID.Zero; UUID.TryParse(userID_str, out userID); string tuserID_str = (string)requestData["targetUserID"]; UUID targetUserID = UUID.Zero; UUID.TryParse(tuserID_str, out targetUserID); string uui = m_HomeUsersService.GetUUI(userID, targetUserID); if (uui != string.Empty) hash["UUI"] = uui; else hash["result"] = "User unknown"; } XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } /// <summary> /// Gets the UUID of a user given First name, Last name. /// </summary> /// <param name="request"></param> /// <param name="remoteClient"></param> /// <returns></returns> public XmlRpcResponse GetUUID(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable hash = new Hashtable(); Hashtable requestData = (Hashtable)request.Params[0]; //string host = (string)requestData["host"]; //string portstr = (string)requestData["port"]; if (requestData.ContainsKey("first") && requestData.ContainsKey("last")) { string first = (string)requestData["first"]; string last = (string)requestData["last"]; UUID uuid = m_HomeUsersService.GetUUID(first, last); hash["UUID"] = uuid.ToString(); } XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; } } }
// 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.Globalization; using System.IO; using System.Reflection; using System.Diagnostics; namespace System.Runtime.Serialization.Formatters.Binary { internal sealed class ObjectReader { // System.Serializer information internal Stream _stream; internal ISurrogateSelector _surrogates; internal StreamingContext _context; internal ObjectManager _objectManager; internal InternalFE _formatterEnums; internal SerializationBinder _binder; // Top object and headers internal long _topId; internal bool _isSimpleAssembly = false; internal object _topObject; internal SerObjectInfoInit _serObjectInfoInit; internal IFormatterConverter _formatterConverter; // Stack of Object ParseRecords internal SerStack _stack; // ValueType Fixup Stack private SerStack _valueFixupStack; // Cross AppDomain internal object[] _crossAppDomainArray; //Set by the BinaryFormatter //MethodCall and MethodReturn are handled special for perf reasons private bool _fullDeserialization; private SerStack ValueFixupStack => _valueFixupStack ?? (_valueFixupStack = new SerStack("ValueType Fixup Stack")); // Older formatters generate ids for valuetypes using a different counter than ref types. Newer ones use // a single counter, only value types have a negative value. Need a way to handle older formats. private const int ThresholdForValueTypeIds = int.MaxValue; private bool _oldFormatDetected = false; private IntSizedArray _valTypeObjectIdTable; private readonly NameCache _typeCache = new NameCache(); internal object TopObject { get { return _topObject; } set { _topObject = value; if (_objectManager != null) { _objectManager.TopObject = value; } } } internal ObjectReader(Stream stream, ISurrogateSelector selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder binder) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } _stream = stream; _surrogates = selector; _context = context; _binder = binder; _formatterEnums = formatterEnums; } internal object Deserialize(BinaryParser serParser, bool fCheck) { if (serParser == null) { throw new ArgumentNullException(nameof(serParser)); } _fullDeserialization = false; TopObject = null; _topId = 0; _isSimpleAssembly = (_formatterEnums._assemblyFormat == FormatterAssemblyStyle.Simple); if (_fullDeserialization) { // Reinitialize _objectManager = new ObjectManager(_surrogates, _context, false, false); _serObjectInfoInit = new SerObjectInfoInit(); } // Will call back to ParseObject, ParseHeader for each object found serParser.Run(); if (_fullDeserialization) { _objectManager.DoFixups(); } if (TopObject == null) { throw new SerializationException(SR.Serialization_TopObject); } //if TopObject has a surrogate then the actual object may be changed during special fixup //So refresh it using topID. if (HasSurrogate(TopObject.GetType()) && _topId != 0)//Not yet resolved { TopObject = _objectManager.GetObject(_topId); } if (TopObject is IObjectReference) { TopObject = ((IObjectReference)TopObject).GetRealObject(_context); } if (_fullDeserialization) { _objectManager.RaiseDeserializationEvent(); // This will raise both IDeserialization and [OnDeserialized] events } return TopObject; } private bool HasSurrogate(Type t) { ISurrogateSelector ignored; return _surrogates != null && _surrogates.GetSurrogate(t, _context, out ignored) != null; } private void CheckSerializable(Type t) { if (!t.IsSerializable && !HasSurrogate(t)) { throw new SerializationException(string.Format(CultureInfo.InvariantCulture, SR.Serialization_NonSerType, t.FullName, t.Assembly.FullName)); } } private void InitFullDeserialization() { _fullDeserialization = true; _stack = new SerStack("ObjectReader Object Stack"); _objectManager = new ObjectManager(_surrogates, _context, false, false); if (_formatterConverter == null) { _formatterConverter = new FormatterConverter(); } } internal object CrossAppDomainArray(int index) { Debug.Assert(index < _crossAppDomainArray.Length, "[System.Runtime.Serialization.Formatters.BinaryObjectReader index out of range for CrossAppDomainArray]"); return _crossAppDomainArray[index]; } internal ReadObjectInfo CreateReadObjectInfo(Type objectType) { return ReadObjectInfo.Create(objectType, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly); } internal ReadObjectInfo CreateReadObjectInfo(Type objectType, string[] memberNames, Type[] memberTypes) { return ReadObjectInfo.Create(objectType, memberNames, memberTypes, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly); } internal void Parse(ParseRecord pr) { switch (pr._parseTypeEnum) { case InternalParseTypeE.SerializedStreamHeader: ParseSerializedStreamHeader(pr); break; case InternalParseTypeE.SerializedStreamHeaderEnd: ParseSerializedStreamHeaderEnd(pr); break; case InternalParseTypeE.Object: ParseObject(pr); break; case InternalParseTypeE.ObjectEnd: ParseObjectEnd(pr); break; case InternalParseTypeE.Member: ParseMember(pr); break; case InternalParseTypeE.MemberEnd: ParseMemberEnd(pr); break; case InternalParseTypeE.Body: case InternalParseTypeE.BodyEnd: case InternalParseTypeE.Envelope: case InternalParseTypeE.EnvelopeEnd: break; case InternalParseTypeE.Empty: default: throw new SerializationException(SR.Format(SR.Serialization_XMLElement, pr._name)); } } // Styled ParseError output private void ParseError(ParseRecord processing, ParseRecord onStack) { throw new SerializationException(SR.Format(SR.Serialization_ParseError, onStack._name + " " + onStack._parseTypeEnum + " " + processing._name + " " + processing._parseTypeEnum)); } // Parse the SerializedStreamHeader element. This is the first element in the stream if present private void ParseSerializedStreamHeader(ParseRecord pr) => _stack.Push(pr); // Parse the SerializedStreamHeader end element. This is the last element in the stream if present private void ParseSerializedStreamHeaderEnd(ParseRecord pr) => _stack.Pop(); // New object encountered in stream private void ParseObject(ParseRecord pr) { if (!_fullDeserialization) { InitFullDeserialization(); } if (pr._objectPositionEnum == InternalObjectPositionE.Top) { _topId = pr._objectId; } if (pr._parseTypeEnum == InternalParseTypeE.Object) { _stack.Push(pr); // Nested objects member names are already on stack } if (pr._objectTypeEnum == InternalObjectTypeE.Array) { ParseArray(pr); return; } // If the Type is null, this means we have a typeload issue // mark the object with TypeLoadExceptionHolder if (pr._dtType == null) { pr._newObj = new TypeLoadExceptionHolder(pr._keyDt); return; } if (ReferenceEquals(pr._dtType, Converter.s_typeofString)) { // String as a top level object if (pr._value != null) { pr._newObj = pr._value; if (pr._objectPositionEnum == InternalObjectPositionE.Top) { TopObject = pr._newObj; return; } else { _stack.Pop(); RegisterObject(pr._newObj, pr, (ParseRecord)_stack.Peek()); return; } } else { // xml Doesn't have the value until later return; } } else { CheckSerializable(pr._dtType); pr._newObj = FormatterServices.GetUninitializedObject(pr._dtType); // Run the OnDeserializing methods _objectManager.RaiseOnDeserializingEvent(pr._newObj); } if (pr._newObj == null) { throw new SerializationException(SR.Format(SR.Serialization_TopObjectInstantiate, pr._dtType)); } if (pr._objectPositionEnum == InternalObjectPositionE.Top) { TopObject = pr._newObj; } if (pr._objectInfo == null) { pr._objectInfo = ReadObjectInfo.Create(pr._dtType, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly); } } // End of object encountered in stream private void ParseObjectEnd(ParseRecord pr) { ParseRecord objectPr = (ParseRecord)_stack.Peek() ?? pr; if (objectPr._objectPositionEnum == InternalObjectPositionE.Top) { if (ReferenceEquals(objectPr._dtType, Converter.s_typeofString)) { objectPr._newObj = objectPr._value; TopObject = objectPr._newObj; return; } } _stack.Pop(); ParseRecord parentPr = (ParseRecord)_stack.Peek(); if (objectPr._newObj == null) { return; } if (objectPr._objectTypeEnum == InternalObjectTypeE.Array) { if (objectPr._objectPositionEnum == InternalObjectPositionE.Top) { TopObject = objectPr._newObj; } RegisterObject(objectPr._newObj, objectPr, parentPr); return; } objectPr._objectInfo.PopulateObjectMembers(objectPr._newObj, objectPr._memberData); // Registration is after object is populated if ((!objectPr._isRegistered) && (objectPr._objectId > 0)) { RegisterObject(objectPr._newObj, objectPr, parentPr); } if (objectPr._isValueTypeFixup) { ValueFixup fixup = (ValueFixup)ValueFixupStack.Pop(); //Value fixup fixup.Fixup(objectPr, parentPr); // Value fixup } if (objectPr._objectPositionEnum == InternalObjectPositionE.Top) { TopObject = objectPr._newObj; } objectPr._objectInfo.ObjectEnd(); } // Array object encountered in stream private void ParseArray(ParseRecord pr) { long genId = pr._objectId; if (pr._arrayTypeEnum == InternalArrayTypeE.Base64) { // ByteArray pr._newObj = pr._value.Length > 0 ? Convert.FromBase64String(pr._value) : Array.Empty<byte>(); if (_stack.Peek() == pr) { _stack.Pop(); } if (pr._objectPositionEnum == InternalObjectPositionE.Top) { TopObject = pr._newObj; } ParseRecord parentPr = (ParseRecord)_stack.Peek(); // Base64 can be registered at this point because it is populated RegisterObject(pr._newObj, pr, parentPr); } else if ((pr._newObj != null) && Converter.IsWriteAsByteArray(pr._arrayElementTypeCode)) { // Primtive typed Array has already been read if (pr._objectPositionEnum == InternalObjectPositionE.Top) { TopObject = pr._newObj; } ParseRecord parentPr = (ParseRecord)_stack.Peek(); // Primitive typed array can be registered at this point because it is populated RegisterObject(pr._newObj, pr, parentPr); } else if ((pr._arrayTypeEnum == InternalArrayTypeE.Jagged) || (pr._arrayTypeEnum == InternalArrayTypeE.Single)) { // Multidimensional jagged array or single array bool couldBeValueType = true; if ((pr._lowerBoundA == null) || (pr._lowerBoundA[0] == 0)) { if (ReferenceEquals(pr._arrayElementType, Converter.s_typeofString)) { pr._objectA = new string[pr._lengthA[0]]; pr._newObj = pr._objectA; couldBeValueType = false; } else if (ReferenceEquals(pr._arrayElementType, Converter.s_typeofObject)) { pr._objectA = new object[pr._lengthA[0]]; pr._newObj = pr._objectA; couldBeValueType = false; } else if (pr._arrayElementType != null) { pr._newObj = Array.CreateInstance(pr._arrayElementType, pr._lengthA[0]); } pr._isLowerBound = false; } else { if (pr._arrayElementType != null) { pr._newObj = Array.CreateInstance(pr._arrayElementType, pr._lengthA, pr._lowerBoundA); } pr._isLowerBound = true; } if (pr._arrayTypeEnum == InternalArrayTypeE.Single) { if (!pr._isLowerBound && (Converter.IsWriteAsByteArray(pr._arrayElementTypeCode))) { pr._primitiveArray = new PrimitiveArray(pr._arrayElementTypeCode, (Array)pr._newObj); } else if (couldBeValueType && pr._arrayElementType != null) { if (!pr._arrayElementType.IsValueType && !pr._isLowerBound) { pr._objectA = (object[])pr._newObj; } } } pr._indexMap = new int[1]; } else if (pr._arrayTypeEnum == InternalArrayTypeE.Rectangular) { // Rectangle array pr._isLowerBound = false; if (pr._lowerBoundA != null) { for (int i = 0; i < pr._rank; i++) { if (pr._lowerBoundA[i] != 0) { pr._isLowerBound = true; } } } if (pr._arrayElementType != null) { pr._newObj = !pr._isLowerBound ? Array.CreateInstance(pr._arrayElementType, pr._lengthA) : Array.CreateInstance(pr._arrayElementType, pr._lengthA, pr._lowerBoundA); } // Calculate number of items int sum = 1; for (int i = 0; i < pr._rank; i++) { sum = sum * pr._lengthA[i]; } pr._indexMap = new int[pr._rank]; pr._rectangularMap = new int[pr._rank]; pr._linearlength = sum; } else { throw new SerializationException(SR.Format(SR.Serialization_ArrayType, pr._arrayTypeEnum)); } } // Builds a map for each item in an incoming rectangle array. The map specifies where the item is placed in the output Array Object private void NextRectangleMap(ParseRecord pr) { // For each invocation, calculate the next rectangular array position // example // indexMap 0 [0,0,0] // indexMap 1 [0,0,1] // indexMap 2 [0,0,2] // indexMap 3 [0,0,3] // indexMap 4 [0,1,0] for (int irank = pr._rank - 1; irank > -1; irank--) { // Find the current or lower dimension which can be incremented. if (pr._rectangularMap[irank] < pr._lengthA[irank] - 1) { // The current dimension is at maximum. Increase the next lower dimension by 1 pr._rectangularMap[irank]++; if (irank < pr._rank - 1) { // The current dimension and higher dimensions are zeroed. for (int i = irank + 1; i < pr._rank; i++) { pr._rectangularMap[i] = 0; } } Array.Copy(pr._rectangularMap, 0, pr._indexMap, 0, pr._rank); break; } } } // Array object item encountered in stream private void ParseArrayMember(ParseRecord pr) { ParseRecord objectPr = (ParseRecord)_stack.Peek(); // Set up for inserting value into correct array position if (objectPr._arrayTypeEnum == InternalArrayTypeE.Rectangular) { if (objectPr._memberIndex > 0) { NextRectangleMap(objectPr); // Rectangle array, calculate position in array } if (objectPr._isLowerBound) { for (int i = 0; i < objectPr._rank; i++) { objectPr._indexMap[i] = objectPr._rectangularMap[i] + objectPr._lowerBoundA[i]; } } } else { objectPr._indexMap[0] = !objectPr._isLowerBound ? objectPr._memberIndex : // Zero based array objectPr._lowerBoundA[0] + objectPr._memberIndex; // Lower Bound based array } // Set Array element according to type of element if (pr._memberValueEnum == InternalMemberValueE.Reference) { // Object Reference // See if object has already been instantiated object refObj = _objectManager.GetObject(pr._idRef); if (refObj == null) { // Object not instantiated // Array fixup manager int[] fixupIndex = new int[objectPr._rank]; Array.Copy(objectPr._indexMap, 0, fixupIndex, 0, objectPr._rank); _objectManager.RecordArrayElementFixup(objectPr._objectId, fixupIndex, pr._idRef); } else { if (objectPr._objectA != null) { objectPr._objectA[objectPr._indexMap[0]] = refObj; } else { ((Array)objectPr._newObj).SetValue(refObj, objectPr._indexMap); // Object has been instantiated } } } else if (pr._memberValueEnum == InternalMemberValueE.Nested) { //Set up dtType for ParseObject if (pr._dtType == null) { pr._dtType = objectPr._arrayElementType; } ParseObject(pr); _stack.Push(pr); if (objectPr._arrayElementType != null) { if ((objectPr._arrayElementType.IsValueType) && (pr._arrayElementTypeCode == InternalPrimitiveTypeE.Invalid)) { pr._isValueTypeFixup = true; //Valuefixup ValueFixupStack.Push(new ValueFixup((Array)objectPr._newObj, objectPr._indexMap)); //valuefixup } else { if (objectPr._objectA != null) { objectPr._objectA[objectPr._indexMap[0]] = pr._newObj; } else { ((Array)objectPr._newObj).SetValue(pr._newObj, objectPr._indexMap); } } } } else if (pr._memberValueEnum == InternalMemberValueE.InlineValue) { if ((ReferenceEquals(objectPr._arrayElementType, Converter.s_typeofString)) || (ReferenceEquals(pr._dtType, Converter.s_typeofString))) { // String in either a string array, or a string element of an object array ParseString(pr, objectPr); if (objectPr._objectA != null) { objectPr._objectA[objectPr._indexMap[0]] = pr._value; } else { ((Array)objectPr._newObj).SetValue(pr._value, objectPr._indexMap); } } else if (objectPr._isArrayVariant) { // Array of type object if (pr._keyDt == null) { throw new SerializationException(SR.Serialization_ArrayTypeObject); } object var = null; if (ReferenceEquals(pr._dtType, Converter.s_typeofString)) { ParseString(pr, objectPr); var = pr._value; } else if (ReferenceEquals(pr._dtTypeCode, InternalPrimitiveTypeE.Invalid)) { CheckSerializable(pr._dtType); // Not nested and invalid, so it is an empty object var = FormatterServices.GetUninitializedObject(pr._dtType); } else { var = pr._varValue != null ? pr._varValue : Converter.FromString(pr._value, pr._dtTypeCode); } if (objectPr._objectA != null) { objectPr._objectA[objectPr._indexMap[0]] = var; } else { ((Array)objectPr._newObj).SetValue(var, objectPr._indexMap); // Primitive type } } else { // Primitive type if (objectPr._primitiveArray != null) { // Fast path for Soap primitive arrays. Binary was handled in the BinaryParser objectPr._primitiveArray.SetValue(pr._value, objectPr._indexMap[0]); } else { object var = pr._varValue != null ? pr._varValue : Converter.FromString(pr._value, objectPr._arrayElementTypeCode); if (objectPr._objectA != null) { objectPr._objectA[objectPr._indexMap[0]] = var; } else { ((Array)objectPr._newObj).SetValue(var, objectPr._indexMap); // Primitive type } } } } else if (pr._memberValueEnum == InternalMemberValueE.Null) { objectPr._memberIndex += pr._consecutiveNullArrayEntryCount - 1; //also incremented again below } else { ParseError(pr, objectPr); } objectPr._memberIndex++; } private void ParseArrayMemberEnd(ParseRecord pr) { // If this is a nested array object, then pop the stack if (pr._memberValueEnum == InternalMemberValueE.Nested) { ParseObjectEnd(pr); } } // Object member encountered in stream private void ParseMember(ParseRecord pr) { ParseRecord objectPr = (ParseRecord)_stack.Peek(); string objName = objectPr?._name; switch (pr._memberTypeEnum) { case InternalMemberTypeE.Item: ParseArrayMember(pr); return; case InternalMemberTypeE.Field: break; } //if ((pr.PRdtType == null) && !objectPr.PRobjectInfo.isSi) if (pr._dtType == null && objectPr._objectInfo._isTyped) { pr._dtType = objectPr._objectInfo.GetType(pr._name); if (pr._dtType != null) { pr._dtTypeCode = Converter.ToCode(pr._dtType); } } if (pr._memberValueEnum == InternalMemberValueE.Null) { // Value is Null objectPr._objectInfo.AddValue(pr._name, null, ref objectPr._si, ref objectPr._memberData); } else if (pr._memberValueEnum == InternalMemberValueE.Nested) { ParseObject(pr); _stack.Push(pr); if ((pr._objectInfo != null) && pr._objectInfo._objectType != null && (pr._objectInfo._objectType.IsValueType)) { pr._isValueTypeFixup = true; //Valuefixup ValueFixupStack.Push(new ValueFixup(objectPr._newObj, pr._name, objectPr._objectInfo));//valuefixup } else { objectPr._objectInfo.AddValue(pr._name, pr._newObj, ref objectPr._si, ref objectPr._memberData); } } else if (pr._memberValueEnum == InternalMemberValueE.Reference) { // See if object has already been instantiated object refObj = _objectManager.GetObject(pr._idRef); if (refObj == null) { objectPr._objectInfo.AddValue(pr._name, null, ref objectPr._si, ref objectPr._memberData); objectPr._objectInfo.RecordFixup(objectPr._objectId, pr._name, pr._idRef); // Object not instantiated } else { objectPr._objectInfo.AddValue(pr._name, refObj, ref objectPr._si, ref objectPr._memberData); } } else if (pr._memberValueEnum == InternalMemberValueE.InlineValue) { // Primitive type or String if (ReferenceEquals(pr._dtType, Converter.s_typeofString)) { ParseString(pr, objectPr); objectPr._objectInfo.AddValue(pr._name, pr._value, ref objectPr._si, ref objectPr._memberData); } else if (pr._dtTypeCode == InternalPrimitiveTypeE.Invalid) { // The member field was an object put the value is Inline either bin.Base64 or invalid if (pr._arrayTypeEnum == InternalArrayTypeE.Base64) { objectPr._objectInfo.AddValue(pr._name, Convert.FromBase64String(pr._value), ref objectPr._si, ref objectPr._memberData); } else if (ReferenceEquals(pr._dtType, Converter.s_typeofObject)) { throw new SerializationException(SR.Format(SR.Serialization_TypeMissing, pr._name)); } else { ParseString(pr, objectPr); // Register the object if it has an objectId // Object Class with no memberInfo data // only special case where AddValue is needed? if (ReferenceEquals(pr._dtType, Converter.s_typeofSystemVoid)) { objectPr._objectInfo.AddValue(pr._name, pr._dtType, ref objectPr._si, ref objectPr._memberData); } else if (objectPr._objectInfo._isSi) { // ISerializable are added as strings, the conversion to type is done by the // ISerializable object objectPr._objectInfo.AddValue(pr._name, pr._value, ref objectPr._si, ref objectPr._memberData); } } } else { object var = pr._varValue != null ? pr._varValue : Converter.FromString(pr._value, pr._dtTypeCode); objectPr._objectInfo.AddValue(pr._name, var, ref objectPr._si, ref objectPr._memberData); } } else { ParseError(pr, objectPr); } } // Object member end encountered in stream private void ParseMemberEnd(ParseRecord pr) { switch (pr._memberTypeEnum) { case InternalMemberTypeE.Item: ParseArrayMemberEnd(pr); return; case InternalMemberTypeE.Field: if (pr._memberValueEnum == InternalMemberValueE.Nested) { ParseObjectEnd(pr); } break; default: ParseError(pr, (ParseRecord)_stack.Peek()); break; } } // Processes a string object by getting an internal ID for it and registering it with the objectManager private void ParseString(ParseRecord pr, ParseRecord parentPr) { // Process String class if ((!pr._isRegistered) && (pr._objectId > 0)) { // String is treated as an object if it has an id //m_objectManager.RegisterObject(pr.PRvalue, pr.PRobjectId); RegisterObject(pr._value, pr, parentPr, true); } } private void RegisterObject(object obj, ParseRecord pr, ParseRecord objectPr) { RegisterObject(obj, pr, objectPr, false); } private void RegisterObject(object obj, ParseRecord pr, ParseRecord objectPr, bool bIsString) { if (!pr._isRegistered) { pr._isRegistered = true; SerializationInfo si = null; long parentId = 0; MemberInfo memberInfo = null; int[] indexMap = null; if (objectPr != null) { indexMap = objectPr._indexMap; parentId = objectPr._objectId; if (objectPr._objectInfo != null) { if (!objectPr._objectInfo._isSi) { // ParentId is only used if there is a memberInfo memberInfo = objectPr._objectInfo.GetMemberInfo(pr._name); } } } // SerializationInfo is always needed for ISerialization si = pr._si; if (bIsString) { _objectManager.RegisterString((string)obj, pr._objectId, si, parentId, memberInfo); } else { _objectManager.RegisterObject(obj, pr._objectId, si, parentId, memberInfo, indexMap); } } } // Assigns an internal ID associated with the binary id number internal long GetId(long objectId) { if (!_fullDeserialization) { InitFullDeserialization(); } if (objectId > 0) { return objectId; } if (_oldFormatDetected || objectId == -1) { // Alarm bells. This is an old format. Deal with it. _oldFormatDetected = true; if (_valTypeObjectIdTable == null) { _valTypeObjectIdTable = new IntSizedArray(); } long tempObjId = 0; if ((tempObjId = _valTypeObjectIdTable[(int)objectId]) == 0) { tempObjId = ThresholdForValueTypeIds + objectId; _valTypeObjectIdTable[(int)objectId] = (int)tempObjId; } return tempObjId; } return -1 * objectId; } internal Type Bind(string assemblyString, string typeString) { Type type = null; if (_binder != null) { type = _binder.BindToType(assemblyString, typeString); } if (type == null) { type = FastBindToType(assemblyString, typeString); } return type; } internal sealed class TypeNAssembly { public Type Type; public string AssemblyName; } internal Type FastBindToType(string assemblyName, string typeName) { Type type = null; TypeNAssembly entry = (TypeNAssembly)_typeCache.GetCachedValue(typeName); if (entry == null || entry.AssemblyName != assemblyName) { Assembly assm = null; try { assm = Assembly.Load(new AssemblyName(assemblyName)); } catch { } if (assm == null) { return null; } if (_isSimpleAssembly) { GetSimplyNamedTypeFromAssembly(assm, typeName, ref type); } else { type = FormatterServices.GetTypeFromAssembly(assm, typeName); } if (type == null) { return null; } // before adding it to cache, let us do the security check CheckTypeForwardedTo(assm, type.Assembly, type); entry = new TypeNAssembly(); entry.Type = type; entry.AssemblyName = assemblyName; _typeCache.SetCachedValue(entry); } return entry.Type; } private static void GetSimplyNamedTypeFromAssembly(Assembly assm, string typeName, ref Type type) { // Catching any exceptions that could be thrown from a failure on assembly load // This is necessary, for example, if there are generic parameters that are qualified with a version of the assembly that predates the one available try { type = FormatterServices.GetTypeFromAssembly(assm, typeName); } catch (TypeLoadException) { } catch (FileNotFoundException) { } catch (FileLoadException) { } catch (BadImageFormatException) { } } private string _previousAssemblyString; private string _previousName; private Type _previousType; internal Type GetType(BinaryAssemblyInfo assemblyInfo, string name) { Type objectType = null; if (((_previousName != null) && (_previousName.Length == name.Length) && (_previousName.Equals(name))) && ((_previousAssemblyString != null) && (_previousAssemblyString.Length == assemblyInfo._assemblyString.Length) && (_previousAssemblyString.Equals(assemblyInfo._assemblyString)))) { objectType = _previousType; } else { objectType = Bind(assemblyInfo._assemblyString, name); if (objectType == null) { Assembly sourceAssembly = assemblyInfo.GetAssembly(); if (_isSimpleAssembly) { GetSimplyNamedTypeFromAssembly(sourceAssembly, name, ref objectType); } else { objectType = FormatterServices.GetTypeFromAssembly(sourceAssembly, name); } // here let us do the security check if (objectType != null) { CheckTypeForwardedTo(sourceAssembly, objectType.Assembly, objectType); } } _previousAssemblyString = assemblyInfo._assemblyString; _previousName = name; _previousType = objectType; } return objectType; } private static void CheckTypeForwardedTo(Assembly sourceAssembly, Assembly destAssembly, Type resolvedType) { // nop on core } } }
using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Xml; using xgc3.Core; namespace xgc3.RuntimeEnv { public class Symbol : Instance { // Flags that can describe a public string CodeBehind = null; public string BaseClass = null; public string FullClassName; public string FullBaseClassName; public static Symbol Parse(XmlNode node) { Symbol symbol = new Symbol(); foreach (XmlAttribute attr in node.Attributes) { symbol.SetProperty(attr.Name, attr.Value); } return symbol; } private Symbol() { } public Symbol(string className, string fullClassName, string fullBaseClassName, Type childrenType ) { Name = className; FullBaseClassName = fullBaseClassName; FullClassName = fullClassName; ChildrenType = childrenType; } public Symbol(string className, string fullClassName, string fullBaseClassName) { Name = className; FullBaseClassName = fullBaseClassName; FullClassName = fullClassName; } } public class SymbolTable : BaseRuntimeEnvInstance { private Dictionary<string /*classname*/, Symbol > m_symbols = new Dictionary<string,Symbol>(); private Dictionary<string /*instancename*/, string /*full class name*/> m_instanceTypes = new Dictionary<string,string>(); /// <summary> /// Manage all the classes in the system. /// </summary> #if LOAD_WITH_CSSCRIPT private AsmHelper m_helper; #endif /// <summary> /// Returns type of statically defined instance. Use RunningObjectTable for dynamic instances. /// </summary> /// <param name="instanceName"></param> /// <returns></returns> public string LookupFullTypeNameOfInstance( string instanceName) { return m_instanceTypes[instanceName]; } /// <summary> /// So we can lookup the class of an instance (kinda like ROT, but compile time). /// Used for clones. /// </summary> /// <param name="name"></param> /// <param name="fullClassName"></param> public void AddClassInstanceName( string name, string fullClassName) { if (m_instanceTypes.ContainsKey(name)) { throw new Exceptions.CompileException("Duplicate 'Name' attribute: " + name); } m_instanceTypes.Add( name, fullClassName); } /// <summary> /// Helps to detect duplicate symbols, for example. /// </summary> /// <param name="className"></param> public void AddClassSymbol(Symbol symbol ) { if (m_symbols.ContainsKey( symbol.Name)) { throw new Exceptions.CompileException("Duplicate class name: {0}", symbol.Name); } if (m_symbols.ContainsKey(symbol.FullClassName)) { throw new Exceptions.CompileException("Duplicate full class name: {0}", symbol.FullClassName); } //if ( (fullBaseClass != null) && !m_symbols.ContainsKey(fullBaseClass)) //{ // throw new Exceptions.CompileException("Unknown base class: {0}", fullBaseClass); //} m_symbols.Add(symbol.Name, symbol); #if OLD_WAY Assembly assembly = Assembly.Load( new AssemblyName( "xgc3.Generated")); // Get all Types available in the assembly in an array Type[] typeArray = assembly.GetTypes (); Type t=typeArray[className]; t.FullName, t.BaseType #endif } /// <summary> /// Does class have specified attribute? /// </summary> /// <param name="typeName"></param> /// <param name="attribute"></param> /// <param name="inherit"></param> /// <returns></returns> public bool HasCustomAttribute(string typeName, Type attribute, bool inherit) { System.Reflection.MemberInfo inf = GetType( typeName); return inf.GetCustomAttributes(attribute, inherit).Length > 0; } // Convert a value/type int C# code string public string ValueToCode(string value, string typeString) { string code; Type type = this.GetType(typeString); if (type == typeof(Int32)) { code = value; } else if (type == typeof(string)) { code = "\"" + value + "\""; } else if (type == typeof(Microsoft.Xna.Framework.Graphics.Color)) { // Special handler for colors. Convert color "name" to static property on the XNA color object. code = "Microsoft.Xna.Framework.Graphics.Color." + value; } else if (type.IsSubclassOf(typeof(Enum))) { code = typeString + "." + value; } else if (type is Type) { code = type.ToString(); } else { throw new Exceptions.CompileException("Unsupported value for DefaultValue: " + value); } return code; } /// <summary> /// Useful for checking if a type implements an interface. /// </summary> /// <param name="id"></param> /// <param name="typeName"></param> /// <param name="gm"></param> /// <returns></returns> public Type GetType( string typeName) { string fulltypename; try { fulltypename = m_symbols[typeName].FullClassName; } catch (Exception) { throw new Exceptions.CompileException("Unknown type: {0}", typeName); } try { // Problems instantiating flower 4 //MAYBE I NEED A PUBLIC CONSTRUCTOR. // Also fails: Assembly.Load("GameEditor.xgc, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); // Assembly asm = Assembly.LoadFrom("GameEditor.xgc.dll"); // TODO - Use passed in name. return asm.GetType(fulltypename); } catch (Exception ex) { throw new Exceptions.CompileException(ex.Message); } } /// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="typeName"></param> /// <param name="gm">Populate every instance with a call back to this top-level-object.</param> /// <returns></returns> public Instance Construct(string id, string typeName, GameManager gm) { string fulltypename; try { fulltypename = m_symbols[typeName].FullClassName; } catch (Exception) { throw new Exceptions.CompileException("Unknown type: {0}", typeName); } try { // Problems instantiating flower 4 //MAYBE I NEED A PUBLIC CONSTRUCTOR. // Also fails: Assembly.Load("GameEditor.xgc, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); // Assembly asm = Assembly.LoadFrom( "GameEditor.xgc.dll"); // TODO - Use passed in name. object oo = asm.CreateInstance(fulltypename); Instance bi = oo as Instance; #if LOAD_WITH_CSSCRIPT else { // Generated classes must be instantiated this way. bi = (Instance)m_helper.CreateObject(fulltypename); } #endif if (bi != null) { bi.Name = id; bi.GameMgr = gm; bi.IsJustCreated = true; bi.ChildrenType = m_symbols[typeName].ChildrenType; // TODO: Set defaults on all properties from class here. } return bi; } catch (Exception ex) { throw new Exceptions.CompileException( ex.Message); //"Only types that inherit from Instance can be constructed. ID={0} Type={1}", id, typeName); } } public string LookupFullTypeName(string className) { return m_symbols[className].FullClassName; } public string LookupFullBaseTypeName(string className) { try { string fullBaseClass = m_symbols[className].FullBaseClassName; if (fullBaseClass == null) { throw new Exceptions.CompileException("Invalid root object: {0}", className); } return fullBaseClass; } catch { throw new Exceptions.CompileException("Unknown base class for class: {0}", className); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Collections.ObjectModel.Tests { public class KeyedCollectionTest { [Fact] public void StringComparer() { var collection = new TestKeyedCollectionOfIKeyedItem<string, int>( System.StringComparer.OrdinalIgnoreCase) { new KeyedItem<string, int>("foo", 0), new KeyedItem<string, int>("bar", 1) }; AssertExtensions.Throws<ArgumentException>("key", null, () => collection.Add(new KeyedItem<string, int>("Foo", 0))); AssertExtensions.Throws<ArgumentException>("key", null, () => collection.Add(new KeyedItem<string, int>("fOo", 0))); AssertExtensions.Throws<ArgumentException>("key", null, () => collection.Add(new KeyedItem<string, int>("baR", 0))); } [Theory] [InlineData(-2)] [InlineData(int.MinValue)] public void Ctor_InvalidDictionaryCreationThreshold_ThrowsArgumentOutOfRangeException(int dictionaryCreationThreshold) { AssertExtensions.Throws<ArgumentOutOfRangeException>("dictionaryCreationThreshold", () => new TestKeyedCollectionOfIKeyedItem<string, int>(dictionaryCreationThreshold)); } } public class IListTestKeyedCollectionIntInt : IListTestKeyedCollection<int, int> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return "foo"; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override int CreateItem() { return s_item++; } protected override int GetKeyForItem(int item) { return item; } } public class IListTestKeyedCollectionStringString : IListTestKeyedCollection<string, string> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return 5; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override string CreateItem() { return (s_item++).ToString(); } protected override string GetKeyForItem(string item) { return item; } } public class IListTestKeyedCollectionIntString : IListTestKeyedCollection<int, string> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return 5; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override string CreateItem() { return (s_item++).ToString(); } protected override int GetKeyForItem(string item) { return item == null ? 0 : int.Parse(item); } } public class IListTestKeyedCollectionStringInt : IListTestKeyedCollection<string, int> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return "bar"; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override int CreateItem() { return s_item++; } protected override string GetKeyForItem(int item) { return item.ToString(); } } public class IListTestKeyedCollectionIntIntBadKey : IListTestKeyedCollectionBadKey<int, int> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return "foo"; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override int CreateItem() { return s_item++; } protected override int GetKeyForItem(int item) { return item; } } public class IListTestKeyedCollectionStringStringBadKey : IListTestKeyedCollectionBadKey<string, string> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return 5; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override string CreateItem() { return (s_item++).ToString(); } protected override string GetKeyForItem(string item) { return item; } } public class IListTestKeyedCollectionIntStringBadKey : IListTestKeyedCollectionBadKey<int, string> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return 5; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override string CreateItem() { return (s_item++).ToString(); } protected override int GetKeyForItem(string item) { return item == null ? 0 : int.Parse(item); } } public class IListTestKeyedCollectionStringIntBadKey : IListTestKeyedCollectionBadKey<string, int> { private static int s_item = 1; /// <summary> /// When overridden in a derived class, Gets a list of values that are not valid elements in the collection under test. /// </summary> /// <returns>An <see cref="IEnumerable" /> containing the invalid values.</returns> protected override IEnumerable GetInvalidValues() { yield return (long) 5; yield return "bar"; yield return new object(); } /// <summary> /// When overridden in a derived class, Gets a new, unique item. /// </summary> /// <returns>The new item.</returns> protected override int CreateItem() { return s_item++; } protected override string GetKeyForItem(int item) { return item.ToString(); } } public class KeyedCollectionTestsIntInt : KeyedCollectionTests<int, int> { private int _curValue = 1; public override int GetKeyForItem(int item) { return item; } public override int GenerateValue() { return _curValue++; } } public class KeyedCollectionTestsStringString : KeyedCollectionTests<string, string> { private int _curValue = 1; public override string GetKeyForItem(string item) { return item; } public override string GenerateValue() { return (_curValue++).ToString(); } } public class KeyedCollectionTestsIntString : KeyedCollectionTests<int, string> { private int _curValue = 1; public override int GetKeyForItem(string item) { return int.Parse(item); } public override string GenerateValue() { return (_curValue++).ToString(); } } public class KeyedCollectionTestsStringInt : KeyedCollectionTests<string, int> { private int _curValue = 1; public override string GetKeyForItem(int item) { return item.ToString(); } public override int GenerateValue() { return _curValue++; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Compute.Tests { public class ImageTests : VMTestBase { [Fact] [Trait("Name", "TestCreateImage_with_DiskEncryptionSet")] public void TestCreateImage_with_DiskEncryptionSet() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { using (MockContext context = MockContext.Start(this.GetType())) { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); EnsureClientsInitialized(context); string diskEncryptionSetId = getDefaultDiskEncryptionSetId(); CreateImageTestHelper(originalTestLocation, diskEncryptionSetId); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } [Fact] [Trait("Name", "TestCreateImage_without_DiskEncryptionSet")] public void TestCreateImage_without_DiskEncryptionSet() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { using (MockContext context = MockContext.Start(this.GetType())) { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "FranceCentral"); EnsureClientsInitialized(context); CreateImageTestHelper(originalTestLocation, diskEncryptionSetId: null); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } private void CreateImageTestHelper(string originalTestLocation, string diskEncryptionSetId) { VirtualMachine inputVM = null; // Create resource group var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix); var imageName = ComputeManagementTestUtilities.GenerateName("imageTest"); // Create a VM, so we can use its OS disk for creating the image string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string asName = ComputeManagementTestUtilities.GenerateName("as"); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); try { // Create Storage Account var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // Add data disk to the VM. Action<VirtualMachine> addDataDiskToVM = vm => { string containerName = HttpMockServer.GetAssetName("TestImageOperations", TestPrefix); var vhdContainer = "https://" + storageAccountName + ".blob.core.windows.net/" + containerName; var vhduri = vhdContainer + string.Format("/{0}.vhd", HttpMockServer.GetAssetName("TestImageOperations", TestPrefix)); vm.HardwareProfile.VmSize = VirtualMachineSizeTypes.StandardA4; vm.StorageProfile.DataDisks = new List<DataDisk>(); foreach (int index in new int[] { 1, 2 }) { var diskName = "dataDisk" + index; var ddUri = vhdContainer + string.Format("/{0}{1}.vhd", diskName, HttpMockServer.GetAssetName("TestImageOperations", TestPrefix)); var dd = new DataDisk { Caching = CachingTypes.None, Image = null, DiskSizeGB = 10, CreateOption = DiskCreateOptionTypes.Empty, Lun = 1 + index, Name = diskName, Vhd = new VirtualHardDisk { Uri = ddUri } }; vm.StorageProfile.DataDisks.Add(dd); } var testStatus = new InstanceViewStatus { Code = "test", Message = "test" }; var testStatusList = new List<InstanceViewStatus> { testStatus }; }; // Create the VM, whose OS disk will be used in creating the image var createdVM = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM, addDataDiskToVM); int expectedDiskLunWithDiskEncryptionSet = createdVM.StorageProfile.DataDisks[0].Lun; // Create the Image var imageInput = new Image() { Location = m_location, Tags = new Dictionary<string, string>() { {"RG", "rg"}, {"testTag", "1"}, }, StorageProfile = new ImageStorageProfile() { OsDisk = new ImageOSDisk() { BlobUri = createdVM.StorageProfile.OsDisk.Vhd.Uri, DiskEncryptionSet = diskEncryptionSetId == null ? null : new DiskEncryptionSetParameters() { Id = diskEncryptionSetId }, OsState = OperatingSystemStateTypes.Generalized, OsType = OperatingSystemTypes.Windows, }, DataDisks = new List<ImageDataDisk>() { new ImageDataDisk() { BlobUri = createdVM.StorageProfile.DataDisks[0].Vhd.Uri, DiskEncryptionSet = diskEncryptionSetId == null ? null: new DiskEncryptionSetParameters() { Id = diskEncryptionSetId }, Lun = expectedDiskLunWithDiskEncryptionSet, } } }, HyperVGeneration = HyperVGeneration.V1 }; var image = m_CrpClient.Images.CreateOrUpdate(rgName, imageName, imageInput); var getImage = m_CrpClient.Images.Get(rgName, imageName); ValidateImage(imageInput, getImage); if( diskEncryptionSetId != null) { Assert.True(getImage.StorageProfile.OsDisk.DiskEncryptionSet != null, "OsDisk.DiskEncryptionSet is null"); Assert.True(string.Equals(diskEncryptionSetId, getImage.StorageProfile.OsDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase), "getImage.StorageProfile.OsDisk.DiskEncryptionSet is not matching with expected DiskEncryptionSet resource"); Assert.Equal(1, getImage.StorageProfile.DataDisks.Count); Assert.True(getImage.StorageProfile.DataDisks[0].DiskEncryptionSet != null, ".DataDisks.DiskEncryptionSet is null"); Assert.True(string.Equals(diskEncryptionSetId, getImage.StorageProfile.DataDisks[0].DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase), "DataDisks.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource"); } ImageUpdate updateParams = new ImageUpdate() { Tags = getImage.Tags }; string tagKey = "UpdateTag"; updateParams.Tags.Add(tagKey, "TagValue"); m_CrpClient.Images.Update(rgName, imageName, updateParams); getImage = m_CrpClient.Images.Get(rgName, imageName); Assert.True(getImage.Tags.ContainsKey(tagKey)); var listResponse = m_CrpClient.Images.ListByResourceGroup(rgName); Assert.Single(listResponse); m_CrpClient.Images.Delete(rgName, image.Name); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); if (inputVM != null) { m_CrpClient.VirtualMachines.Delete(rgName, inputVM.Name); } m_ResourcesClient.ResourceGroups.Delete(rgName); } } void ValidateImage(Image imageIn, Image imageOut) { Assert.True(!string.IsNullOrEmpty(imageOut.ProvisioningState)); if(imageIn.Tags != null) { foreach(KeyValuePair<string, string> kvp in imageIn.Tags) { Assert.True(imageOut.Tags[kvp.Key] == kvp.Value); } } Assert.NotNull(imageOut.StorageProfile.OsDisk); if (imageIn.StorageProfile.OsDisk != null) { Assert.True(imageOut.StorageProfile.OsDisk.BlobUri == imageIn.StorageProfile.OsDisk.BlobUri); Assert.True(imageOut.StorageProfile.OsDisk.OsState == imageIn.StorageProfile.OsDisk.OsState); Assert.True(imageOut.StorageProfile.OsDisk.OsType == imageIn.StorageProfile.OsDisk.OsType); } if (imageIn.StorageProfile.DataDisks != null && imageIn.StorageProfile.DataDisks.Any()) { foreach (var dataDisk in imageIn.StorageProfile.DataDisks) { var dataDiskOut = imageOut.StorageProfile.DataDisks.FirstOrDefault( d => int.Equals(dataDisk.Lun, d.Lun)); Assert.NotNull(dataDiskOut); Assert.NotNull(dataDiskOut.BlobUri); Assert.NotNull(dataDiskOut.DiskSizeGB); } } Assert.Equal(imageIn.StorageProfile.ZoneResilient, imageOut.StorageProfile.ZoneResilient); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Security; using System.Text; using System.Xml; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// implementation for the Export-Clixml command /// </summary> [Cmdlet(VerbsData.Export, "Clixml", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113297")] public sealed class ExportClixmlCommand : PSCmdlet, IDisposable { #region Command Line Parameters // If a Passthru parameter is added, the SupportsShouldProcess // implementation will need to be modified. /// <summary> /// Depth of serialization /// </summary> [Parameter] [ValidateRange(1, int.MaxValue)] public int Depth { get; set; } = 0; /// <summary> /// mandatory file name to write to /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")] public string Path { get; set; } /// <summary> /// mandatory file name to write to /// </summary> [Parameter(Mandatory = true, ParameterSetName = "ByLiteralPath")] [Alias("PSPath")] public string LiteralPath { get { return Path; } set { Path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// Input object to be exported /// </summary> [Parameter(ValueFromPipeline = true, Mandatory = true)] [AllowNull] public PSObject InputObject { get; set; } /// <summary> /// Property that sets force parameter. /// </summary> [Parameter] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// Property that prevents file overwrite. /// </summary> [Parameter] [Alias("NoOverwrite")] public SwitchParameter NoClobber { get { return _noclobber; } set { _noclobber = value; } } private bool _noclobber; /// <summary> /// Encoding optional flag /// </summary> /// [Parameter] [ValidateSetAttribute(new string[] { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" })] public string Encoding { get; set; } = "Unicode"; #endregion Command Line Parameters #region Overrides /// <summary> /// BeginProcessing override /// </summary> protected override void BeginProcessing() { CreateFileStream(); } /// <summary> /// /// </summary> protected override void ProcessRecord() { if (null != _serializer) { _serializer.Serialize(InputObject); _xw.Flush(); } } /// <summary> /// /// </summary> protected override void EndProcessing() { if (_serializer != null) { _serializer.Done(); _serializer = null; } CleanUp(); } /// <summary> /// /// </summary> protected override void StopProcessing() { base.StopProcessing(); _serializer.Stop(); } #endregion Overrides #region file /// <summary> /// handle to file stream /// </summary> private FileStream _fs; /// <summary> /// stream writer used to write to file /// </summary> private XmlWriter _xw; /// <summary> /// Serializer used for serialization /// </summary> private Serializer _serializer; /// <summary> /// FileInfo of file to clear read-only flag when operation is complete /// </summary> private FileInfo _readOnlyFileInfo = null; private void CreateFileStream() { Dbg.Assert(Path != null, "FileName is mandatory parameter"); if (!ShouldProcess(Path)) return; StreamWriter sw; PathUtils.MasterStreamOpen( this, this.Path, this.Encoding, false, // default encoding false, // append this.Force, this.NoClobber, out _fs, out sw, out _readOnlyFileInfo, _isLiteralPath ); // create xml writer XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.CloseOutput = true; xmlSettings.Encoding = sw.Encoding; xmlSettings.Indent = true; xmlSettings.OmitXmlDeclaration = true; _xw = XmlWriter.Create(sw, xmlSettings); if (Depth == 0) { _serializer = new Serializer(_xw); } else { _serializer = new Serializer(_xw, Depth, true); } } private void CleanUp() { if (_fs != null) { if (_xw != null) { _xw.Dispose(); _xw = null; } _fs.Dispose(); _fs = null; } // reset the read-only attribute if (null != _readOnlyFileInfo) { _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; _readOnlyFileInfo = null; } } #endregion file #region IDisposable Members /// <summary> /// Set to true when object is disposed /// </summary> private bool _disposed; /// <summary> /// public dispose method /// </summary> public void Dispose() { if (_disposed == false) { CleanUp(); } _disposed = true; } #endregion IDisposable Members } /// <summary> /// Implements Import-Clixml command /// </summary> [Cmdlet(VerbsData.Import, "Clixml", SupportsPaging = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113340")] public sealed class ImportClixmlCommand : PSCmdlet, IDisposable { #region Command Line Parameters /// <summary> /// mandatory file name to read from /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] public String[] Path { get; set; } /// <summary> /// mandatory file name to read from /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] [Alias("PSPath")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] LiteralPath { get { return Path; } set { Path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; #endregion Command Line Parameters #region IDisposable Members private bool _disposed = false; /// <summary> /// public dispose method /// </summary> public void Dispose() { if (!_disposed) { GC.SuppressFinalize(this); if (_helper != null) { _helper.Dispose(); _helper = null; } _disposed = true; } } #endregion private ImportXmlHelper _helper; /// <summary> /// ProcessRecord overload /// </summary> protected override void ProcessRecord() { if (Path != null) { foreach (string path in Path) { _helper = new ImportXmlHelper(path, this, _isLiteralPath); _helper.Import(); } } } /// <summary> /// /// </summary> protected override void StopProcessing() { base.StopProcessing(); _helper.Stop(); } } /// <summary> /// implementation for the convertto-xml command /// </summary> [Cmdlet(VerbsData.ConvertTo, "Xml", SupportsShouldProcess = false, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135204", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(XmlDocument), typeof(String))] public sealed class ConvertToXmlCommand : PSCmdlet, IDisposable { #region Command Line Parameters /// <summary> /// Depth of serialization /// </summary> [Parameter(HelpMessage = "Specifies how many levels of contained objects should be included in the XML representation")] [ValidateRange(1, int.MaxValue)] public int Depth { get; set; } = 0; /// <summary> /// Input Object which is written to XML format /// </summary> [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] [AllowNull] public PSObject InputObject { get; set; } /// <summary> /// Property that sets NoTypeInformation parameter. /// </summary> [Parameter(HelpMessage = "Specifies not to include the Type information in the XML representation")] public SwitchParameter NoTypeInformation { get { return _notypeinformation; } set { _notypeinformation = value; } } private bool _notypeinformation; /// <summary> /// Property that sets As parameter. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [ValidateSet("Stream", "String", "Document")] public string As { get; set; } = "Document"; #endregion Command Line Parameters #region Overrides /// <summary> /// BeginProcessing override /// </summary> protected override void BeginProcessing() { if (!As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { CreateMemoryStream(); } else { WriteObject(string.Format(CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"{0}\"?>", Encoding.UTF8.WebName)); WriteObject("<Objects>"); } } /// <summary> /// override ProcessRecord /// </summary> protected override void ProcessRecord() { if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { CreateMemoryStream(); if (null != _serializer) _serializer.SerializeAsStream(InputObject); if (null != _serializer) { _serializer.DoneAsStream(); _serializer = null; } //Loading to the XML Document _ms.Position = 0; StreamReader read = new StreamReader(_ms); string data = read.ReadToEnd(); WriteObject(data); //Cleanup CleanUp(); } else { if (null != _serializer) _serializer.Serialize(InputObject); } } /// <summary> /// /// </summary> protected override void EndProcessing() { if (null != _serializer) { _serializer.Done(); _serializer = null; } if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { WriteObject("</Objects>"); } else { //Loading to the XML Document _ms.Position = 0; if (As.Equals("Document", StringComparison.OrdinalIgnoreCase)) { // this is a trusted xml doc - the cmdlet generated the doc into a private memory stream XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(_ms); WriteObject(xmldoc); } else if (As.Equals("String", StringComparison.OrdinalIgnoreCase)) { StreamReader read = new StreamReader(_ms); string data = read.ReadToEnd(); WriteObject(data); } } //Cleaning up CleanUp(); } /// <summary> /// /// </summary> protected override void StopProcessing() { _serializer.Stop(); } #endregion Overrides #region memory /// <summary> /// XmlText writer /// </summary> private XmlWriter _xw; /// <summary> /// Serializer used for serialization /// </summary> private CustomSerialization _serializer; /// <summary> ///Memory Stream used for serialization /// </summary> private MemoryStream _ms; private void CreateMemoryStream() { // Memory Stream _ms = new MemoryStream(); // We use XmlTextWriter originally: // _xw = new XmlTextWriter(_ms, null); // _xw.Formatting = Formatting.Indented; // This implies the following settings: // - Encoding is null -> use the default encoding 'UTF-8' when creating the writer from the stream; // - XmlTextWriter closes the underlying stream / writer when 'Close/Dispose' is called on it; // - Use the default indentation setting -- two space characters. // // We configure the same settings in XmlWriterSettings when refactoring this code to use XmlWriter: // - The default encoding used by XmlWriterSettings is 'UTF-8', but we call it out explicitly anyway; // - Set CloseOutput to true; // - Set Indent to true, and by default, IndentChars is two space characters. // // We use XmlWriterSettings.OmitXmlDeclaration instead of XmlWriter.WriteStartDocument because the // xml writer created by calling XmlWriter.Create(Stream, XmlWriterSettings) will write out the xml // declaration even without calling WriteStartDocument(). var xmlSettings = new XmlWriterSettings(); xmlSettings.Encoding = Encoding.UTF8; xmlSettings.CloseOutput = true; xmlSettings.Indent = true; if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { // Omit xml declaration in this case because we will write out the declaration string in BeginProcess. xmlSettings.OmitXmlDeclaration = true; } _xw = XmlWriter.Create(_ms, xmlSettings); if (Depth == 0) { _serializer = new CustomSerialization(_xw, _notypeinformation); } else { _serializer = new CustomSerialization(_xw, _notypeinformation, Depth); } } /// <summary> ///Cleaning up the MemoryStream /// </summary> private void CleanUp() { if (_ms != null) { if (_xw != null) { _xw.Dispose(); _xw = null; } _ms.Dispose(); _ms = null; } } #endregion memory #region IDisposable Members /// <summary> /// Set to true when object is disposed /// </summary> private bool _disposed; /// <summary> /// public dispose method /// </summary> public void Dispose() { if (_disposed == false) { CleanUp(); } _disposed = true; } #endregion IDisposable Members } /// <summary> /// Helper class to import single XML file /// </summary> internal class ImportXmlHelper : IDisposable { #region constructor /// <summary> /// XML file to import /// </summary> private readonly string _path; /// <summary> /// Reference to cmdlet which is using this helper class /// </summary> private readonly PSCmdlet _cmdlet; private bool _isLiteralPath; internal ImportXmlHelper(string fileName, PSCmdlet cmdlet, bool isLiteralPath) { if (fileName == null) { throw PSTraceSource.NewArgumentNullException("fileName"); } if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } _path = fileName; _cmdlet = cmdlet; _isLiteralPath = isLiteralPath; } #endregion constructor #region file /// <summary> /// handle to file stream /// </summary> internal FileStream _fs; /// <summary> /// XmlReader used to read file /// </summary> internal XmlReader _xr; private static XmlReader CreateXmlReader(Stream stream) { TextReader textReader = new StreamReader(stream); // skip #< CLIXML directive const string cliXmlDirective = "#< CLIXML"; if (textReader.Peek() == (int)cliXmlDirective[0]) { string line = textReader.ReadLine(); if (!line.Equals(cliXmlDirective, StringComparison.Ordinal)) { stream.Seek(0, SeekOrigin.Begin); } } return XmlReader.Create(textReader, InternalDeserializer.XmlReaderSettingsForCliXml); } internal void CreateFileStream() { _fs = PathUtils.OpenFileStream(_path, _cmdlet, _isLiteralPath); _xr = CreateXmlReader(_fs); } private void CleanUp() { if (_fs != null) { _fs.Dispose(); _fs = null; } } #endregion file #region IDisposable Members /// <summary> /// Set to true when object is disposed /// </summary> private bool _disposed; /// <summary> /// public dispose method /// </summary> public void Dispose() { if (_disposed == false) { CleanUp(); } _disposed = true; GC.SuppressFinalize(this); } #endregion IDisposable Members private Deserializer _deserializer; internal void Import() { CreateFileStream(); _deserializer = new Deserializer(_xr); // If total count has been requested, return a dummy object with zero confidence if (_cmdlet.PagingParameters.IncludeTotalCount) { PSObject totalCount = _cmdlet.PagingParameters.NewTotalCount(0, 0); _cmdlet.WriteObject(totalCount); } ulong skip = _cmdlet.PagingParameters.Skip; ulong first = _cmdlet.PagingParameters.First; // if paging is not specified then keep the old V2 behavior if (skip == 0 && first == ulong.MaxValue) { ulong item = 0; while (!_deserializer.Done()) { object result = _deserializer.Deserialize(); if (item++ < skip) continue; if (first == 0) break; _cmdlet.WriteObject(result); first--; } } // else try to flatten the output if possible else { ulong skipped = 0; ulong count = 0; while (!_deserializer.Done() && count < first) { object result = _deserializer.Deserialize(); PSObject psObject = result as PSObject; if (psObject == null && skipped++ >= skip) { count++; _cmdlet.WriteObject(result); continue; } ICollection c = psObject.BaseObject as ICollection; if (c != null) { foreach (object o in c) { if (count >= first) break; if (skipped++ >= skip) { count++; _cmdlet.WriteObject(o); } } } else { if (skipped++ >= skip) { count++; _cmdlet.WriteObject(result); } } } } } internal void Stop() { if (_deserializer != null) { _deserializer.Stop(); } } } // ImportXmlHelper #region Select-Xml ///<summary> ///This cmdlet is used to search an xml document based on the XPath Query. ///</summary> [Cmdlet(VerbsCommon.Select, "Xml", DefaultParameterSetName = "Xml", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135255")] [OutputType(typeof(SelectXmlInfo))] public class SelectXmlCommand : PSCmdlet { # region parameters /// <summary> /// Specifies the path which contains the xml files. The default is the current /// user directory /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Path")] [ValidateNotNullOrEmpty] public String[] Path { get; set; } /// <summary> /// Specifies the literal path which contains the xml files. The default is the current /// user directory /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "LiteralPath")] [ValidateNotNullOrEmpty] [Alias("PSPath")] public String[] LiteralPath { get { return Path; } set { Path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// The following is the definition of the input parameter "XML". /// Specifies the xml Node /// </summary> [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, ParameterSetName = "Xml")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", MessageId = "System.Xml.XmlNode")] [Alias("Node")] public System.Xml.XmlNode[] Xml { get; set; } /// <summary> /// The following is the definition of the input parameter in string format. /// Specifies the string format of a fully qualified xml. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "Content")] [ValidateNotNullOrEmpty] public string[] Content { get; set; } /// <summary> /// The following is the definition of the input parameter "Xpath". /// Specifies the String in XPath language syntax. The xml documents will be /// searched for the nodes/values represented by this parameter. /// </summary> [Parameter(Mandatory = true, Position = 0)] [ValidateNotNullOrEmpty] public string XPath { get; set; } /// <summary> /// The following definition used to specify the /// NameSpace of xml. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable Namespace { get; set; } # endregion parameters # region private private void WriteResults(XmlNodeList foundXmlNodes, string filePath) { Dbg.Assert(foundXmlNodes != null, "Caller should verify foundNodes != null"); foreach (XmlNode foundXmlNode in foundXmlNodes) { SelectXmlInfo selectXmlInfo = new SelectXmlInfo(); selectXmlInfo.Node = foundXmlNode; selectXmlInfo.Pattern = XPath; selectXmlInfo.Path = filePath; this.WriteObject(selectXmlInfo); } } private void ProcessXmlNode(XmlNode xmlNode, string filePath) { Dbg.Assert(xmlNode != null, "Caller should verify xmlNode != null"); XmlNodeList xList; if (Namespace != null) { XmlNamespaceManager xmlns = AddNameSpaceTable(this.ParameterSetName, xmlNode as XmlDocument, Namespace); xList = xmlNode.SelectNodes(XPath, xmlns); } else { xList = xmlNode.SelectNodes(XPath); } this.WriteResults(xList, filePath); } private void ProcessXmlFile(string filePath) { //Cannot use ImportXMLHelper because it will throw terminating error which will //not be inline with Select-String //So doing self processing of the file. try { XmlDocument xmlDocument = InternalDeserializer.LoadUnsafeXmlDocument( new FileInfo(filePath), true, /* preserve whitespace, comments, etc. */ null); /* default maxCharactersInDocument */ this.ProcessXmlNode(xmlDocument, filePath); } catch (NotSupportedException notSupportedException) { this.WriteFileReadError(filePath, notSupportedException); } catch (IOException ioException) { this.WriteFileReadError(filePath, ioException); } catch (SecurityException securityException) { this.WriteFileReadError(filePath, securityException); } catch (UnauthorizedAccessException unauthorizedAccessException) { this.WriteFileReadError(filePath, unauthorizedAccessException); } catch (XmlException xmlException) { this.WriteFileReadError(filePath, xmlException); } catch (InvalidOperationException invalidOperationException) { this.WriteFileReadError(filePath, invalidOperationException); } } private void WriteFileReadError(string filePath, Exception exception) { string errorMessage = string.Format( CultureInfo.InvariantCulture, // filePath is culture invariant, exception message is to be copied verbatim UtilityCommonStrings.FileReadError, filePath, exception.Message); ArgumentException argumentException = new ArgumentException(errorMessage, exception); ErrorRecord errorRecord = new ErrorRecord(argumentException, "ProcessingFile", ErrorCategory.InvalidArgument, filePath); this.WriteError(errorRecord); } private XmlNamespaceManager AddNameSpaceTable(string parametersetname, XmlDocument xDoc, Hashtable namespacetable) { XmlNamespaceManager xmlns; if (parametersetname.Equals("Xml")) { XmlNameTable xmlnt = new NameTable(); xmlns = new XmlNamespaceManager(xmlnt); } else { xmlns = new XmlNamespaceManager(xDoc.NameTable); } foreach (DictionaryEntry row in namespacetable) { try { xmlns.AddNamespace(row.Key.ToString(), row.Value.ToString()); } catch (NullReferenceException) { string message = StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError); InvalidOperationException e = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); WriteError(er); } catch (ArgumentNullException) { string message = StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError); InvalidOperationException e = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); WriteError(er); } } return xmlns; } # endregion private #region override /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { if (ParameterSetName.Equals("Xml", StringComparison.OrdinalIgnoreCase)) { foreach (XmlNode xmlNode in this.Xml) { ProcessXmlNode(xmlNode, string.Empty); } } else if ( (ParameterSetName.Equals("Path", StringComparison.OrdinalIgnoreCase) || (ParameterSetName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase)))) { //If any file not resolved, execution stops. this is to make consistent with select-string. List<string> fullresolvedPaths = new List<string>(); foreach (string fpath in Path) { if (_isLiteralPath) { string resolvedPath = GetUnresolvedProviderPathFromPSPath(fpath); fullresolvedPaths.Add(resolvedPath); } else { ProviderInfo provider; Collection<string> resolvedPaths = GetResolvedProviderPathFromPSPath(fpath, out provider); if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { //Cannot open File error string message = StringUtil.Format(UtilityCommonStrings.FileOpenError, provider.FullName); InvalidOperationException e = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(e, "ProcessingFile", ErrorCategory.InvalidOperation, fpath); WriteError(er); continue; } fullresolvedPaths.AddRange(resolvedPaths); } } foreach (string file in fullresolvedPaths) { ProcessXmlFile(file); } } else if (ParameterSetName.Equals("Content", StringComparison.OrdinalIgnoreCase)) { foreach (string xmlstring in Content) { XmlDocument xmlDocument; try { xmlDocument = (XmlDocument)LanguagePrimitives.ConvertTo(xmlstring, typeof(XmlDocument), CultureInfo.InvariantCulture); } catch (PSInvalidCastException invalidCastException) { this.WriteError(invalidCastException.ErrorRecord); continue; } this.ProcessXmlNode(xmlDocument, string.Empty); } } else { Dbg.Assert(false, "Unrecognized parameterset"); } }//End ProcessRecord() #endregion overrides }//End Class /// <summary> /// The object returned by Select-Xml representing the result of a match. /// </summary> public sealed class SelectXmlInfo { /// <summary> /// If the object is InputObject, Input Stream is used. /// </summary> private const string inputStream = "InputStream"; private const string MatchFormat = "{0}:{1}"; private const string SimpleFormat = "{0}"; /// <summary> /// The XmlNode that matches search /// </summary> [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", MessageId = "System.Xml.XmlNode")] public XmlNode Node { get; set; } /// <summary> /// The FileName from which the match is found. /// </summary> public string Path { get { return _path; } set { if (String.IsNullOrEmpty(value)) { _path = inputStream; } else { _path = value; } } } private string _path; /// <summary> /// The pattern used to search /// </summary> public string Pattern { get; set; } /// <summary> /// Returns the string representation of this object. The format /// depends on whether a path has been set for this object or not. /// </summary> /// <returns></returns> public override string ToString() { return ToString(null); } /// <summary> /// Return String representation of the object /// </summary> /// <param name="directory"></param> /// <returns></returns> private string ToString(string directory) { string displayPath = (directory != null) ? RelativePath(directory) : _path; return FormatLine(GetNodeText(), displayPath); } /// <summary> /// Returns the XmlNode Value or InnerXml. /// </summary> /// <returns></returns> internal string GetNodeText() { string nodeText = String.Empty; if (Node != null) { if (Node.Value != null) { nodeText = Node.Value.Trim(); } else { nodeText = Node.InnerXml.Trim(); } } return nodeText; } /// <summary> /// Returns the path of the matching file truncated relative to the <paramref name="directory"/> parameter. /// <remarks> /// For example, if the matching path was c:\foo\bar\baz.c and the directory argument was c:\foo /// the routine would return bar\baz.c /// </remarks> /// </summary> /// <param name="directory">The directory base the truncation on.</param> /// <returns>The relative path that was produced.</returns> private string RelativePath(string directory) { string relPath = _path; if (!relPath.Equals(inputStream)) { if (relPath.StartsWith(directory, StringComparison.CurrentCultureIgnoreCase)) { int offset = directory.Length; if (offset < relPath.Length) { if (directory[offset - 1] == '\\' || directory[offset - 1] == '/') relPath = relPath.Substring(offset); else if (relPath[offset] == '\\' || relPath[offset] == '/') relPath = relPath.Substring(offset + 1); } } } return relPath; } /// <summary> /// Formats a line for use in ToString. /// </summary> /// <param name="text"></param> /// <param name="displaypath"></param> /// <returns></returns> private string FormatLine(string text, string displaypath) { if (_path.Equals(inputStream)) { return StringUtil.Format(SimpleFormat, text); } else { return StringUtil.Format(MatchFormat, text, displaypath); } } } #endregion Select-Xml }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace LunchBox.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); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Log; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV1 { internal partial class DiagnosticIncrementalAnalyzer : BaseDiagnosticIncrementalAnalyzer { private readonly int _correlationId; private readonly MemberRangeMap _memberRangeMap; private readonly AnalyzerExecutor _executor; private readonly StateManager _stateManager; /// <summary> /// PERF: Always run analyzers sequentially for background analysis. /// </summary> private const bool ConcurrentAnalysis = false; /// <summary> /// Always compute suppressed diagnostics - diagnostic clients may or may not request for suppressed diagnostics. /// </summary> private const bool ReportSuppressedDiagnostics = true; public DiagnosticIncrementalAnalyzer( DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, HostAnalyzerManager analyzerManager, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource) : base(owner, workspace, analyzerManager, hostDiagnosticUpdateSource) { _correlationId = correlationId; _memberRangeMap = new MemberRangeMap(); _executor = new AnalyzerExecutor(this); _stateManager = new StateManager(analyzerManager); _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged; } private void OnProjectAnalyzerReferenceChanged(object sender, ProjectAnalyzerReferenceChangedEventArgs e) { if (e.Removed.Length == 0) { // nothing to refresh return; } // events will be automatically serialized. ClearProjectStatesAsync(e.Project, e.Removed, CancellationToken.None); } public override Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken)) { return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken); } } public override Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentClose, GetResetLogMessage, document, cancellationToken)) { // we don't need the info for closed file _memberRangeMap.Remove(document.Id); return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken); } } public override Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken)) { // clear states for re-analysis and raise events about it. otherwise, some states might not updated on re-analysis // due to our build-live de-duplication logic where we put all state in Documents state. return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken); } } private Task ClearOnlyDocumentStates(Document document, bool raiseEvent, CancellationToken cancellationToken) { // we remove whatever information we used to have on document open/close and re-calculate diagnostics // we had to do this since some diagnostic analyzer changes its behavior based on whether the document is opened or not. // so we can't use cached information. ClearDocumentStates(document, _stateManager.GetStateSets(document.Project), raiseEvent, includeProjectState: false, cancellationToken: cancellationToken); return SpecializedTasks.EmptyTask; } private bool CheckOption(Workspace workspace, string language, bool documentOpened) { var optionService = workspace.Services.GetService<IOptionService>(); if (optionService == null || optionService.GetOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, language)) { return true; } if (documentOpened) { return true; } return false; } internal CompilationWithAnalyzers GetCompilationWithAnalyzers(Project project, Compilation compilation, bool concurrentAnalysis, bool reportSuppressedDiagnostics) { Contract.ThrowIfFalse(project.SupportsCompilation); Contract.ThrowIfNull(compilation); var analysisOptions = new CompilationWithAnalyzersOptions( new WorkspaceAnalyzerOptions(project.AnalyzerOptions, project.Solution.Workspace), GetOnAnalyzerException(project.Id), concurrentAnalysis, logAnalyzerExecutionTime: true, reportSuppressedDiagnostics: reportSuppressedDiagnostics); var analyzers = _stateManager.GetAnalyzers(project); var filteredAnalyzers = analyzers .Where(a => !CompilationWithAnalyzers.IsDiagnosticAnalyzerSuppressed(a, compilation.Options, analysisOptions.OnAnalyzerException)) .Distinct() .ToImmutableArray(); if (filteredAnalyzers.IsEmpty) { return null; } return new CompilationWithAnalyzers(compilation, filteredAnalyzers, analysisOptions); } public override async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { await AnalyzeSyntaxAsync(document, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task AnalyzeSyntaxAsync(Document document, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen())) { return; } var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var dataVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false); var versions = new VersionArgument(textVersion, dataVersion); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fullSpan = root == null ? null : (TextSpan?)root.FullSpan; var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken); var openedDocument = document.IsOpen(); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project)) { if (SkipRunningAnalyzer(document.Project.CompilationOptions, userDiagnosticDriver, openedDocument, skipClosedFileChecks, stateSet)) { await ClearExistingDiagnostics(document, stateSet, StateType.Syntax, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Syntax, diagnosticIds)) { var data = await _executor.GetSyntaxAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType.Syntax, document, stateSet, data.Items); continue; } var state = stateSet.GetState(StateType.Syntax); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Syntax, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { await AnalyzeDocumentAsync(document, bodyOpt, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen())) { return; } var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); var dataVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var versions = new VersionArgument(textVersion, dataVersion, projectVersion); if (bodyOpt == null) { await AnalyzeDocumentAsync(document, versions, diagnosticIds, skipClosedFileChecks, cancellationToken).ConfigureAwait(false); } else { // only open file can go this route await AnalyzeBodyDocumentAsync(document, bodyOpt, versions, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task AnalyzeBodyDocumentAsync(Document document, SyntaxNode member, VersionArgument versions, CancellationToken cancellationToken) { try { // syntax facts service must exist, otherwise, this method won't have called. var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var memberId = syntaxFacts.GetMethodLevelMemberId(root, member); var spanBasedDriver = new DiagnosticAnalyzerDriver(document, member.FullSpan, root, this, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken); var documentBasedDriver = new DiagnosticAnalyzerDriver(document, root.FullSpan, root, this, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project)) { if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, document.Project)) { await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document)) { var supportsSemanticInSpan = stateSet.Analyzer.SupportsSpanBasedSemanticDiagnosticAnalysis(); var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver; var ranges = _memberRangeMap.GetSavedMemberRange(stateSet.Analyzer, document); var data = await _executor.GetDocumentBodyAnalysisDataAsync( stateSet, versions, userDiagnosticDriver, root, member, memberId, supportsSemanticInSpan, ranges).ConfigureAwait(false); _memberRangeMap.UpdateMemberRange(stateSet.Analyzer, document, versions.TextVersion, memberId, member.FullSpan, ranges); var state = stateSet.GetState(StateType.Document); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType.Document, document, stateSet, data.Items); continue; } RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task AnalyzeDocumentAsync(Document document, VersionArgument versions, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fullSpan = root == null ? null : (TextSpan?)root.FullSpan; var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken); bool openedDocument = document.IsOpen(); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project)) { if (SkipRunningAnalyzer(document.Project.CompilationOptions, userDiagnosticDriver, openedDocument, skipClosedFileChecks, stateSet)) { await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document, diagnosticIds)) { var data = await _executor.GetDocumentAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType.Document, document, stateSet, data.Items); continue; } if (openedDocument) { _memberRangeMap.Touch(stateSet.Analyzer, document, versions.TextVersion); } var state = stateSet.GetState(StateType.Document); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { await AnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false); } private async Task AnalyzeProjectAsync(Project project, CancellationToken cancellationToken) { try { // Compilation actions can report diagnostics on open files, so "documentOpened = true" if (!CheckOption(project.Solution.Workspace, project.Language, documentOpened: true)) { return; } var projectTextVersion = await project.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); var analyzerDriver = new DiagnosticAnalyzerDriver(project, this, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken); var versions = new VersionArgument(projectTextVersion, semanticVersion, projectVersion); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(project)) { // Compilation actions can report diagnostics on open files, so we skipClosedFileChecks. if (SkipRunningAnalyzer(project.CompilationOptions, analyzerDriver, openedDocument: true, skipClosedFileChecks: true, stateSet: stateSet)) { await ClearExistingDiagnostics(project, stateSet, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Project, diagnosticIds: null)) { var data = await _executor.GetProjectAnalysisDataAsync(analyzerDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseProjectDiagnosticsUpdatedIfNeeded(project, stateSet, ImmutableArray<DiagnosticData>.Empty, data.Items); continue; } var state = stateSet.GetState(StateType.Project); await PersistProjectData(project, state, data).ConfigureAwait(false); RaiseProjectDiagnosticsUpdatedIfNeeded(project, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private bool SkipRunningAnalyzer( CompilationOptions compilationOptions, DiagnosticAnalyzerDriver userDiagnosticDriver, bool openedDocument, bool skipClosedFileChecks, StateSet stateSet) { if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, userDiagnosticDriver.Project)) { return true; } if (skipClosedFileChecks) { return false; } if (ShouldRunAnalyzerForClosedFile(compilationOptions, openedDocument, stateSet.Analyzer)) { return false; } return true; } private static async Task PersistProjectData(Project project, DiagnosticState state, AnalysisData data) { // TODO: Cancellation is not allowed here to prevent data inconsistency. But there is still a possibility of data inconsistency due to // things like exception. For now, I am letting it go and let v2 engine take care of it properly. If v2 doesn't come online soon enough // more refactoring is required on project state. // clear all existing data state.Remove(project.Id); foreach (var document in project.Documents) { state.Remove(document.Id); } // quick bail out if (data.Items.Length == 0) { return; } // save new data var group = data.Items.GroupBy(d => d.DocumentId); foreach (var kv in group) { if (kv.Key == null) { // save project scope diagnostics await state.PersistAsync(project, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false); continue; } // save document scope diagnostics var document = project.GetDocument(kv.Key); if (document == null) { continue; } await state.PersistAsync(document, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false); } } public override void RemoveDocument(DocumentId documentId) { using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None)) { _memberRangeMap.Remove(documentId); foreach (var stateSet in _stateManager.GetStateSets(documentId.ProjectId)) { stateSet.Remove(documentId); var solutionArgs = new SolutionArgument(null, documentId.ProjectId, documentId); for (var stateType = 0; stateType < s_stateTypeCount; stateType++) { RaiseDiagnosticsRemoved((StateType)stateType, documentId, stateSet, solutionArgs); } } } } public override void RemoveProject(ProjectId projectId) { using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None)) { foreach (var stateSet in _stateManager.GetStateSets(projectId)) { stateSet.Remove(projectId); var solutionArgs = new SolutionArgument(null, projectId, null); RaiseDiagnosticsRemoved(StateType.Project, projectId, stateSet, solutionArgs); } } _stateManager.RemoveStateSet(projectId); } public override async Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: false, diagnostics: diagnostics, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken); return await getter.TryGetAsync().ConfigureAwait(false); } public override async Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: true, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken); var result = await getter.TryGetAsync().ConfigureAwait(false); Contract.Requires(result); return getter.Diagnostics; } private bool ShouldRunAnalyzerForClosedFile(CompilationOptions options, bool openedDocument, DiagnosticAnalyzer analyzer) { // we have opened document, doesn't matter if (openedDocument || analyzer.IsCompilerAnalyzer()) { return true; } // PERF: Don't query descriptors for compiler analyzer, always execute it. if (analyzer.IsCompilerAnalyzer()) { return true; } return Owner.GetDiagnosticDescriptors(analyzer).Any(d => GetEffectiveSeverity(d, options) != ReportDiagnostic.Hidden); } private static ReportDiagnostic GetEffectiveSeverity(DiagnosticDescriptor descriptor, CompilationOptions options) { return options == null ? MapSeverityToReport(descriptor.DefaultSeverity) : descriptor.GetEffectiveSeverity(options); } private static ReportDiagnostic MapSeverityToReport(DiagnosticSeverity severity) { switch (severity) { case DiagnosticSeverity.Hidden: return ReportDiagnostic.Hidden; case DiagnosticSeverity.Info: return ReportDiagnostic.Info; case DiagnosticSeverity.Warning: return ReportDiagnostic.Warn; case DiagnosticSeverity.Error: return ReportDiagnostic.Error; default: throw ExceptionUtilities.Unreachable; } } private bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds) { return ShouldRunAnalyzerForStateType(analyzer, stateTypeId, diagnosticIds, Owner.GetDiagnosticDescriptors); } private static bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds = null, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getDescriptors = null) { // PERF: Don't query descriptors for compiler analyzer, always execute it for all state types. if (analyzer.IsCompilerAnalyzer()) { return true; } if (diagnosticIds != null && getDescriptors(analyzer).All(d => !diagnosticIds.Contains(d.Id))) { return false; } switch (stateTypeId) { case StateType.Syntax: return analyzer.SupportsSyntaxDiagnosticAnalysis(); case StateType.Document: return analyzer.SupportsSemanticDiagnosticAnalysis(); case StateType.Project: return analyzer.SupportsProjectDiagnosticAnalysis(); default: throw ExceptionUtilities.Unreachable; } } public override void LogAnalyzerCountSummary() { DiagnosticAnalyzerLogger.LogAnalyzerCrashCountSummary(_correlationId, DiagnosticLogAggregator); DiagnosticAnalyzerLogger.LogAnalyzerTypeCountSummary(_correlationId, DiagnosticLogAggregator); // reset the log aggregator ResetDiagnosticLogAggregator(); } private static bool CheckSyntaxVersions(Document document, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) && document.CanReusePersistedSyntaxTreeVersion(versions.DataVersion, existingData.DataVersion); } private static bool CheckSemanticVersions(Document document, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) && document.Project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion); } private static bool CheckSemanticVersions(Project project, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return VersionStamp.CanReusePersistedVersion(versions.TextVersion, existingData.TextVersion) && project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion); } private void RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType type, Document document, StateSet stateSet, ImmutableArray<DiagnosticData> items) { RaiseDocumentDiagnosticsUpdatedIfNeeded(type, document, stateSet, ImmutableArray<DiagnosticData>.Empty, items); } private void RaiseDocumentDiagnosticsUpdatedIfNeeded( StateType type, Document document, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { var noItems = existingItems.Length == 0 && newItems.Length == 0; if (noItems) { return; } RaiseDiagnosticsCreated(type, document.Id, stateSet, new SolutionArgument(document), newItems); } private void RaiseProjectDiagnosticsUpdatedIfNeeded( Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { var noItems = existingItems.Length == 0 && newItems.Length == 0; if (noItems) { return; } RaiseProjectDiagnosticsRemovedIfNeeded(project, stateSet, existingItems, newItems); RaiseProjectDiagnosticsUpdated(project, stateSet, newItems); } private void RaiseProjectDiagnosticsRemovedIfNeeded( Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { if (existingItems.Length == 0) { return; } var removedItems = existingItems.GroupBy(d => d.DocumentId).Select(g => g.Key).Except(newItems.GroupBy(d => d.DocumentId).Select(g => g.Key)); foreach (var documentId in removedItems) { if (documentId == null) { RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, new SolutionArgument(project)); continue; } var document = project.GetDocument(documentId); var argument = documentId == null ? new SolutionArgument(null, documentId.ProjectId, documentId) : new SolutionArgument(document); RaiseDiagnosticsRemoved(StateType.Project, documentId, stateSet, argument); } } private void RaiseProjectDiagnosticsUpdated(Project project, StateSet stateSet, ImmutableArray<DiagnosticData> diagnostics) { var group = diagnostics.GroupBy(d => d.DocumentId); foreach (var kv in group) { if (kv.Key == null) { RaiseDiagnosticsCreated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), kv.ToImmutableArrayOrEmpty()); continue; } RaiseDiagnosticsCreated(StateType.Project, kv.Key, stateSet, new SolutionArgument(project.GetDocument(kv.Key)), kv.ToImmutableArrayOrEmpty()); } } private static ImmutableArray<DiagnosticData> GetDiagnosticData(ILookup<DocumentId, DiagnosticData> lookup, DocumentId documentId) { return lookup.Contains(documentId) ? lookup[documentId].ToImmutableArrayOrEmpty() : ImmutableArray<DiagnosticData>.Empty; } private void RaiseDiagnosticsCreated( StateType type, object key, StateSet stateSet, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics) { if (Owner == null) { return; } // get right arg id for the given analyzer var id = CreateArgumentKey(type, key, stateSet); Owner.RaiseDiagnosticsUpdated(this, DiagnosticsUpdatedArgs.DiagnosticsCreated(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId, diagnostics)); } private static ArgumentKey CreateArgumentKey(StateType type, object key, StateSet stateSet) { return stateSet.ErrorSourceName != null ? new HostAnalyzerKey(stateSet.Analyzer, type, key, stateSet.ErrorSourceName) : new ArgumentKey(stateSet.Analyzer, type, key); } private void RaiseDiagnosticsRemoved( StateType type, object key, StateSet stateSet, SolutionArgument solution) { if (Owner == null) { return; } // get right arg id for the given analyzer var id = CreateArgumentKey(type, key, stateSet); Owner.RaiseDiagnosticsUpdated(this, DiagnosticsUpdatedArgs.DiagnosticsRemoved(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId)); } private ImmutableArray<DiagnosticData> UpdateDocumentDiagnostics( AnalysisData existingData, ImmutableArray<TextSpan> range, ImmutableArray<DiagnosticData> memberDiagnostics, SyntaxTree tree, SyntaxNode member, int memberId) { // get old span var oldSpan = range[memberId]; // get old diagnostics var diagnostics = existingData.Items; // check quick exit cases if (diagnostics.Length == 0 && memberDiagnostics.Length == 0) { return diagnostics; } // simple case if (diagnostics.Length == 0 && memberDiagnostics.Length > 0) { return memberDiagnostics; } // regular case var result = new List<DiagnosticData>(); // update member location Contract.Requires(member.FullSpan.Start == oldSpan.Start); var delta = member.FullSpan.End - oldSpan.End; var replaced = false; foreach (var diagnostic in diagnostics) { if (diagnostic.TextSpan.Start < oldSpan.Start) { result.Add(diagnostic); continue; } if (!replaced) { result.AddRange(memberDiagnostics); replaced = true; } if (oldSpan.End <= diagnostic.TextSpan.Start) { result.Add(UpdatePosition(diagnostic, tree, delta)); continue; } } // if it haven't replaced, replace it now if (!replaced) { result.AddRange(memberDiagnostics); replaced = true; } return result.ToImmutableArray(); } private DiagnosticData UpdatePosition(DiagnosticData diagnostic, SyntaxTree tree, int delta) { var start = Math.Min(Math.Max(diagnostic.TextSpan.Start + delta, 0), tree.Length); var newSpan = new TextSpan(start, start >= tree.Length ? 0 : diagnostic.TextSpan.Length); var mappedLineInfo = tree.GetMappedLineSpan(newSpan); var originalLineInfo = tree.GetLineSpan(newSpan); return new DiagnosticData( diagnostic.Id, diagnostic.Category, diagnostic.Message, diagnostic.ENUMessageForBingSearch, diagnostic.Severity, diagnostic.DefaultSeverity, diagnostic.IsEnabledByDefault, diagnostic.WarningLevel, diagnostic.CustomTags, diagnostic.Properties, diagnostic.Workspace, diagnostic.ProjectId, new DiagnosticDataLocation(diagnostic.DocumentId, newSpan, originalFilePath: originalLineInfo.Path, originalStartLine: originalLineInfo.StartLinePosition.Line, originalStartColumn: originalLineInfo.StartLinePosition.Character, originalEndLine: originalLineInfo.EndLinePosition.Line, originalEndColumn: originalLineInfo.EndLinePosition.Character, mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(), mappedStartLine: mappedLineInfo.StartLinePosition.Line, mappedStartColumn: mappedLineInfo.StartLinePosition.Character, mappedEndLine: mappedLineInfo.EndLinePosition.Line, mappedEndColumn: mappedLineInfo.EndLinePosition.Character), description: diagnostic.Description, helpLink: diagnostic.HelpLink, isSuppressed: diagnostic.IsSuppressed); } private static IEnumerable<DiagnosticData> GetDiagnosticData(Document document, SyntaxTree tree, TextSpan? span, IEnumerable<Diagnostic> diagnostics) { return diagnostics != null ? diagnostics.Where(dx => ShouldIncludeDiagnostic(dx, tree, span)).Select(d => DiagnosticData.Create(document, d)) : null; } private static bool ShouldIncludeDiagnostic(Diagnostic diagnostic, SyntaxTree tree, TextSpan? span) { if (diagnostic == null) { return false; } if (diagnostic.Location == null || diagnostic.Location == Location.None) { return false; } if (diagnostic.Location.SourceTree != tree) { return false; } if (span == null) { return true; } return span.Value.Contains(diagnostic.Location.SourceSpan); } private static IEnumerable<DiagnosticData> GetDiagnosticData(Project project, IEnumerable<Diagnostic> diagnostics) { if (diagnostics == null) { yield break; } foreach (var diagnostic in diagnostics) { if (diagnostic.Location == null || diagnostic.Location == Location.None) { yield return DiagnosticData.Create(project, diagnostic); continue; } var document = project.GetDocument(diagnostic.Location.SourceTree); if (document == null) { continue; } yield return DiagnosticData.Create(document, diagnostic); } } private static async Task<IEnumerable<DiagnosticData>> GetSyntaxDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_SyntaxDiagnostic, GetSyntaxLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false); var diagnostics = await userDiagnosticDriver.GetSyntaxDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private static async Task<IEnumerable<DiagnosticData>> GetSemanticDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_SemanticDiagnostic, GetSemanticLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false); var diagnostics = await userDiagnosticDriver.GetSemanticDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private static async Task<IEnumerable<DiagnosticData>> GetProjectDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, userDiagnosticDriver.Project, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var diagnostics = await userDiagnosticDriver.GetProjectDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Project, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private void ClearDocumentStates( Document document, IEnumerable<StateSet> states, bool raiseEvent, bool includeProjectState, CancellationToken cancellationToken) { // Compiler + User diagnostics foreach (var state in states) { for (var stateType = 0; stateType < s_stateTypeCount; stateType++) { if (!includeProjectState && stateType == (int)StateType.Project) { // don't re-set project state type continue; } cancellationToken.ThrowIfCancellationRequested(); ClearDocumentState(document, state, (StateType)stateType, raiseEvent); } } } private void ClearDocumentState(Document document, StateSet stateSet, StateType type, bool raiseEvent) { var state = stateSet.GetState(type); // remove saved info state.Remove(document.Id); if (raiseEvent) { // raise diagnostic updated event var documentId = document.Id; var solutionArgs = new SolutionArgument(document); RaiseDiagnosticsRemoved(type, document.Id, stateSet, solutionArgs); } } private void ClearProjectStatesAsync(Project project, IEnumerable<StateSet> states, CancellationToken cancellationToken) { foreach (var document in project.Documents) { ClearDocumentStates(document, states, raiseEvent: true, includeProjectState: true, cancellationToken: cancellationToken); } foreach (var stateSet in states) { cancellationToken.ThrowIfCancellationRequested(); ClearProjectState(project, stateSet); } } private void ClearProjectState(Project project, StateSet stateSet) { var state = stateSet.GetState(StateType.Project); // remove saved cache state.Remove(project.Id); // raise diagnostic updated event var solutionArgs = new SolutionArgument(project); RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, solutionArgs); } private async Task ClearExistingDiagnostics(Document document, StateSet stateSet, StateType type, CancellationToken cancellationToken) { var state = stateSet.GetState(type); var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false); if (existingData?.Items.Length > 0) { ClearDocumentState(document, stateSet, type, raiseEvent: true); } } private async Task ClearExistingDiagnostics(Project project, StateSet stateSet, CancellationToken cancellationToken) { var state = stateSet.GetState(StateType.Project); var existingData = await state.TryGetExistingDataAsync(project, cancellationToken).ConfigureAwait(false); if (existingData?.Items.Length > 0) { ClearProjectState(project, stateSet); } } private static string GetSyntaxLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer) { return string.Format("syntax: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString()); } private static string GetSemanticLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer) { return string.Format("semantic: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString()); } private static string GetProjectLogMessage(Project project, DiagnosticAnalyzer analyzer) { return string.Format("project: {0}, {1}", project.FilePath ?? project.Name, analyzer.ToString()); } private static string GetResetLogMessage(Document document) { return string.Format("document reset: {0}", document.FilePath ?? document.Name); } private static string GetOpenLogMessage(Document document) { return string.Format("document open: {0}", document.FilePath ?? document.Name); } private static string GetRemoveLogMessage(DocumentId id) { return string.Format("document remove: {0}", id.ToString()); } private static string GetRemoveLogMessage(ProjectId id) { return string.Format("project remove: {0}", id.ToString()); } public override Task NewSolutionSnapshotAsync(Solution newSolution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } } }
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. /* Copyright 2007-2013 The NGenerics Team (https://github.com/ngenerics/ngenerics/wiki/Team) This program is licensed under the GNU Lesser General Public License (LGPL). You should have received a copy of the license along with the source code. If not, an online copy of the license can be found at http://www.gnu.org/copyleft/lesser.html. Community contributions : - TKey Peek(out TPriority) contributed by Karl Shulze (http://www.karlschulze.com/).</remarks> */ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using NGenerics.Comparers; using NGenerics.DataStructures.Trees; using NGenerics.Util; namespace NGenerics.DataStructures.Queues { /// <summary> /// An implementation of a Priority Queue (can be <see cref="PriorityQueueType.Minimum"/> or <see cref="PriorityQueueType.Maximum"/>). /// </summary> /// <typeparam name="TPriority">The type of the priority in the <see cref="PriorityQueue{TPriority, TValue}"/>.</typeparam> /// <typeparam name="TValue">The type of the elements in the <see cref="PriorityQueue{TPriority, TValue}"/>.</typeparam> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] //[Serializable] public class PriorityQueue<TValue, TPriority> : ICollection<TValue>, IQueue<TValue> { #region Globals private readonly RedBlackTreeList<TPriority, TValue> _tree; private TPriority _defaultPriority; private readonly PriorityQueueType _queueType; #endregion #region Construction /// <param name="queueType">Type of the queue.</param> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="Constructor" lang="cs" title="The following example shows how to use the default constructor."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="Constructor" lang="vbnet" title="The following example shows how to use the default constructor."/> /// </example> public PriorityQueue(PriorityQueueType queueType) : this(queueType, Comparer<TPriority>.Default) { } /// <inheritdoc/> public PriorityQueue(PriorityQueueType queueType, IComparer<TPriority> comparer) { if ((queueType != PriorityQueueType.Minimum) && (queueType != PriorityQueueType.Maximum)) { throw new ArgumentOutOfRangeException("queueType"); } _queueType = queueType; _tree = new RedBlackTreeList<TPriority, TValue>(comparer); } /// <summary> /// Initializes a new instance of the <see cref="PriorityQueue&lt;TValue, TPriority&gt;"/> class. /// </summary> /// <param name="queueType">Type of the queue.</param> /// <param name="comparison">The comparison.</param> /// <inheritdoc/> public PriorityQueue(PriorityQueueType queueType, Comparison<TPriority> comparison) : this(queueType, new ComparisonComparer<TPriority>(comparison)) { } #endregion #region IQueue<T> Members /// <inheritdoc /> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="Enqueue" lang="cs" title="The following example shows how to use the Enqueue method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="Enqueue" lang="vbnet" title="The following example shows how to use the Enqueue method."/> /// </example> public void Enqueue(TValue item) { Add(item); } /// <summary> /// Enqueues the specified item. /// </summary> /// <param name="item">The item.</param> /// <param name="priority">The priority.</param> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="EnqueuePriority" lang="cs" title="The following example shows how to use the Enqueue method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="EnqueuePriority" lang="vbnet" title="The following example shows how to use the Enqueue method."/> /// </example> public void Enqueue(TValue item, TPriority priority) { Add(item, priority); } /// <summary> /// Dequeues the item at the front of the queue. /// </summary> /// <returns>The item at the front of the queue.</returns> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="Dequeue" lang="cs" title="The following example shows how to use the Dequeue method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="Dequeue" lang="vbnet" title="The following example shows how to use the Dequeue method."/> /// </example> public TValue Dequeue() { TPriority priority; return Dequeue(out priority); } /// <summary> /// Peeks at the item in the front of the queue, without removing it. /// </summary> /// <returns>The item at the front of the queue.</returns> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="Peek" lang="cs" title="The following example shows how to use the Peek method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="Peek" lang="vbnet" title="The following example shows how to use the Peek method."/> /// </example> public TValue Peek() { var association = GetNextItem(); // Always dequeue in FIFO manner return association.Value.First.Value; } /// <summary> /// Peeks at the item in the front of the queue, without removing it. /// </summary> /// <param name="priority">The priority of the item.</param> /// <returns>The item at the front of the queue.</returns> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="PeekPriority" lang="cs" title="The following example shows how to use the Peek method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="PeekPriority" lang="vbnet" title="The following example shows how to use the Peek method."/> /// </example> public TValue Peek(out TPriority priority) { var association = GetNextItem(); var item = association.Value.First.Value; priority = association.Key; return item; } #endregion #region ICollection<T> Members /// <inheritdoc /> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="IsReadOnly" lang="cs" title="The following example shows how to use the IsReadOnly property."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="IsReadOnly" lang="vbnet" title="The following example shows how to use the IsReadOnly property."/> /// </example> public bool IsReadOnly => false; #endregion #region IEnumerable Members /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="GetEnumerator" lang="cs" title="The following example shows how to use the GetEnumerator method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="GetEnumerator" lang="vbnet" title="The following example shows how to use the GetEnumerator method."/> /// </example> public IEnumerator<TValue> GetEnumerator() { return _tree.GetValueEnumerator(); } #endregion #region Public Members /// <inheritdoc /> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="Count" lang="cs" title="The following example shows how to use the Count property."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="Count" lang="vbnet" title="The following example shows how to use the Count property."/> /// </example> public int Count { get; private set; } /// <inheritdoc /> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="Contains" lang="cs" title="The following example shows how to use the Contains method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="Contains" lang="vbnet" title="The following example shows how to use the Contains method."/> /// </example> public bool Contains(TValue item) { return _tree.ContainsValue(item); } /// <inheritdoc /> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="CopyTo" lang="cs" title="The following example shows how to use the CopyTo method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="CopyTo" lang="vbnet" title="The following example shows how to use the CopyTo method."/> /// </example> public void CopyTo(TValue[] array, int arrayIndex) { #region Validation Guard.ArgumentNotNull(array, "array"); if ((array.Length - arrayIndex) < Count) { throw new ArgumentException(Constants.NotEnoughSpaceInTheTargetArray, "array"); } #endregion foreach (var association in _tree) { var items = association.Value; foreach (var item in items) { array.SetValue(item, arrayIndex++); } } } /// <inheritdoc /> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="Add" lang="cs" title="The following example shows how to use the Add method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="Add" lang="vbnet" title="The following example shows how to use the Add method."/> /// </example> public void Add(TValue item) { Add(item, _defaultPriority); } /// <summary> /// Adds an item to the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param> /// <param name="priority">The priority of the item.</param> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="AddPriority" lang="cs" title="The following example shows how to use the Add method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="AddPriority" lang="vbnet" title="The following example shows how to use the Add method."/> /// </example> public void Add(TValue item, TPriority priority) { AddItem(item, priority); } /// <inheritdoc /> public bool Remove(TValue item) { TPriority priority; return Remove(item, out priority); } /// <summary> /// Returns an enumerator that iterates through the keys in the collection. /// </summary> /// <returns>A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the keys in the collection.</returns> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="GetKeyEnumerator" lang="cs" title="The following example shows how to use the GetKeyEnumerator method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="GetKeyEnumerator" lang="vbnet" title="The following example shows how to use the GetKeyEnumerator method."/> /// </example> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public IEnumerator<KeyValuePair<TPriority, TValue>> GetKeyEnumerator() { return _tree.GetKeyEnumerator(); } /// <inheritdoc /> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="Clear" lang="cs" title="The following example shows how to use the Clear method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="Clear" lang="vbnet" title="The following example shows how to use the Clear method."/> /// </example> public void Clear() { ClearItems(); } /// <summary> /// Dequeues the item from the head of the queue. /// </summary> /// <param name="priority">The priority of the item to dequeue.</param> /// <returns>The item at the head of the queue.</returns> /// <exception cref="InvalidOperationException">The <see cref="PriorityQueue{TValue, TPriority}"/> is empty.</exception> /// <example> /// <code source="..\..\Source\Examples\ExampleLibraryCSharp\DataStructures\Queues\PriorityQueueExamples.cs" region="DequeueWithPriority" lang="cs" title="The following example shows how to use the Dequeue method."/> /// <code source="..\..\Source\Examples\ExampleLibraryVB\DataStructures\Queues\PriorityQueueExamples.vb" region="DequeueWithPriority" lang="vbnet" title="The following example shows how to use the Dequeue method."/> /// </example> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")] public TValue Dequeue(out TPriority priority) { return DequeueItem(out priority); } /// <summary> /// Dequeues the item at the front of the queue. /// </summary> /// <returns>The item at the front of the queue.</returns> /// <remarks> /// <b>Notes to Inheritors: </b> /// Derived classes can override this method to change the behavior of the <see cref="Dequeue()"/> or <see cref="Dequeue(out TPriority)"/> methods. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")] protected virtual TValue DequeueItem(out TPriority priority) { var association = GetNextItem(); var item = association.Value.First.Value; association.Value.RemoveFirst(); var key = association.Key; if (association.Value.Count == 0) { _tree.Remove(association.Key); } Count--; priority = key; return item; } /// <summary> /// Gets or sets the default priority. /// </summary> /// <value>The default priority.</value> public TPriority DefaultPriority { get { return _defaultPriority; } set { _defaultPriority = value; } } /// <summary> /// Removes the first occurrence of the specified item from the property queue. /// </summary> /// <param name="item">The item to remove.</param> /// <param name="priority">The priority associated with the item.</param> /// <returns><c>true</c> if the item exists in the <see cref="PriorityQueue{TValue, TPriority}"/> and has been removed; otherwise <c>false</c>.</returns> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#")] public bool Remove(TValue item, out TPriority priority) { return RemoveItem(item, out priority); } /// <summary> /// Removes the item. /// </summary> /// <param name="item">The item to remove</param> /// <param name="priority">The priority of the item that was removed.</param> /// <returns>An indication of whether the item was found, and removed.</returns> /// <remarks> /// <b>Notes to Inheritors: </b> /// Derived classes can override this method to change the behavior of the <see cref="Remove(TValue,out TPriority)"/> method. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#")] protected virtual bool RemoveItem(TValue item, out TPriority priority) { var removed = _tree.Remove(item, out priority); if (removed) { Count--; } return removed; } /// <summary> /// Removes the items with the specified priority. /// </summary> /// <param name="priority">The priority.</param> /// <returns><c>true</c> if the priority exists in the <see cref="PriorityQueue{TValue, TPriority}"/> and has been removed; otherwise <c>false</c>.</returns> public bool RemovePriorityGroup(TPriority priority) { return RemoveItems(priority); } /// <summary> /// Removes the items from the collection with the specified priority. /// </summary> /// <param name="priority">The priority to search for.</param> /// <returns>An indication of whether items were found having the specified priority.</returns> protected virtual bool RemoveItems(TPriority priority) { LinkedList<TValue> items; if (_tree.TryGetValue(priority, out items)) { _tree.Remove(priority); Count -= items.Count; return true; } return false; } /// <summary> /// Removes the items with the specified priority. /// </summary> /// <param name="priority">The priority.</param> /// <returns>The items with the specified priority.</returns> public IList<TValue> GetPriorityGroup(TPriority priority) { LinkedList<TValue> items; return _tree.TryGetValue(priority, out items) ? new List<TValue>(items) : new List<TValue>(); } /// <summary> /// Adds the specified items to the priority queue with the specified priority. /// </summary> /// <param name="items">The items.</param> /// <param name="priority">The priority.</param> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference (<c>Nothing</c> in Visual Basic).</exception> public void AddPriorityGroup(IList<TValue> items, TPriority priority) { #region Validation Guard.ArgumentNotNull(items, "items"); #endregion AddPriorityGroupItem(items, priority); } /// <summary> /// Adds the specified items to the priority queue with the specified priority. /// </summary> /// <param name="items">The items.</param> /// <param name="priority">The priority.</param> /// <remarks> /// <b>Notes to Inheritors: </b> /// Derived classes can override this method to change the behavior of the <see cref="AddPriorityGroup"/> method. /// </remarks> protected virtual void AddPriorityGroupItem(IList<TValue> items, TPriority priority) { LinkedList<TValue> currentValues; if (_tree.TryGetValue(priority, out currentValues)) { for (var i = 0; i < items.Count; i++) { currentValues.AddLast(items[i]); } } else { currentValues = new LinkedList<TValue>(items); _tree.Add(priority, currentValues); } } #endregion #region Protected Members /// <summary> /// Adds the item to the queue. /// </summary> /// <param name="item">The item to add.</param> /// <param name="priority">The priority of the item.</param> /// <remarks> /// <b>Notes to Inheritors: </b> /// Derived classes can override this method to change the behavior of the <see cref="Add(TValue,TPriority)"/> method. /// </remarks> protected virtual void AddItem(TValue item, TPriority priority) { LinkedList<TValue> list; if (_tree.TryGetValue(priority, out list)) { list.AddLast(item); } else { list = new LinkedList<TValue>(); list.AddLast(item); _tree.Add(priority, list); } Count++; } /// <summary> /// Clears all the objects in this instance. /// </summary> /// <remarks> /// <b>Notes to Inheritors: </b> /// Derived classes can override this method to change the behavior of the <see cref="Clear"/> method. /// </remarks> protected virtual void ClearItems() { _tree.Clear(); Count = 0; } #endregion #region Private Members /// <summary> /// Checks if the list is not empty, and if it is, throw an exception. /// </summary> private void CheckTreeNotEmpty() { if (_tree.Count == 0) { throw new InvalidOperationException("The Priority Queue is empty."); } } /// <summary> /// Gets the next item. /// </summary> private KeyValuePair<TPriority, LinkedList<TValue>> GetNextItem() { #region Validation CheckTreeNotEmpty(); #endregion return _queueType == PriorityQueueType.Maximum ? _tree.Maximum : _tree.Minimum; } #endregion } }
using UnityEngine; using System; using System.IO; using System.Collections.Generic; using Oculus.Avatar; using Oculus.Platform; using Oculus.Platform.Models; // This class coordinates communication with the Oculus Platform // Service running in your device. public class SocialPlatformManager : MonoBehaviour { private static readonly Vector3 START_ROTATION_ONE = new Vector3(0, 180, 0); private static readonly Vector3 START_POSITION_ONE = new Vector3(0, 4, 5); private static readonly Vector3 START_ROTATION_TWO = new Vector3(0, 0, 0); private static readonly Vector3 START_POSITION_TWO = new Vector3(0, 4, -5); private static readonly Vector3 START_ROTATION_THREE = new Vector3(0, 270, 0); private static readonly Vector3 START_POSITION_THREE = new Vector3(5, 4, 0); private static readonly Vector3 START_ROTATION_FOUR = new Vector3(0, 90, 0); private static readonly Vector3 START_POSITION_FOUR = new Vector3(-5, 4, 0); private static readonly Color BLACK = new Color(0.0f, 0.0f, 0.0f); private static readonly Color WHITE = new Color(1.0f, 1.0f, 1.0f); private static readonly Color CYAN = new Color(0.0f, 1.0f, 1.0f); private static readonly Color BLUE = new Color(0.0f, 0.0f, 1.0f); private static readonly Color GREEN = new Color(0.0f, 1.0f, 0.0f); public Oculus.Platform.CAPI.FilterCallback micFilterDelegate = new Oculus.Platform.CAPI.FilterCallback(SocialPlatformManager.MicFilter); private float voiceCurrent = 0.0f; // Local player private UInt32 packetSequence = 0; public OvrAvatar localAvatarPrefab; public OvrAvatar remoteAvatarPrefab; public GameObject helpPanel; protected MeshRenderer helpMesh; public Material riftMaterial; public Material gearMaterial; protected OvrAvatar localAvatar; protected GameObject localTrackingSpace; protected GameObject localPlayerHead; // Remote players protected Dictionary<ulong, RemotePlayer> remoteUsers = new Dictionary<ulong, RemotePlayer>(); // GameObject that represents the center sphere as a visual status indicator of the room public GameObject roomSphere; protected MeshRenderer sphereMesh; public GameObject roomFloor; protected MeshRenderer floorMesh; protected State currentState; protected static SocialPlatformManager s_instance = null; protected RoomManager roomManager; protected P2PManager p2pManager; protected VoipManager voipManager; // my Application-scoped Oculus ID protected ulong myID; // my Oculus user name protected string myOculusID; // animating the mouth for voip public static readonly float VOIP_SCALE = 2f; public virtual void Update() { // Look for updates from remote users p2pManager.GetRemotePackets(); // update avatar mouths to match voip volume foreach (KeyValuePair<ulong, RemotePlayer> kvp in remoteUsers) { float remoteVoiceCurrent = Mathf.Clamp(kvp.Value.voipSource.peakAmplitude * VOIP_SCALE, 0f, 1f); kvp.Value.RemoteAvatar.VoiceAmplitude = remoteVoiceCurrent; } if (localAvatar != null) { localAvatar.VoiceAmplitude = Mathf.Clamp(voiceCurrent * VOIP_SCALE, 0f, 1f); } } #region Initialization and Shutdown public virtual void Awake() { LogOutputLine("Start Log."); // Grab the MeshRenderers. We'll be using the material colour to visually show status helpMesh = helpPanel.GetComponent<MeshRenderer>(); sphereMesh = roomSphere.GetComponent<MeshRenderer>(); floorMesh = roomFloor.GetComponent<MeshRenderer>(); // Set up the local player localTrackingSpace = this.transform.Find("OVRCameraRig/TrackingSpace").gameObject; localPlayerHead = this.transform.Find("OVRCameraRig/TrackingSpace/CenterEyeAnchor").gameObject; // make sure only one instance of this manager ever exists if (s_instance != null) { Destroy(gameObject); return; } s_instance = this; DontDestroyOnLoad(gameObject); TransitionToState(State.INITIALIZING); Core.Initialize(); roomManager = new RoomManager(); p2pManager = new P2PManager(); voipManager = new VoipManager(); } public virtual void Start() { // First thing we should do is perform an entitlement check to make sure // we successfully connected to the Oculus Platform Service. Entitlements.IsUserEntitledToApplication().OnComplete(IsEntitledCallback); Oculus.Platform.Request.RunCallbacks(); } void IsEntitledCallback(Message msg) { if (msg.IsError) { TerminateWithError(msg); return; } // Next get the identity of the user that launched the Application. Users.GetLoggedInUser().OnComplete(GetLoggedInUserCallback); Oculus.Platform.Request.RunCallbacks(); } void GetLoggedInUserCallback(Message<User> msg) { if (msg.IsError) { TerminateWithError(msg); return; } myID = msg.Data.ID; myOculusID = msg.Data.OculusID; localAvatar = Instantiate(localAvatarPrefab); localTrackingSpace = this.transform.Find("OVRCameraRig/TrackingSpace").gameObject; localAvatar.transform.SetParent(localTrackingSpace.transform, false); localAvatar.transform.localPosition = new Vector3(0, 0, 0); localAvatar.transform.localRotation = Quaternion.identity; if (UnityEngine.Application.platform == RuntimePlatform.Android) { helpPanel.transform.SetParent(localAvatar.transform.Find("body"), false); helpPanel.transform.localPosition = new Vector3(0, 1.0f, 1.0f); helpMesh.material = gearMaterial; } else { helpPanel.transform.SetParent(localAvatar.transform.Find("hand_left"), false); helpPanel.transform.localPosition = new Vector3(0, 0.2f, 0.2f); helpMesh.material = riftMaterial; } localAvatar.oculusUserID = myID.ToString(); localAvatar.RecordPackets = true; localAvatar.PacketRecorded += OnLocalAvatarPacketRecorded; localAvatar.EnableMouthVertexAnimation = true; Quaternion rotation = Quaternion.identity; switch (UnityEngine.Random.Range(0, 4)) { case 0: rotation.eulerAngles = START_ROTATION_ONE; this.transform.localPosition = START_POSITION_ONE; this.transform.localRotation = rotation; break; case 1: rotation.eulerAngles = START_ROTATION_TWO; this.transform.localPosition = START_POSITION_TWO; this.transform.localRotation = rotation; break; case 2: rotation.eulerAngles = START_ROTATION_THREE; this.transform.localPosition = START_POSITION_THREE; this.transform.localRotation = rotation; break; case 3: default: rotation.eulerAngles = START_ROTATION_FOUR; this.transform.localPosition = START_POSITION_FOUR; this.transform.localRotation = rotation; break; } TransitionToState(State.CHECKING_LAUNCH_STATE); // If the user launched the app by accepting the notification, then we want to // join that room. If not, try to find a friend's room to join if (!roomManager.CheckForInvite()) { SocialPlatformManager.LogOutput("No invite on launch, looking for a friend to join."); Users.GetLoggedInUserFriendsAndRooms() .OnComplete(GetLoggedInUserFriendsAndRoomsCallback); } Voip.SetMicrophoneFilterCallback(micFilterDelegate); } void GetLoggedInUserFriendsAndRoomsCallback(Message<UserAndRoomList> msg) { if (msg.IsError) { return; } foreach (UserAndRoom el in msg.Data) { // see if any friends are in a joinable room if (el.User == null) continue; if (el.RoomOptional == null) continue; if (el.RoomOptional.IsMembershipLocked == true) continue; if (el.RoomOptional.Joinability != RoomJoinability.CanJoin) continue; if (el.RoomOptional.JoinPolicy == RoomJoinPolicy.None) continue; SocialPlatformManager.LogOutput("Trying to join room " + el.RoomOptional.ID + ", friend " + el.User.OculusID); roomManager.JoinExistingRoom(el.RoomOptional.ID); return; } SocialPlatformManager.LogOutput("No friend to join. Creating my own room."); // didn't find any open rooms, start a new room roomManager.CreateRoom(); TransitionToState(State.CREATING_A_ROOM); } public void OnLocalAvatarPacketRecorded(object sender, OvrAvatar.PacketEventArgs args) { var size = Oculus.Avatar.CAPI.ovrAvatarPacket_GetSize(args.Packet.ovrNativePacket); byte[] toSend = new byte[size]; Oculus.Avatar.CAPI.ovrAvatarPacket_Write(args.Packet.ovrNativePacket, size, toSend); foreach (KeyValuePair<ulong, RemotePlayer> kvp in remoteUsers) { //LogOutputLine("Sending avatar Packet to " + kvp.Key); p2pManager.SendAvatarUpdate(kvp.Key, this.localAvatar.transform, packetSequence, toSend); } packetSequence++; } public void OnApplicationQuit() { roomManager.LeaveCurrentRoom(); foreach (KeyValuePair<ulong, RemotePlayer> kvp in remoteUsers) { p2pManager.Disconnect(kvp.Key); voipManager.Disconnect(kvp.Key); } LogOutputLine("End Log."); } public void AddUser(ulong userID, ref RemotePlayer remoteUser) { remoteUsers.Add(userID, remoteUser); } public void LogOutputLine(string line) { Debug.Log(Time.time + ": " + line); } // For most errors we terminate the Application since this example doesn't make // sense if the user is disconnected. public static void TerminateWithError(Message msg) { s_instance.LogOutputLine("Error: " + msg.GetError().Message); UnityEngine.Application.Quit(); } #endregion #region Properties public static State CurrentState { get { return s_instance.currentState; } } public static ulong MyID { get { if (s_instance != null) { return s_instance.myID; } else { return 0; } } } public static string MyOculusID { get { if (s_instance != null && s_instance.myOculusID != null) { return s_instance.myOculusID; } else { return string.Empty; } } } #endregion #region State Management public enum State { // loading platform library, checking application entitlement, // getting the local user info INITIALIZING, // Checking to see if we were launched from an invite CHECKING_LAUNCH_STATE, // Creating a room to join CREATING_A_ROOM, // in this state we've create a room, and hopefully // sent some invites, and we're waiting people to join WAITING_IN_A_ROOM, // in this state we're attempting to join a room from an invite JOINING_A_ROOM, // we're in a room with others CONNECTED_IN_A_ROOM, // Leaving a room LEAVING_A_ROOM, // shutdown any connections and leave the current room SHUTDOWN, }; public static void TransitionToState(State newState) { if (s_instance) { s_instance.LogOutputLine("State " + s_instance.currentState + " -> " + newState); } if (s_instance && s_instance.currentState != newState) { s_instance.currentState = newState; // state transition logic switch (newState) { case State.SHUTDOWN: s_instance.OnApplicationQuit(); break; default: break; } } SetSphereColorForState(); } private static void SetSphereColorForState() { switch (s_instance.currentState) { case State.INITIALIZING: case State.SHUTDOWN: s_instance.sphereMesh.material.color = BLACK; break; case State.WAITING_IN_A_ROOM: s_instance.sphereMesh.material.color = WHITE; break; case State.CONNECTED_IN_A_ROOM: s_instance.sphereMesh.material.color = CYAN; break; default: break; } } public static void SetFloorColorForState(bool host) { if (host) { s_instance.floorMesh.material.color = BLUE; } else { s_instance.floorMesh.material.color = GREEN; } } public static void MarkAllRemoteUsersAsNotInRoom() { foreach (KeyValuePair<ulong, RemotePlayer> kvp in s_instance.remoteUsers) { kvp.Value.stillInRoom = false; } } public static void MarkRemoteUserInRoom(ulong userID) { RemotePlayer remoteUser = new RemotePlayer(); if (s_instance.remoteUsers.TryGetValue(userID, out remoteUser)) { remoteUser.stillInRoom = true; } } public static void ForgetRemoteUsersNotInRoom() { List<ulong> toPurge = new List<ulong>(); foreach (KeyValuePair<ulong, RemotePlayer> kvp in s_instance.remoteUsers) { if (kvp.Value.stillInRoom == false) { toPurge.Add(kvp.Key); } } foreach (ulong key in toPurge) { RemoveRemoteUser(key); } } public static void LogOutput(string line) { s_instance.LogOutputLine(Time.time + ": " + line); } public static bool IsUserInRoom(ulong userID) { return s_instance.remoteUsers.ContainsKey(userID); } public static void AddRemoteUser(ulong userID) { RemotePlayer remoteUser = new RemotePlayer(); remoteUser.RemoteAvatar = Instantiate(s_instance.remoteAvatarPrefab); remoteUser.RemoteAvatar.oculusUserID = userID.ToString(); remoteUser.RemoteAvatar.ShowThirdPerson = true; remoteUser.RemoteAvatar.EnableMouthVertexAnimation = true; remoteUser.p2pConnectionState = PeerConnectionState.Unknown; remoteUser.voipConnectionState = PeerConnectionState.Unknown; remoteUser.stillInRoom = true; remoteUser.remoteUserID = userID; s_instance.AddUser(userID, ref remoteUser); s_instance.p2pManager.ConnectTo(userID); s_instance.voipManager.ConnectTo(userID); remoteUser.voipSource = remoteUser.RemoteAvatar.gameObject.AddComponent<VoipAudioSourceHiLevel>(); remoteUser.voipSource.senderID = userID; s_instance.LogOutputLine("Adding User " + userID); } public static void RemoveRemoteUser(ulong userID) { RemotePlayer remoteUser = new RemotePlayer(); if (s_instance.remoteUsers.TryGetValue(userID, out remoteUser)) { Destroy(remoteUser.RemoteAvatar.GetComponent<VoipAudioSourceHiLevel>(), 0); Destroy(remoteUser.RemoteAvatar.gameObject, 0); s_instance.remoteUsers.Remove(userID); s_instance.LogOutputLine("Removing User " + userID); } } public void UpdateVoiceData(short[] pcmData) { float voiceMax = 0.0f; float[] floats = new float[pcmData.Length]; for (int n = 0; n < pcmData.Length; n++) { float cur = floats[n] = (float)pcmData[n] / (float)short.MaxValue; if (cur > voiceMax) { voiceMax = cur; } } voiceCurrent = voiceMax; } public static void MicFilter(short[] pcmData, System.UIntPtr pcmDataLength, int frequency, int numChannels) { s_instance.UpdateVoiceData(pcmData); } public static RemotePlayer GetRemoteUser(ulong userID) { RemotePlayer remoteUser = new RemotePlayer(); if (s_instance.remoteUsers.TryGetValue(userID, out remoteUser)) { return remoteUser; } else { return null; } } #endregion }
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 VideoStoreRedux.Areas.HelpPage.ModelDescriptions; using VideoStoreRedux.Areas.HelpPage.Models; namespace VideoStoreRedux.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); } } } }
// 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.Collections.ObjectModel; using System.Text; using System.Xml; namespace System.ServiceModel.Channels { public sealed class AddressHeaderCollection : ReadOnlyCollection<AddressHeader> { public AddressHeaderCollection() : base(new List<AddressHeader>()) { } public AddressHeaderCollection(IEnumerable<AddressHeader> addressHeaders) : base(new List<AddressHeader>(addressHeaders)) { // avoid allocating an enumerator when possible IList<AddressHeader> collection = addressHeaders as IList<AddressHeader>; if (collection != null) { for (int i = 0; i < collection.Count; i++) { if (collection[i] == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.MessageHeaderIsNull0)); } } } else { foreach (AddressHeader addressHeader in addressHeaders) { if (addressHeaders == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.MessageHeaderIsNull0)); } } } } internal static AddressHeaderCollection EmptyHeaderCollection { get; } = new AddressHeaderCollection(); private int InternalCount { get { if (this == (object)EmptyHeaderCollection) { return 0; } return Count; } } public void AddHeadersTo(Message message) { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(message)); } for (int i = 0; i < InternalCount; i++) { message.Headers.Add(this[i].ToMessageHeader()); } } public AddressHeader[] FindAll(string name, string ns) { if (name == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(name))); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(ns))); } List<AddressHeader> results = new List<AddressHeader>(); for (int i = 0; i < Count; i++) { AddressHeader header = this[i]; if (header.Name == name && header.Namespace == ns) { results.Add(header); } } return results.ToArray(); } public AddressHeader FindHeader(string name, string ns) { if (name == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(name))); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(ns))); } AddressHeader matchingHeader = null; for (int i = 0; i < Count; i++) { AddressHeader header = this[i]; if (header.Name == name && header.Namespace == ns) { if (matchingHeader != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MultipleMessageHeaders, name, ns))); } matchingHeader = header; } } return matchingHeader; } internal bool IsEquivalent(AddressHeaderCollection col) { if (InternalCount != col.InternalCount) { return false; } StringBuilder builder = new StringBuilder(); Dictionary<string, int> myHeaders = new Dictionary<string, int>(); PopulateHeaderDictionary(builder, myHeaders); Dictionary<string, int> otherHeaders = new Dictionary<string, int>(); col.PopulateHeaderDictionary(builder, otherHeaders); if (myHeaders.Count != otherHeaders.Count) { return false; } foreach (KeyValuePair<string, int> pair in myHeaders) { int count; if (otherHeaders.TryGetValue(pair.Key, out count)) { if (count != pair.Value) { return false; } } else { return false; } } return true; } internal void PopulateHeaderDictionary(StringBuilder builder, Dictionary<string, int> headers) { string key; for (int i = 0; i < InternalCount; ++i) { builder.Remove(0, builder.Length); key = this[i].GetComparableForm(builder); if (headers.ContainsKey(key)) { headers[key] = headers[key] + 1; } else { headers.Add(key, 1); } } } internal static AddressHeaderCollection ReadServiceParameters(XmlDictionaryReader reader) { return ReadServiceParameters(reader, false); } internal static AddressHeaderCollection ReadServiceParameters(XmlDictionaryReader reader, bool isReferenceProperty) { reader.MoveToContent(); if (reader.IsEmptyElement) { reader.Skip(); return null; } else { reader.ReadStartElement(); List<AddressHeader> headerList = new List<AddressHeader>(); while (reader.IsStartElement()) { headerList.Add(new BufferedAddressHeader(reader, isReferenceProperty)); } reader.ReadEndElement(); return new AddressHeaderCollection(headerList); } } internal bool HasReferenceProperties { get { for (int i = 0; i < InternalCount; i++) { if (this[i].IsReferenceProperty) { return true; } } return false; } } internal bool HasNonReferenceProperties { get { for (int i = 0; i < InternalCount; i++) { if (!this[i].IsReferenceProperty) { return true; } } return false; } } internal void WriteReferencePropertyContentsTo(XmlDictionaryWriter writer) { for (int i = 0; i < InternalCount; i++) { if (this[i].IsReferenceProperty) { this[i].WriteAddressHeader(writer); } } } internal void WriteNonReferencePropertyContentsTo(XmlDictionaryWriter writer) { for (int i = 0; i < InternalCount; i++) { if (!this[i].IsReferenceProperty) { this[i].WriteAddressHeader(writer); } } } internal void WriteContentsTo(XmlDictionaryWriter writer) { for (int i = 0; i < InternalCount; i++) { this[i].WriteAddressHeader(writer); } } } }
// 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.IO; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public abstract class HttpContent : IDisposable { private HttpContentHeaders _headers; private MemoryStream _bufferedContent; private object _contentReadStream; // Stream or Task<Stream> private bool _disposed; private bool _canCalculateLength; internal const int MaxBufferSize = int.MaxValue; internal static readonly Encoding DefaultStringEncoding = Encoding.UTF8; private const int UTF8CodePage = 65001; private const int UTF8PreambleLength = 3; private const byte UTF8PreambleByte0 = 0xEF; private const byte UTF8PreambleByte1 = 0xBB; private const byte UTF8PreambleByte2 = 0xBF; private const int UTF8PreambleFirst2Bytes = 0xEFBB; #if !uap // UTF32 not supported on Phone private const int UTF32CodePage = 12000; private const int UTF32PreambleLength = 4; private const byte UTF32PreambleByte0 = 0xFF; private const byte UTF32PreambleByte1 = 0xFE; private const byte UTF32PreambleByte2 = 0x00; private const byte UTF32PreambleByte3 = 0x00; #endif private const int UTF32OrUnicodePreambleFirst2Bytes = 0xFFFE; private const int UnicodeCodePage = 1200; private const int UnicodePreambleLength = 2; private const byte UnicodePreambleByte0 = 0xFF; private const byte UnicodePreambleByte1 = 0xFE; private const int BigEndianUnicodeCodePage = 1201; private const int BigEndianUnicodePreambleLength = 2; private const byte BigEndianUnicodePreambleByte0 = 0xFE; private const byte BigEndianUnicodePreambleByte1 = 0xFF; private const int BigEndianUnicodePreambleFirst2Bytes = 0xFEFF; #if DEBUG static HttpContent() { // Ensure the encoding constants used in this class match the actual data from the Encoding class AssertEncodingConstants(Encoding.UTF8, UTF8CodePage, UTF8PreambleLength, UTF8PreambleFirst2Bytes, UTF8PreambleByte0, UTF8PreambleByte1, UTF8PreambleByte2); #if !uap // UTF32 not supported on Phone AssertEncodingConstants(Encoding.UTF32, UTF32CodePage, UTF32PreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UTF32PreambleByte0, UTF32PreambleByte1, UTF32PreambleByte2, UTF32PreambleByte3); #endif AssertEncodingConstants(Encoding.Unicode, UnicodeCodePage, UnicodePreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UnicodePreambleByte0, UnicodePreambleByte1); AssertEncodingConstants(Encoding.BigEndianUnicode, BigEndianUnicodeCodePage, BigEndianUnicodePreambleLength, BigEndianUnicodePreambleFirst2Bytes, BigEndianUnicodePreambleByte0, BigEndianUnicodePreambleByte1); } private static void AssertEncodingConstants(Encoding encoding, int codePage, int preambleLength, int first2Bytes, params byte[] preamble) { Debug.Assert(encoding != null); Debug.Assert(preamble != null); Debug.Assert(codePage == encoding.CodePage, "Encoding code page mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.CodePage): {1}", codePage, encoding.CodePage); byte[] actualPreamble = encoding.GetPreamble(); Debug.Assert(preambleLength == actualPreamble.Length, "Encoding preamble length mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble().Length): {1}", preambleLength, actualPreamble.Length); Debug.Assert(actualPreamble.Length >= 2); int actualFirst2Bytes = actualPreamble[0] << 8 | actualPreamble[1]; Debug.Assert(first2Bytes == actualFirst2Bytes, "Encoding preamble first 2 bytes mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual: {1}", first2Bytes, actualFirst2Bytes); Debug.Assert(preamble.Length == actualPreamble.Length, "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); for (int i = 0; i < preamble.Length; i++) { Debug.Assert(preamble[i] == actualPreamble[i], "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); } } #endif public HttpContentHeaders Headers { get { if (_headers == null) { _headers = new HttpContentHeaders(this); } return _headers; } } private bool IsBuffered { get { return _bufferedContent != null; } } internal void SetBuffer(byte[] buffer, int offset, int count) { _bufferedContent = new MemoryStream(buffer, offset, count, writable: false, publiclyVisible: true); } internal bool TryGetBuffer(out ArraySegment<byte> buffer) { if (_bufferedContent != null) { return _bufferedContent.TryGetBuffer(out buffer); } buffer = default; return false; } protected HttpContent() { // Log to get an ID for the current content. This ID is used when the content gets associated to a message. if (NetEventSource.IsEnabled) NetEventSource.Enter(this); // We start with the assumption that we can calculate the content length. _canCalculateLength = true; if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } public Task<string> ReadAsStringAsync() { CheckDisposed(); return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsString()); } private string ReadBufferedContentAsString() { Debug.Assert(IsBuffered); if (_bufferedContent.Length == 0) { return string.Empty; } ArraySegment<byte> buffer; if (!TryGetBuffer(out buffer)) { buffer = new ArraySegment<byte>(_bufferedContent.ToArray()); } return ReadBufferAsString(buffer, Headers); } internal static string ReadBufferAsString(ArraySegment<byte> buffer, HttpContentHeaders headers) { // We don't validate the Content-Encoding header: If the content was encoded, it's the caller's // responsibility to make sure to only call ReadAsString() on already decoded content. E.g. if the // Content-Encoding is 'gzip' the user should set HttpClientHandler.AutomaticDecompression to get a // decoded response stream. Encoding encoding = null; int bomLength = -1; string charset = headers.ContentType?.CharSet; // If we do have encoding information in the 'Content-Type' header, use that information to convert // the content to a string. if (charset != null) { try { // Remove at most a single set of quotes. if (charset.Length > 2 && charset[0] == '\"' && charset[charset.Length - 1] == '\"') { encoding = Encoding.GetEncoding(charset.Substring(1, charset.Length - 2)); } else { encoding = Encoding.GetEncoding(charset); } // Byte-order-mark (BOM) characters may be present even if a charset was specified. bomLength = GetPreambleLength(buffer, encoding); } catch (ArgumentException e) { throw new InvalidOperationException(SR.net_http_content_invalid_charset, e); } } // If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present, // then check for a BOM in the data to figure out the encoding. if (encoding == null) { if (!TryDetectEncoding(buffer, out encoding, out bomLength)) { // Use the default encoding (UTF8) if we couldn't detect one. encoding = DefaultStringEncoding; // We already checked to see if the data had a UTF8 BOM in TryDetectEncoding // and DefaultStringEncoding is UTF8, so the bomLength is 0. bomLength = 0; } } // Drop the BOM when decoding the data. return encoding.GetString(buffer.Array, buffer.Offset + bomLength, buffer.Count - bomLength); } public Task<byte[]> ReadAsByteArrayAsync() { CheckDisposed(); return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsByteArray()); } internal byte[] ReadBufferedContentAsByteArray() { // The returned array is exposed out of the library, so use ToArray rather // than TryGetBuffer in order to make a copy. return _bufferedContent.ToArray(); } public Task<Stream> ReadAsStreamAsync() { CheckDisposed(); // _contentReadStream will be either null (nothing yet initialized), a Stream (it was previously // initialized in TryReadAsStream), or a Task<Stream> (it was previously initialized here // in ReadAsStreamAsync). if (_contentReadStream == null) // don't yet have a Stream { Task<Stream> t = TryGetBuffer(out ArraySegment<byte> buffer) ? Task.FromResult<Stream>(new MemoryStream(buffer.Array, buffer.Offset, buffer.Count, writable: false)) : CreateContentReadStreamAsync(); _contentReadStream = t; return t; } else if (_contentReadStream is Task<Stream> t) // have a Task<Stream> { return t; } else { Debug.Assert(_contentReadStream is Stream, $"Expected a Stream, got ${_contentReadStream}"); Task<Stream> ts = Task.FromResult((Stream)_contentReadStream); _contentReadStream = ts; return ts; } } internal Stream TryReadAsStream() { CheckDisposed(); // _contentReadStream will be either null (nothing yet initialized), a Stream (it was previously // initialized here in TryReadAsStream), or a Task<Stream> (it was previously initialized // in ReadAsStreamAsync). if (_contentReadStream == null) // don't yet have a Stream { Stream s = TryGetBuffer(out ArraySegment<byte> buffer) ? new MemoryStream(buffer.Array, buffer.Offset, buffer.Count, writable: false) : TryCreateContentReadStream(); _contentReadStream = s; return s; } else if (_contentReadStream is Stream s) // have a Stream { return s; } else // have a Task<Stream> { Debug.Assert(_contentReadStream is Task<Stream>, $"Expected a Task<Stream>, got ${_contentReadStream}"); Task<Stream> t = (Task<Stream>)_contentReadStream; return t.Status == TaskStatus.RanToCompletion ? t.Result : null; } } protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context); // TODO #9071: Expose this publicly. Until it's public, only sealed or internal types should override it, and then change // their SerializeToStreamAsync implementation to delegate to this one. They need to be sealed as otherwise an external // type could derive from it and override SerializeToStreamAsync(stream, context) further, at which point when // HttpClient calls SerializeToStreamAsync(stream, context, cancellationToken), their custom override will be skipped. internal virtual Task SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken) => SerializeToStreamAsync(stream, context); // TODO #38559: Expose something to enable this publicly. For very specific HTTP/2 scenarios (e.g. gRPC), we need // to be able to allow request content to continue sending after SendAsync has completed, which goes against the // previous design of content, and which means that with some servers, even outside of desired scenarios we could // end up unexpectedly having request content still sending even after the response completes, which could lead to // spurious failures in unsuspecting client code. To mitigate that, we prohibit duplex on all known HttpContent // types, waiting for the request content to complete before completing the SendAsync task. internal virtual bool AllowDuplex => true; public Task CopyToAsync(Stream stream, TransportContext context) => CopyToAsync(stream, context, CancellationToken.None); // TODO #9071: Expose this publicly. internal Task CopyToAsync(Stream stream, TransportContext context, CancellationToken cancellationToken) { CheckDisposed(); if (stream == null) { throw new ArgumentNullException(nameof(stream)); } try { ArraySegment<byte> buffer; if (TryGetBuffer(out buffer)) { return CopyToAsyncCore(stream.WriteAsync(new ReadOnlyMemory<byte>(buffer.Array, buffer.Offset, buffer.Count), cancellationToken)); } else { Task task = SerializeToStreamAsync(stream, context, cancellationToken); CheckTaskNotNull(task); return CopyToAsyncCore(new ValueTask(task)); } } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { return Task.FromException(GetStreamCopyException(e)); } } private static async Task CopyToAsyncCore(ValueTask copyTask) { try { await copyTask.ConfigureAwait(false); } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { throw WrapStreamCopyException(e); } } public Task CopyToAsync(Stream stream) { return CopyToAsync(stream, null); } public Task LoadIntoBufferAsync() { return LoadIntoBufferAsync(MaxBufferSize); } // No "CancellationToken" parameter needed since canceling the CTS will close the connection, resulting // in an exception being thrown while we're buffering. // If buffering is used without a connection, it is supposed to be fast, thus no cancellation required. public Task LoadIntoBufferAsync(long maxBufferSize) => LoadIntoBufferAsync(maxBufferSize, CancellationToken.None); internal Task LoadIntoBufferAsync(long maxBufferSize, CancellationToken cancellationToken) { CheckDisposed(); if (maxBufferSize > HttpContent.MaxBufferSize) { // This should only be hit when called directly; HttpClient/HttpClientHandler // will not exceed this limit. throw new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize, SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize)); } if (IsBuffered) { // If we already buffered the content, just return a completed task. return Task.CompletedTask; } Exception error = null; MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error); if (tempBuffer == null) { // We don't throw in LoadIntoBufferAsync(): return a faulted task. return Task.FromException(error); } try { Task task = SerializeToStreamAsync(tempBuffer, null, cancellationToken); CheckTaskNotNull(task); return LoadIntoBufferAsyncCore(task, tempBuffer); } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { return Task.FromException(GetStreamCopyException(e)); } // other synchronous exceptions from SerializeToStreamAsync/CheckTaskNotNull will propagate } private async Task LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer) { try { await serializeToStreamTask.ConfigureAwait(false); } catch (Exception e) { tempBuffer.Dispose(); // Cleanup partially filled stream. Exception we = GetStreamCopyException(e); if (we != e) throw we; throw; } try { tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data. _bufferedContent = tempBuffer; } catch (Exception e) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, e); throw; } } protected virtual Task<Stream> CreateContentReadStreamAsync() { // By default just buffer the content to a memory stream. Derived classes can override this behavior // if there is a better way to retrieve the content as stream (e.g. byte array/string use a more efficient // way, like wrapping a read-only MemoryStream around the bytes/string) return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => (Stream)s._bufferedContent); } // As an optimization for internal consumers of HttpContent (e.g. HttpClient.GetStreamAsync), and for // HttpContent-derived implementations that override CreateContentReadStreamAsync in a way that always // or frequently returns synchronously-completed tasks, we can avoid the task allocation by enabling // callers to try to get the Stream first synchronously. internal virtual Stream TryCreateContentReadStream() => null; // Derived types return true if they're able to compute the length. It's OK if derived types return false to // indicate that they're not able to compute the length. The transport channel needs to decide what to do in // that case (send chunked, buffer first, etc.). protected internal abstract bool TryComputeLength(out long length); internal long? GetComputedOrBufferLength() { CheckDisposed(); if (IsBuffered) { return _bufferedContent.Length; } // If we already tried to calculate the length, but the derived class returned 'false', then don't try // again; just return null. if (_canCalculateLength) { long length = 0; if (TryComputeLength(out length)) { return length; } // Set flag to make sure next time we don't try to compute the length, since we know that we're unable // to do so. _canCalculateLength = false; } return null; } private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error) { error = null; // If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the // content length exceeds the max. buffer size. long? contentLength = Headers.ContentLength; if (contentLength != null) { Debug.Assert(contentLength >= 0); if (contentLength > maxBufferSize) { error = new HttpRequestException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize)); return null; } // We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize. return new LimitMemoryStream((int)maxBufferSize, (int)contentLength); } // We couldn't determine the length of the buffer. Create a memory stream with an empty buffer. return new LimitMemoryStream((int)maxBufferSize, 0); } #region IDisposable Members protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; if (_contentReadStream != null) { Stream s = _contentReadStream as Stream ?? (_contentReadStream is Task<Stream> t && t.Status == TaskStatus.RanToCompletion ? t.Result : null); s?.Dispose(); _contentReadStream = null; } if (IsBuffered) { _bufferedContent.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region Helpers private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } private void CheckTaskNotNull(Task task) { if (task == null) { var e = new InvalidOperationException(SR.net_http_content_no_task_returned); if (NetEventSource.IsEnabled) NetEventSource.Error(this, e); throw e; } } internal static bool StreamCopyExceptionNeedsWrapping(Exception e) => e is IOException || e is ObjectDisposedException; private static Exception GetStreamCopyException(Exception originalException) { // HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream // provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content // types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple // exceptions (depending on the underlying transport), but just HttpRequestExceptions // Custom stream should throw either IOException or HttpRequestException. // We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we // don't want to hide such "usage error" exceptions in HttpRequestException. // ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in // the response stream being closed. return StreamCopyExceptionNeedsWrapping(originalException) ? WrapStreamCopyException(originalException) : originalException; } internal static Exception WrapStreamCopyException(Exception e) { Debug.Assert(StreamCopyExceptionNeedsWrapping(e)); return new HttpRequestException(SR.net_http_content_stream_copy_error, e); } private static int GetPreambleLength(ArraySegment<byte> buffer, Encoding encoding) { byte[] data = buffer.Array; int offset = buffer.Offset; int dataLength = buffer.Count; Debug.Assert(data != null); Debug.Assert(encoding != null); switch (encoding.CodePage) { case UTF8CodePage: return (dataLength >= UTF8PreambleLength && data[offset + 0] == UTF8PreambleByte0 && data[offset + 1] == UTF8PreambleByte1 && data[offset + 2] == UTF8PreambleByte2) ? UTF8PreambleLength : 0; #if !uap // UTF32 not supported on Phone case UTF32CodePage: return (dataLength >= UTF32PreambleLength && data[offset + 0] == UTF32PreambleByte0 && data[offset + 1] == UTF32PreambleByte1 && data[offset + 2] == UTF32PreambleByte2 && data[offset + 3] == UTF32PreambleByte3) ? UTF32PreambleLength : 0; #endif case UnicodeCodePage: return (dataLength >= UnicodePreambleLength && data[offset + 0] == UnicodePreambleByte0 && data[offset + 1] == UnicodePreambleByte1) ? UnicodePreambleLength : 0; case BigEndianUnicodeCodePage: return (dataLength >= BigEndianUnicodePreambleLength && data[offset + 0] == BigEndianUnicodePreambleByte0 && data[offset + 1] == BigEndianUnicodePreambleByte1) ? BigEndianUnicodePreambleLength : 0; default: byte[] preamble = encoding.GetPreamble(); return BufferHasPrefix(buffer, preamble) ? preamble.Length : 0; } } private static bool TryDetectEncoding(ArraySegment<byte> buffer, out Encoding encoding, out int preambleLength) { byte[] data = buffer.Array; int offset = buffer.Offset; int dataLength = buffer.Count; Debug.Assert(data != null); if (dataLength >= 2) { int first2Bytes = data[offset + 0] << 8 | data[offset + 1]; switch (first2Bytes) { case UTF8PreambleFirst2Bytes: if (dataLength >= UTF8PreambleLength && data[offset + 2] == UTF8PreambleByte2) { encoding = Encoding.UTF8; preambleLength = UTF8PreambleLength; return true; } break; case UTF32OrUnicodePreambleFirst2Bytes: #if !uap // UTF32 not supported on Phone if (dataLength >= UTF32PreambleLength && data[offset + 2] == UTF32PreambleByte2 && data[offset + 3] == UTF32PreambleByte3) { encoding = Encoding.UTF32; preambleLength = UTF32PreambleLength; } else #endif { encoding = Encoding.Unicode; preambleLength = UnicodePreambleLength; } return true; case BigEndianUnicodePreambleFirst2Bytes: encoding = Encoding.BigEndianUnicode; preambleLength = BigEndianUnicodePreambleLength; return true; } } encoding = null; preambleLength = 0; return false; } private static bool BufferHasPrefix(ArraySegment<byte> buffer, byte[] prefix) { byte[] byteArray = buffer.Array; if (prefix == null || byteArray == null || prefix.Length > buffer.Count || prefix.Length == 0) return false; for (int i = 0, j = buffer.Offset; i < prefix.Length; i++, j++) { if (prefix[i] != byteArray[j]) return false; } return true; } #endregion Helpers private static async Task<TResult> WaitAndReturnAsync<TState, TResult>(Task waitTask, TState state, Func<TState, TResult> returnFunc) { await waitTask.ConfigureAwait(false); return returnFunc(state); } private static Exception CreateOverCapacityException(int maxBufferSize) { return new HttpRequestException(SR.Format(SR.net_http_content_buffersize_exceeded, maxBufferSize)); } internal sealed class LimitMemoryStream : MemoryStream { private readonly int _maxSize; public LimitMemoryStream(int maxSize, int capacity) : base(capacity) { Debug.Assert(capacity <= maxSize); _maxSize = maxSize; } public byte[] GetSizedBuffer() { ArraySegment<byte> buffer; return TryGetBuffer(out buffer) && buffer.Offset == 0 && buffer.Count == buffer.Array.Length ? buffer.Array : ToArray(); } public override void Write(byte[] buffer, int offset, int count) { CheckSize(count); base.Write(buffer, offset, count); } public override void WriteByte(byte value) { CheckSize(1); base.WriteByte(value); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckSize(count); return base.WriteAsync(buffer, offset, count, cancellationToken); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { CheckSize(buffer.Length); return base.WriteAsync(buffer, cancellationToken); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { CheckSize(count); return base.BeginWrite(buffer, offset, count, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { base.EndWrite(asyncResult); } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { ArraySegment<byte> buffer; if (TryGetBuffer(out buffer)) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); long pos = Position; long length = Length; Position = length; long bytesToWrite = length - pos; return destination.WriteAsync(buffer.Array, (int)(buffer.Offset + pos), (int)bytesToWrite, cancellationToken); } return base.CopyToAsync(destination, bufferSize, cancellationToken); } private void CheckSize(int countToAdd) { if (_maxSize - Length < countToAdd) { throw CreateOverCapacityException(_maxSize); } } } internal sealed class LimitArrayPoolWriteStream : Stream { private const int MaxByteArrayLength = 0x7FFFFFC7; private const int InitialLength = 256; private readonly int _maxBufferSize; private byte[] _buffer; private int _length; public LimitArrayPoolWriteStream(int maxBufferSize) : this(maxBufferSize, InitialLength) { } public LimitArrayPoolWriteStream(int maxBufferSize, long capacity) { if (capacity < InitialLength) { capacity = InitialLength; } else if (capacity > maxBufferSize) { throw CreateOverCapacityException(maxBufferSize); } _maxBufferSize = maxBufferSize; _buffer = ArrayPool<byte>.Shared.Rent((int)capacity); } protected override void Dispose(bool disposing) { Debug.Assert(_buffer != null); ArrayPool<byte>.Shared.Return(_buffer); _buffer = null; base.Dispose(disposing); } public ArraySegment<byte> GetBuffer() => new ArraySegment<byte>(_buffer, 0, _length); public byte[] ToArray() { var arr = new byte[_length]; Buffer.BlockCopy(_buffer, 0, arr, 0, _length); return arr; } private void EnsureCapacity(int value) { if ((uint)value > (uint)_maxBufferSize) // value cast handles overflow to negative as well { throw CreateOverCapacityException(_maxBufferSize); } else if (value > _buffer.Length) { Grow(value); } } private void Grow(int value) { Debug.Assert(value > _buffer.Length); // Extract the current buffer to be replaced. byte[] currentBuffer = _buffer; _buffer = null; // Determine the capacity to request for the new buffer. It should be // at least twice as long as the current one, if not more if the requested // value is more than that. If the new value would put it longer than the max // allowed byte array, than shrink to that (and if the required length is actually // longer than that, we'll let the runtime throw). uint twiceLength = 2 * (uint)currentBuffer.Length; int newCapacity = twiceLength > MaxByteArrayLength ? (value > MaxByteArrayLength ? value : MaxByteArrayLength) : Math.Max(value, (int)twiceLength); // Get a new buffer, copy the current one to it, return the current one, and // set the new buffer as current. byte[] newBuffer = ArrayPool<byte>.Shared.Rent(newCapacity); Buffer.BlockCopy(currentBuffer, 0, newBuffer, 0, _length); ArrayPool<byte>.Shared.Return(currentBuffer); _buffer = newBuffer; } public override void Write(byte[] buffer, int offset, int count) { Debug.Assert(buffer != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); EnsureCapacity(_length + count); Buffer.BlockCopy(buffer, offset, _buffer, _length, count); _length += count; } public override void Write(ReadOnlySpan<byte> buffer) { EnsureCapacity(_length + buffer.Length); buffer.CopyTo(new Span<byte>(_buffer, _length, buffer.Length)); _length += buffer.Length; } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Write(buffer, offset, count); return Task.CompletedTask; } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) { Write(buffer.Span); return default; } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override void WriteByte(byte value) { int newLength = _length + 1; EnsureCapacity(newLength); _buffer[_length] = value; _length = newLength; } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; public override long Length => _length; public override bool CanWrite => true; public override bool CanRead => false; public override bool CanSeek => false; public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } } } }
using PlayFab.Internal; using System; using System.Collections.Generic; namespace PlayFab.CloudScriptModels { public class AdCampaignAttributionModel { /// <summary> /// UTC time stamp of attribution /// </summary> public DateTime AttributedAt ; /// <summary> /// Attribution campaign identifier /// </summary> public string CampaignId ; /// <summary> /// Attribution network name /// </summary> public string Platform ; } public enum CloudScriptRevisionOption { Live, Latest, Specific } public class ContactEmailInfoModel { /// <summary> /// The email address /// </summary> public string EmailAddress ; /// <summary> /// The name of the email info data /// </summary> public string Name ; /// <summary> /// The verification status of the email /// </summary> public EmailVerificationStatus? VerificationStatus ; } public enum ContinentCode { AF, AN, AS, EU, NA, OC, SA } public enum CountryCode { AF, AX, AL, DZ, AS, AD, AO, AI, AQ, AG, AR, AM, AW, AU, AT, AZ, BS, BH, BD, BB, BY, BE, BZ, BJ, BM, BT, BO, BQ, BA, BW, BV, BR, IO, BN, BG, BF, BI, KH, CM, CA, CV, KY, CF, TD, CL, CN, CX, CC, CO, KM, CG, CD, CK, CR, CI, HR, CU, CW, CY, CZ, DK, DJ, DM, DO, EC, EG, SV, GQ, ER, EE, ET, FK, FO, FJ, FI, FR, GF, PF, TF, GA, GM, GE, DE, GH, GI, GR, GL, GD, GP, GU, GT, GG, GN, GW, GY, HT, HM, VA, HN, HK, HU, IS, IN, ID, IR, IQ, IE, IM, IL, IT, JM, JP, JE, JO, KZ, KE, KI, KP, KR, KW, KG, LA, LV, LB, LS, LR, LY, LI, LT, LU, MO, MK, MG, MW, MY, MV, ML, MT, MH, MQ, MR, MU, YT, MX, FM, MD, MC, MN, ME, MS, MA, MZ, MM, NA, NR, NP, NL, NC, NZ, NI, NE, NG, NU, NF, MP, NO, OM, PK, PW, PS, PA, PG, PY, PE, PH, PN, PL, PT, PR, QA, RE, RO, RU, RW, BL, SH, KN, LC, MF, PM, VC, WS, SM, ST, SA, SN, RS, SC, SL, SG, SX, SK, SI, SB, SO, ZA, GS, SS, ES, LK, SD, SR, SJ, SZ, SE, CH, SY, TW, TJ, TZ, TH, TL, TG, TK, TO, TT, TN, TR, TM, TC, TV, UG, UA, AE, GB, US, UM, UY, UZ, VU, VE, VN, VG, VI, WF, EH, YE, ZM, ZW } public enum EmailVerificationStatus { Unverified, Pending, Confirmed } public class EmptyResult : PlayFabResultCommon { } /// <summary> /// Combined entity type and ID structure which uniquely identifies a single entity. /// </summary> public class EntityKey { /// <summary> /// Unique ID of the entity. /// </summary> public string Id { get; set; } /// <summary> /// Entity type. See https://docs.microsoft.com/gaming/playfab/features/data/entities/available-built-in-entity-types /// </summary> public string Type { get; set; } } public class ExecuteCloudScriptResult : PlayFabResultCommon { /// <summary> /// Number of PlayFab API requests issued by the CloudScript function /// </summary> public int APIRequestsIssued ; /// <summary> /// Information about the error, if any, that occurred during execution /// </summary> public ScriptExecutionError Error ; public double ExecutionTimeSeconds ; /// <summary> /// The name of the function that executed /// </summary> public string FunctionName ; /// <summary> /// The object returned from the CloudScript function, if any /// </summary> public object FunctionResult ; /// <summary> /// Flag indicating if the FunctionResult was too large and was subsequently dropped from this event. This only occurs if /// the total event size is larger than 350KB. /// </summary> public bool? FunctionResultTooLarge ; /// <summary> /// Number of external HTTP requests issued by the CloudScript function /// </summary> public int HttpRequestsIssued ; /// <summary> /// Entries logged during the function execution. These include both entries logged in the function code using log.info() /// and log.error() and error entries for API and HTTP request failures. /// </summary> public List<LogStatement> Logs ; /// <summary> /// Flag indicating if the logs were too large and were subsequently dropped from this event. This only occurs if the total /// event size is larger than 350KB after the FunctionResult was removed. /// </summary> public bool? LogsTooLarge ; public uint MemoryConsumedBytes ; /// <summary> /// Processor time consumed while executing the function. This does not include time spent waiting on API calls or HTTP /// requests. /// </summary> public double ProcessorTimeSeconds ; /// <summary> /// The revision of the CloudScript that executed /// </summary> public int Revision ; } /// <summary> /// Executes CloudScript with the entity profile that is defined in the request. /// </summary> public class ExecuteEntityCloudScriptRequest : PlayFabRequestCommon { /// <summary> /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). /// </summary> public Dictionary<string,string> CustomTags ; /// <summary> /// The entity to perform this action on. /// </summary> public EntityKey Entity ; /// <summary> /// The name of the CloudScript function to execute /// </summary> public string FunctionName ; /// <summary> /// Object that is passed in to the function as the first argument /// </summary> public object FunctionParameter ; /// <summary> /// Generate a 'entity_executed_cloudscript' PlayStream event containing the results of the function execution and other /// contextual information. This event will show up in the PlayStream debugger console for the player in Game Manager. /// </summary> public bool? GeneratePlayStreamEvent ; /// <summary> /// Option for which revision of the CloudScript to execute. 'Latest' executes the most recently created revision, 'Live' /// executes the current live, published revision, and 'Specific' executes the specified revision. The default value is /// 'Specific', if the SpecificRevision parameter is specified, otherwise it is 'Live'. /// </summary> public CloudScriptRevisionOption? RevisionSelection ; /// <summary> /// The specific revision to execute, when RevisionSelection is set to 'Specific' /// </summary> public int? SpecificRevision ; } /// <summary> /// Executes an Azure Function with the profile of the entity that is defined in the request. /// </summary> public class ExecuteFunctionRequest : PlayFabRequestCommon { /// <summary> /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). /// </summary> public Dictionary<string,string> CustomTags { get; set; } /// <summary> /// The entity to perform this action on. /// </summary> public EntityKey Entity { get; set; } /// <summary> /// The name of the CloudScript function to execute /// </summary> public string FunctionName { get; set; } /// <summary> /// Object that is passed in to the function as the FunctionArgument field of the FunctionExecutionContext data structure /// </summary> public object FunctionParameter { get; set; } /// <summary> /// Generate a 'entity_executed_cloudscript_function' PlayStream event containing the results of the function execution and /// other contextual information. This event will show up in the PlayStream debugger console for the player in Game Manager. /// </summary> public bool? GeneratePlayStreamEvent { get; set; } } public class ExecuteFunctionResult : PlayFabResultCommon { /// <summary> /// Error from the CloudScript Azure Function. /// </summary> public FunctionExecutionError Error ; /// <summary> /// The amount of time the function took to execute /// </summary> public int ExecutionTimeMilliseconds ; /// <summary> /// The name of the function that executed /// </summary> public string FunctionName ; /// <summary> /// The object returned from the function, if any /// </summary> public object FunctionResult ; /// <summary> /// Flag indicating if the FunctionResult was too large and was subsequently dropped from this event. /// </summary> public bool? FunctionResultTooLarge ; } public class FunctionExecutionError { /// <summary> /// Error code, such as CloudScriptAzureFunctionsExecutionTimeLimitExceeded, CloudScriptAzureFunctionsArgumentSizeExceeded, /// CloudScriptAzureFunctionsReturnSizeExceeded or CloudScriptAzureFunctionsHTTPRequestError /// </summary> public string Error ; /// <summary> /// Details about the error /// </summary> public string Message ; /// <summary> /// Point during the execution of the function at which the error occurred, if any /// </summary> public string StackTrace ; } public class FunctionModel { /// <summary> /// The address of the function. /// </summary> public string FunctionAddress ; /// <summary> /// The name the function was registered under. /// </summary> public string FunctionName ; /// <summary> /// The trigger type for the function. /// </summary> public string TriggerType ; } public class GetFunctionRequest : PlayFabRequestCommon { /// <summary> /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). /// </summary> public Dictionary<string,string> CustomTags ; /// <summary> /// The name of the function to register /// </summary> public string FunctionName ; /// <summary> /// The Id of the parent Title /// </summary> public string TitleId ; } public class GetFunctionResult : PlayFabResultCommon { /// <summary> /// The connection string for the storage account containing the queue for a queue trigger Azure Function. /// </summary> public string ConnectionString ; /// <summary> /// The URL to be invoked to execute an HTTP triggered function. /// </summary> public string FunctionUrl ; /// <summary> /// The name of the queue for a queue trigger Azure Function. /// </summary> public string QueueName ; /// <summary> /// The trigger type for the function. /// </summary> public string TriggerType ; } public class HttpFunctionModel { /// <summary> /// The name the function was registered under. /// </summary> public string FunctionName ; /// <summary> /// The URL of the function. /// </summary> public string FunctionUrl ; } public class LinkedPlatformAccountModel { /// <summary> /// Linked account email of the user on the platform, if available /// </summary> public string Email ; /// <summary> /// Authentication platform /// </summary> public LoginIdentityProvider? Platform ; /// <summary> /// Unique account identifier of the user on the platform /// </summary> public string PlatformUserId ; /// <summary> /// Linked account username of the user on the platform, if available /// </summary> public string Username ; } /// <summary> /// A title can have many functions, ListHttpFunctions will return a list of all the currently registered HTTP triggered /// functions for a given title. /// </summary> public class ListFunctionsRequest : PlayFabRequestCommon { /// <summary> /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). /// </summary> public Dictionary<string,string> CustomTags ; /// <summary> /// The Id of the parent Title /// </summary> public string TitleId ; } public class ListFunctionsResult : PlayFabResultCommon { /// <summary> /// The list of functions that are currently registered for the title. /// </summary> public List<FunctionModel> Functions ; } public class ListHttpFunctionsResult : PlayFabResultCommon { /// <summary> /// The list of HTTP triggered functions that are currently registered for the title. /// </summary> public List<HttpFunctionModel> Functions ; } public class ListQueuedFunctionsResult : PlayFabResultCommon { /// <summary> /// The list of Queue triggered functions that are currently registered for the title. /// </summary> public List<QueuedFunctionModel> Functions ; } public class LocationModel { /// <summary> /// City name. /// </summary> public string City ; /// <summary> /// The two-character continent code for this location /// </summary> public ContinentCode? ContinentCode ; /// <summary> /// The two-character ISO 3166-1 country code for the country associated with the location /// </summary> public CountryCode? CountryCode ; /// <summary> /// Latitude coordinate of the geographic location. /// </summary> public double? Latitude ; /// <summary> /// Longitude coordinate of the geographic location. /// </summary> public double? Longitude ; } public enum LoginIdentityProvider { Unknown, PlayFab, Custom, GameCenter, GooglePlay, Steam, XBoxLive, PSN, Kongregate, Facebook, IOSDevice, AndroidDevice, Twitch, WindowsHello, GameServer, CustomServer, NintendoSwitch, FacebookInstantGames, OpenIdConnect, Apple, NintendoSwitchAccount } public class LogStatement { /// <summary> /// Optional object accompanying the message as contextual information /// </summary> public object Data ; /// <summary> /// 'Debug', 'Info', or 'Error' /// </summary> public string Level ; public string Message ; } public class MembershipModel { /// <summary> /// Whether this membership is active. That is, whether the MembershipExpiration time has been reached. /// </summary> public bool IsActive ; /// <summary> /// The time this membership expires /// </summary> public DateTime MembershipExpiration ; /// <summary> /// The id of the membership /// </summary> public string MembershipId ; /// <summary> /// Membership expirations can be explicitly overridden (via game manager or the admin api). If this membership has been /// overridden, this will be the new expiration time. /// </summary> public DateTime? OverrideExpiration ; /// <summary> /// The list of subscriptions that this player has for this membership /// </summary> public List<SubscriptionModel> Subscriptions ; } /// <summary> /// Identifier by either name or ID. Note that a name may change due to renaming, or reused after being deleted. ID is /// immutable and unique. /// </summary> public class NameIdentifier { /// <summary> /// Id Identifier, if present /// </summary> public string Id ; /// <summary> /// Name Identifier, if present /// </summary> public string Name ; } public class PlayerProfileModel { /// <summary> /// List of advertising campaigns the player has been attributed to /// </summary> public List<AdCampaignAttributionModel> AdCampaignAttributions ; /// <summary> /// URL of the player's avatar image /// </summary> public string AvatarUrl ; /// <summary> /// If the player is currently banned, the UTC Date when the ban expires /// </summary> public DateTime? BannedUntil ; /// <summary> /// List of all contact email info associated with the player account /// </summary> public List<ContactEmailInfoModel> ContactEmailAddresses ; /// <summary> /// Player record created /// </summary> public DateTime? Created ; /// <summary> /// Player display name /// </summary> public string DisplayName ; /// <summary> /// List of experiment variants for the player. Note that these variants are not guaranteed to be up-to-date when returned /// during login because the player profile is updated only after login. Instead, use the LoginResult.TreatmentAssignment /// property during login to get the correct variants and variables. /// </summary> public List<string> ExperimentVariants ; /// <summary> /// UTC time when the player most recently logged in to the title /// </summary> public DateTime? LastLogin ; /// <summary> /// List of all authentication systems linked to this player account /// </summary> public List<LinkedPlatformAccountModel> LinkedAccounts ; /// <summary> /// List of geographic locations from which the player has logged in to the title /// </summary> public List<LocationModel> Locations ; /// <summary> /// List of memberships for the player, along with whether are expired. /// </summary> public List<MembershipModel> Memberships ; /// <summary> /// Player account origination /// </summary> public LoginIdentityProvider? Origination ; /// <summary> /// PlayFab player account unique identifier /// </summary> public string PlayerId ; /// <summary> /// Publisher this player belongs to /// </summary> public string PublisherId ; /// <summary> /// List of configured end points registered for sending the player push notifications /// </summary> public List<PushNotificationRegistrationModel> PushNotificationRegistrations ; /// <summary> /// List of leaderboard statistic values for the player /// </summary> public List<StatisticModel> Statistics ; /// <summary> /// List of player's tags for segmentation /// </summary> public List<TagModel> Tags ; /// <summary> /// Title ID this player profile applies to /// </summary> public string TitleId ; /// <summary> /// Sum of the player's purchases made with real-money currencies, converted to US dollars equivalent and represented as a /// whole number of cents (1/100 USD). For example, 999 indicates nine dollars and ninety-nine cents. /// </summary> public uint? TotalValueToDateInUSD ; /// <summary> /// List of the player's lifetime purchase totals, summed by real-money currency /// </summary> public List<ValueToDateModel> ValuesToDate ; } public class PlayStreamEventEnvelopeModel { /// <summary> /// The ID of the entity the event is about. /// </summary> public string EntityId ; /// <summary> /// The type of the entity the event is about. /// </summary> public string EntityType ; /// <summary> /// Data specific to this event. /// </summary> public string EventData ; /// <summary> /// The name of the event. /// </summary> public string EventName ; /// <summary> /// The namespace of the event. /// </summary> public string EventNamespace ; /// <summary> /// Settings for the event. /// </summary> public string EventSettings ; } public class PostFunctionResultForEntityTriggeredActionRequest : PlayFabRequestCommon { /// <summary> /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). /// </summary> public Dictionary<string,string> CustomTags ; /// <summary> /// The entity to perform this action on. /// </summary> public EntityKey Entity ; /// <summary> /// The result of the function execution. /// </summary> public ExecuteFunctionResult FunctionResult ; } public class PostFunctionResultForFunctionExecutionRequest : PlayFabRequestCommon { /// <summary> /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). /// </summary> public Dictionary<string,string> CustomTags ; /// <summary> /// The entity to perform this action on. /// </summary> public EntityKey Entity ; /// <summary> /// The result of the function execution. /// </summary> public ExecuteFunctionResult FunctionResult ; } public class PostFunctionResultForPlayerTriggeredActionRequest : PlayFabRequestCommon { /// <summary> /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). /// </summary> public Dictionary<string,string> CustomTags ; /// <summary> /// The entity to perform this action on. /// </summary> public EntityKey Entity ; /// <summary> /// The result of the function execution. /// </summary> public ExecuteFunctionResult FunctionResult ; /// <summary> /// The player profile the function was invoked with. /// </summary> public PlayerProfileModel PlayerProfile ; /// <summary> /// The triggering PlayStream event, if any, that caused the function to be invoked. /// </summary> public PlayStreamEventEnvelopeModel PlayStreamEventEnvelope ; } public class PostFunctionResultForScheduledTaskRequest : PlayFabRequestCommon { /// <summary> /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). /// </summary> public Dictionary<string,string> CustomTags ; /// <summary> /// The entity to perform this action on. /// </summary> public EntityKey Entity ; /// <summary> /// The result of the function execution /// </summary> public ExecuteFunctionResult FunctionResult ; /// <summary> /// The id of the scheduled task that invoked the function. /// </summary> public NameIdentifier ScheduledTaskId ; } public enum PushNotificationPlatform { ApplePushNotificationService, GoogleCloudMessaging } public class PushNotificationRegistrationModel { /// <summary> /// Notification configured endpoint /// </summary> public string NotificationEndpointARN ; /// <summary> /// Push notification platform /// </summary> public PushNotificationPlatform? Platform ; } public class QueuedFunctionModel { /// <summary> /// The connection string for the Azure Storage Account that hosts the queue. /// </summary> public string ConnectionString ; /// <summary> /// The name the function was registered under. /// </summary> public string FunctionName ; /// <summary> /// The name of the queue that triggers the Azure Function. /// </summary> public string QueueName ; } public class RegisterHttpFunctionRequest : PlayFabRequestCommon { /// <summary> /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). /// </summary> public Dictionary<string,string> CustomTags ; /// <summary> /// The name of the function to register /// </summary> public string FunctionName ; /// <summary> /// Full URL for Azure Function that implements the function. /// </summary> public string FunctionUrl ; /// <summary> /// The Id of the parent Title /// </summary> public string TitleId ; } /// <summary> /// A title can have many functions, RegisterQueuedFunction associates a function name with a queue name and connection /// string. /// </summary> public class RegisterQueuedFunctionRequest : PlayFabRequestCommon { /// <summary> /// A connection string for the storage account that hosts the queue for the Azure Function. /// </summary> public string ConnectionString ; /// <summary> /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). /// </summary> public Dictionary<string,string> CustomTags ; /// <summary> /// The name of the function to register /// </summary> public string FunctionName ; /// <summary> /// The name of the queue for the Azure Function. /// </summary> public string QueueName ; /// <summary> /// The Id of the parent Title /// </summary> public string TitleId ; } public class ScriptExecutionError { /// <summary> /// Error code, such as CloudScriptNotFound, JavascriptException, CloudScriptFunctionArgumentSizeExceeded, /// CloudScriptAPIRequestCountExceeded, CloudScriptAPIRequestError, or CloudScriptHTTPRequestError /// </summary> public string Error ; /// <summary> /// Details about the error /// </summary> public string Message ; /// <summary> /// Point during the execution of the script at which the error occurred, if any /// </summary> public string StackTrace ; } public class StatisticModel { /// <summary> /// Statistic name /// </summary> public string Name ; /// <summary> /// Statistic value /// </summary> public int Value ; /// <summary> /// Statistic version (0 if not a versioned statistic) /// </summary> public int Version ; } public class SubscriptionModel { /// <summary> /// When this subscription expires. /// </summary> public DateTime Expiration ; /// <summary> /// The time the subscription was orignially purchased /// </summary> public DateTime InitialSubscriptionTime ; /// <summary> /// Whether this subscription is currently active. That is, if Expiration > now. /// </summary> public bool IsActive ; /// <summary> /// The status of this subscription, according to the subscription provider. /// </summary> public SubscriptionProviderStatus? Status ; /// <summary> /// The id for this subscription /// </summary> public string SubscriptionId ; /// <summary> /// The item id for this subscription from the primary catalog /// </summary> public string SubscriptionItemId ; /// <summary> /// The provider for this subscription. Apple or Google Play are supported today. /// </summary> public string SubscriptionProvider ; } public enum SubscriptionProviderStatus { NoError, Cancelled, UnknownError, BillingError, ProductUnavailable, CustomerDidNotAcceptPriceChange, FreeTrial, PaymentPending } public class TagModel { /// <summary> /// Full value of the tag, including namespace /// </summary> public string TagValue ; } public enum TriggerType { HTTP, Queue } public class UnregisterFunctionRequest : PlayFabRequestCommon { /// <summary> /// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). /// </summary> public Dictionary<string,string> CustomTags ; /// <summary> /// The name of the function to register /// </summary> public string FunctionName ; /// <summary> /// The Id of the parent Title /// </summary> public string TitleId ; } public class ValueToDateModel { /// <summary> /// ISO 4217 code of the currency used in the purchases /// </summary> public string Currency ; /// <summary> /// Total value of the purchases in a whole number of 1/100 monetary units. For example, 999 indicates nine dollars and /// ninety-nine cents when Currency is 'USD') /// </summary> public uint TotalValue ; /// <summary> /// Total value of the purchases in a string representation of decimal monetary units. For example, '9.99' indicates nine /// dollars and ninety-nine cents when Currency is 'USD'. /// </summary> public string TotalValueAsDecimal ; } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Text; using System.Diagnostics; using System.Security.Principal; using System.CodeDom; using System.CodeDom.Compiler; using Zeus.ErrorHandling; namespace Zeus.UserInterface.WinForms.CrazyErrors { /// <summary> /// Summary description for ZeusDisplayError. /// </summary> public class ZeusDisplayError : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.Label labelExceptionType; private System.Windows.Forms.TextBox textBoxExceptionType; private System.Windows.Forms.TextBox textBoxSource; private System.Windows.Forms.Label labelSource; private System.Windows.Forms.TextBox textBoxStackTrace; private System.Windows.Forms.Label labelMessage; private System.Windows.Forms.Label labelStackTrace; private System.Windows.Forms.TextBox textBoxMessage; private System.Windows.Forms.TextBox textBoxLine; private System.Windows.Forms.TextBox textBoxColumn; private System.Windows.Forms.Label labelLine; private System.Windows.Forms.Label labelColumn; private System.Windows.Forms.TextBox textBoxMethod; private System.Windows.Forms.Label labelMethod; private System.Windows.Forms.Button buttonClose; private System.Windows.Forms.Label labelTitle; private Exception exception; private string lastFileName = string.Empty; private bool isTemplate = true; private int lineNumber = -1, _index = 0, _max = 0; private System.Windows.Forms.Label labelErrorIndex; private System.Windows.Forms.Button buttonNext; private System.Windows.Forms.Button buttonPrev; private System.Windows.Forms.Panel panelErrors; private System.Windows.Forms.TextBox textBoxFile; private System.Windows.Forms.Label labelFile; ArrayList lastErrors = new ArrayList(); public event EventHandler ErrorIndexChange; protected void OnErrorIndexChange() { if (this.ErrorIndexChange != null) { this.ErrorIndexChange(this, new EventArgs()); } } public ZeusDisplayError(Exception exception) { // // Required for Windows Form Designer support // InitializeComponent(); this.exception = exception; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ZeusDisplayError)); this.labelExceptionType = new System.Windows.Forms.Label(); this.textBoxExceptionType = new System.Windows.Forms.TextBox(); this.textBoxSource = new System.Windows.Forms.TextBox(); this.labelSource = new System.Windows.Forms.Label(); this.textBoxStackTrace = new System.Windows.Forms.TextBox(); this.labelMessage = new System.Windows.Forms.Label(); this.labelStackTrace = new System.Windows.Forms.Label(); this.textBoxMessage = new System.Windows.Forms.TextBox(); this.textBoxLine = new System.Windows.Forms.TextBox(); this.textBoxColumn = new System.Windows.Forms.TextBox(); this.labelLine = new System.Windows.Forms.Label(); this.labelColumn = new System.Windows.Forms.Label(); this.textBoxMethod = new System.Windows.Forms.TextBox(); this.labelMethod = new System.Windows.Forms.Label(); this.buttonClose = new System.Windows.Forms.Button(); this.labelTitle = new System.Windows.Forms.Label(); this.labelErrorIndex = new System.Windows.Forms.Label(); this.buttonNext = new System.Windows.Forms.Button(); this.buttonPrev = new System.Windows.Forms.Button(); this.panelErrors = new System.Windows.Forms.Panel(); this.textBoxFile = new System.Windows.Forms.TextBox(); this.labelFile = new System.Windows.Forms.Label(); this.panelErrors.SuspendLayout(); this.SuspendLayout(); // // labelExceptionType // this.labelExceptionType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelExceptionType.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.labelExceptionType.Location = new System.Drawing.Point(8, 72); this.labelExceptionType.Name = "labelExceptionType"; this.labelExceptionType.Size = new System.Drawing.Size(472, 16); this.labelExceptionType.TabIndex = 0; this.labelExceptionType.Text = "Exception Type:"; this.labelExceptionType.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // textBoxExceptionType // this.textBoxExceptionType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxExceptionType.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.textBoxExceptionType.Location = new System.Drawing.Point(8, 88); this.textBoxExceptionType.Name = "textBoxExceptionType"; this.textBoxExceptionType.ReadOnly = true; this.textBoxExceptionType.Size = new System.Drawing.Size(472, 20); this.textBoxExceptionType.TabIndex = 1; this.textBoxExceptionType.Text = ""; // // textBoxSource // this.textBoxSource.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxSource.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.textBoxSource.Location = new System.Drawing.Point(8, 128); this.textBoxSource.Name = "textBoxSource"; this.textBoxSource.ReadOnly = true; this.textBoxSource.Size = new System.Drawing.Size(472, 20); this.textBoxSource.TabIndex = 3; this.textBoxSource.Text = ""; // // labelSource // this.labelSource.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelSource.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.labelSource.Location = new System.Drawing.Point(8, 112); this.labelSource.Name = "labelSource"; this.labelSource.Size = new System.Drawing.Size(472, 16); this.labelSource.TabIndex = 2; this.labelSource.Text = "Source:"; this.labelSource.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // textBoxStackTrace // this.textBoxStackTrace.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxStackTrace.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.textBoxStackTrace.Location = new System.Drawing.Point(8, 304); this.textBoxStackTrace.Multiline = true; this.textBoxStackTrace.Name = "textBoxStackTrace"; this.textBoxStackTrace.ReadOnly = true; this.textBoxStackTrace.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.textBoxStackTrace.Size = new System.Drawing.Size(472, 64); this.textBoxStackTrace.TabIndex = 5; this.textBoxStackTrace.Text = ""; // // labelMessage // this.labelMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelMessage.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.labelMessage.Location = new System.Drawing.Point(8, 232); this.labelMessage.Name = "labelMessage"; this.labelMessage.Size = new System.Drawing.Size(472, 16); this.labelMessage.TabIndex = 4; this.labelMessage.Text = "Message:"; this.labelMessage.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // labelStackTrace // this.labelStackTrace.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelStackTrace.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.labelStackTrace.Location = new System.Drawing.Point(8, 288); this.labelStackTrace.Name = "labelStackTrace"; this.labelStackTrace.Size = new System.Drawing.Size(472, 16); this.labelStackTrace.TabIndex = 7; this.labelStackTrace.Text = "Stack Trace:"; this.labelStackTrace.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // textBoxMessage // this.textBoxMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxMessage.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.textBoxMessage.Location = new System.Drawing.Point(8, 248); this.textBoxMessage.Multiline = true; this.textBoxMessage.Name = "textBoxMessage"; this.textBoxMessage.ReadOnly = true; this.textBoxMessage.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.textBoxMessage.Size = new System.Drawing.Size(472, 40); this.textBoxMessage.TabIndex = 8; this.textBoxMessage.Text = ""; // // textBoxLine // this.textBoxLine.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.textBoxLine.Location = new System.Drawing.Point(8, 208); this.textBoxLine.Name = "textBoxLine"; this.textBoxLine.ReadOnly = true; this.textBoxLine.Size = new System.Drawing.Size(72, 20); this.textBoxLine.TabIndex = 9; this.textBoxLine.Text = ""; // // textBoxColumn // this.textBoxColumn.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.textBoxColumn.Location = new System.Drawing.Point(88, 208); this.textBoxColumn.Name = "textBoxColumn"; this.textBoxColumn.ReadOnly = true; this.textBoxColumn.Size = new System.Drawing.Size(72, 20); this.textBoxColumn.TabIndex = 10; this.textBoxColumn.Text = ""; // // labelLine // this.labelLine.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.labelLine.Location = new System.Drawing.Point(8, 192); this.labelLine.Name = "labelLine"; this.labelLine.Size = new System.Drawing.Size(72, 16); this.labelLine.TabIndex = 11; this.labelLine.Text = "Line:"; this.labelLine.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // labelColumn // this.labelColumn.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.labelColumn.Location = new System.Drawing.Point(88, 192); this.labelColumn.Name = "labelColumn"; this.labelColumn.Size = new System.Drawing.Size(72, 16); this.labelColumn.TabIndex = 12; this.labelColumn.Text = "Column:"; this.labelColumn.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // textBoxMethod // this.textBoxMethod.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxMethod.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.textBoxMethod.Location = new System.Drawing.Point(8, 168); this.textBoxMethod.Name = "textBoxMethod"; this.textBoxMethod.ReadOnly = true; this.textBoxMethod.Size = new System.Drawing.Size(472, 20); this.textBoxMethod.TabIndex = 14; this.textBoxMethod.Text = ""; // // labelMethod // this.labelMethod.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelMethod.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.labelMethod.Location = new System.Drawing.Point(8, 152); this.labelMethod.Name = "labelMethod"; this.labelMethod.Size = new System.Drawing.Size(472, 16); this.labelMethod.TabIndex = 13; this.labelMethod.Text = "Method:"; this.labelMethod.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // buttonClose // this.buttonClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonClose.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.buttonClose.Location = new System.Drawing.Point(400, 384); this.buttonClose.Name = "buttonClose"; this.buttonClose.TabIndex = 15; this.buttonClose.Text = "Close"; this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click); // // labelTitle // this.labelTitle.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelTitle.Font = new System.Drawing.Font("Courier New", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.labelTitle.Location = new System.Drawing.Point(8, 8); this.labelTitle.Name = "labelTitle"; this.labelTitle.Size = new System.Drawing.Size(472, 24); this.labelTitle.TabIndex = 16; this.labelTitle.Text = "System Exception"; this.labelTitle.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // labelErrorIndex // this.labelErrorIndex.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.labelErrorIndex.Location = new System.Drawing.Point(72, 16); this.labelErrorIndex.Name = "labelErrorIndex"; this.labelErrorIndex.Size = new System.Drawing.Size(48, 24); this.labelErrorIndex.TabIndex = 0; this.labelErrorIndex.Text = "1 of 5"; this.labelErrorIndex.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // buttonNext // this.buttonNext.Location = new System.Drawing.Point(120, 16); this.buttonNext.Name = "buttonNext"; this.buttonNext.Size = new System.Drawing.Size(56, 23); this.buttonNext.TabIndex = 18; this.buttonNext.Text = "Next"; this.buttonNext.Click += new System.EventHandler(this.buttonNext_Click); // // buttonPrev // this.buttonPrev.Location = new System.Drawing.Point(8, 16); this.buttonPrev.Name = "buttonPrev"; this.buttonPrev.Size = new System.Drawing.Size(56, 23); this.buttonPrev.TabIndex = 19; this.buttonPrev.Text = "Prev"; this.buttonPrev.Click += new System.EventHandler(this.buttonPrev_Click); // // panelErrors // this.panelErrors.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.panelErrors.Controls.Add(this.buttonPrev); this.panelErrors.Controls.Add(this.labelErrorIndex); this.panelErrors.Controls.Add(this.buttonNext); this.panelErrors.Location = new System.Drawing.Point(0, 368); this.panelErrors.Name = "panelErrors"; this.panelErrors.Size = new System.Drawing.Size(208, 48); this.panelErrors.TabIndex = 20; // // textBoxFile // this.textBoxFile.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxFile.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.textBoxFile.Location = new System.Drawing.Point(8, 48); this.textBoxFile.Name = "textBoxFile"; this.textBoxFile.ReadOnly = true; this.textBoxFile.Size = new System.Drawing.Size(472, 20); this.textBoxFile.TabIndex = 22; this.textBoxFile.Text = ""; // // labelFile // this.labelFile.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelFile.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.labelFile.Location = new System.Drawing.Point(8, 32); this.labelFile.Name = "labelFile"; this.labelFile.Size = new System.Drawing.Size(472, 16); this.labelFile.TabIndex = 21; this.labelFile.Text = "File:"; this.labelFile.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // ZeusDisplayError // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(488, 414); this.Controls.Add(this.textBoxFile); this.Controls.Add(this.labelFile); this.Controls.Add(this.panelErrors); this.Controls.Add(this.labelTitle); this.Controls.Add(this.buttonClose); this.Controls.Add(this.textBoxMethod); this.Controls.Add(this.textBoxColumn); this.Controls.Add(this.textBoxLine); this.Controls.Add(this.textBoxMessage); this.Controls.Add(this.textBoxStackTrace); this.Controls.Add(this.textBoxSource); this.Controls.Add(this.textBoxExceptionType); this.Controls.Add(this.labelMethod); this.Controls.Add(this.labelColumn); this.Controls.Add(this.labelLine); this.Controls.Add(this.labelStackTrace); this.Controls.Add(this.labelMessage); this.Controls.Add(this.labelSource); this.Controls.Add(this.labelExceptionType); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "ZeusDisplayError"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Execption Occurred"; this.Load += new System.EventHandler(this.ZeusDisplayError_Load); this.panelErrors.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void buttonClose_Click(object sender, System.EventArgs e) { this.Close(); } public void SetControlsFromException() { lineNumber = -1; isTemplate = true; lastErrors.Clear(); if (exception is ZeusExecutionException) { ZeusExecutionException executionException = exception as ZeusExecutionException; int numErrors = executionException.Errors.Length; if (numErrors > 1) { this.panelErrors.Visible = true; this._max = executionException.Errors.Length - 1; this.UpdateErrorLabel(); } else { this.panelErrors.Visible = false; } this.labelFile.Text = "Template Filename"; this.labelTitle.Text = "Scripting Error"; this.labelSource.Text = "Source"; this.labelMessage.Text = "Error Text"; this.labelMethod.Text = "Error Number"; this.labelStackTrace.Text = "Scripting Errors and Warnings:"; this.textBoxExceptionType.Text = "Scripting Error"; IZeusExecutionError error = executionException.Errors[this._index]; if (!error.IsWarning) { this.textBoxFile.Text = error.FileName; this.textBoxLine.Text = error.Line.ToString(); this.textBoxColumn.Text = error.Column.ToString(); this.textBoxSource.Text = error.Source; this.textBoxMessage.Text = error.Message + " " + error.Description; this.textBoxMethod.Text = error.Number; this.lastFileName = error.FileName; this.lineNumber = error.Line; } foreach (IZeusExecutionError tmperror in executionException.Errors) { // Create error string for the log StringBuilder builder = new StringBuilder(); builder.Append(tmperror.IsWarning ? "[Warning] " : "[Error] "); builder.Append(tmperror.Source); builder.Append(" (" + tmperror.Line + ", " + tmperror.Column + ") "); builder.Append(tmperror.Number + ": "); builder.Append(tmperror.Message); if (tmperror.StackTrace != string.Empty) { builder.Append("\r\nStack Trace"); builder.Append(tmperror.StackTrace); } if (tmperror == error) { this.textBoxStackTrace.Text = builder.ToString(); } lastErrors.Add(builder.ToString()); } isTemplate = executionException.IsTemplateScript; } else if (exception is ZeusDynamicException) { ZeusDynamicException zde = exception as ZeusDynamicException; this.textBoxFile.Text = string.Empty; this.textBoxLine.Text = string.Empty; this.textBoxColumn.Text = string.Empty; this.textBoxSource.Text = string.Empty; this.textBoxMessage.Text = zde.Message; this.textBoxMethod.Text = string.Empty; this.textBoxStackTrace.Text = string.Empty; this.textBoxExceptionType.Text = zde.GetType().Name; this.labelTitle.Text = zde.DynamicExceptionTypeString; this.labelMethod.Text = string.Empty; // Create error string for the log lastErrors.Add("[" + this.textBoxExceptionType.Text + "] " + zde.DynamicExceptionTypeString + " - " + zde.Message); } else { StackTrace stackTrace = null; StackFrame stackFrame = null; Exception baseException = exception.GetBaseException(); try { stackTrace = new StackTrace(baseException, true); if (stackTrace.FrameCount > 0) { stackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1); } } catch { stackTrace = null; } if (stackFrame != null) { this.textBoxFile.Text = stackFrame.GetFileName(); this.textBoxLine.Text = stackFrame.GetFileLineNumber().ToString(); this.textBoxColumn.Text = stackFrame.GetFileColumnNumber().ToString(); } this.textBoxSource.Text = baseException.Source; this.textBoxMessage.Text = baseException.Message; this.textBoxMethod.Text = baseException.TargetSite.ToString(); this.textBoxStackTrace.Text = baseException.StackTrace; this.textBoxExceptionType.Text = baseException.GetType().Name; this.labelTitle.Text = "System Exception"; this.labelMethod.Text = "Method"; // Create error string for the log lastErrors.Add( "[" + this.textBoxExceptionType.Text + "] " + this.textBoxSource.Text + "(" + this.textBoxLine.Text + ", " + this.textBoxColumn.Text + ") " + this.textBoxMessage.Text); } } private void ZeusDisplayError_Load(object sender, System.EventArgs e) { _index = 0; SetControlsFromException(); UpdateErrorLabel(); OnErrorIndexChange(); } public void UpdateErrorLabel() { int index = _index + 1; int max = _max + 1; this.labelErrorIndex.Text = index.ToString() + " of " + max.ToString(); this.buttonNext.Enabled = (_index != _max); this.buttonPrev.Enabled = (_index != 0); } private void buttonNext_Click(object sender, System.EventArgs e) { if (_index < _max) { _index++; } UpdateErrorLabel(); SetControlsFromException(); OnErrorIndexChange(); } private void buttonPrev_Click(object sender, System.EventArgs e) { if (_index > 0) { _index--; } UpdateErrorLabel(); SetControlsFromException(); OnErrorIndexChange(); } public bool LastErrorIsTemplate { get { return isTemplate; } } public string LastErrorFileName { get { return this.lastFileName; } } public bool LastErrorIsScript { get { return (lineNumber >= 0); } } public int LastErrorLineNumber { get { return lineNumber; } } public ArrayList LastErrorMessages { get { return lastErrors; } } public string LastErrorMessage { get { if (lastErrors.Count > 0) return lastErrors[lastErrors.Count - 1].ToString(); else return string.Empty; } } } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// 8 bit piece of data /// </summary> [Serializable] [XmlRoot] public partial class OneByteChunk { /// <summary> /// one byte of arbitrary data /// </summary> private byte[] _otherParameters = new byte[1]; /// <summary> /// Initializes a new instance of the <see cref="OneByteChunk"/> class. /// </summary> public OneByteChunk() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(OneByteChunk left, OneByteChunk right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(OneByteChunk left, OneByteChunk right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 1 * 1; // _otherParameters return marshalSize; } /// <summary> /// Gets or sets the one byte of arbitrary data /// </summary> [XmlArray(ElementName = "otherParameters")] public byte[] OtherParameters { get { return this._otherParameters; } set { this._otherParameters = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { for (int idx = 0; idx < this._otherParameters.Length; idx++) { dos.WriteByte(this._otherParameters[idx]); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { for (int idx = 0; idx < this._otherParameters.Length; idx++) { this._otherParameters[idx] = dis.ReadByte(); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<OneByteChunk>"); try { for (int idx = 0; idx < this._otherParameters.Length; idx++) { sb.AppendLine("<otherParameters" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"byte\">" + this._otherParameters[idx] + "</otherParameters" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</OneByteChunk>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as OneByteChunk; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(OneByteChunk obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (obj._otherParameters.Length != 1) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < 1; idx++) { if (this._otherParameters[idx] != obj._otherParameters[idx]) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; for (int idx = 0; idx < 1; idx++) { result = GenerateHash(result) ^ this._otherParameters[idx].GetHashCode(); } return result; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IAppRuntime.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Interface for abstracting away the runtime for the application. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Application { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using Kephas.Dynamic; using Kephas.IO; /// <summary> /// Interface for abstracting away the runtime for the application. /// </summary> public interface IAppRuntime : IExpando { /// <summary> /// Gets the application arguments. /// </summary> IAppArgs AppArgs { get; } /// <summary> /// Gets the application location (directory where the executing application lies). /// </summary> /// <returns> /// A path indicating the application location. /// </returns> string GetAppLocation(); /// <summary> /// Gets the location of the application with the indicated identity. /// </summary> /// <param name="appIdentity">The application identity.</param> /// <param name="throwOnNotFound">Optional. True to throw if the indicated app is not found.</param> /// <returns> /// A path indicating the indicated application location. /// </returns> string? GetAppLocation(AppIdentity? appIdentity, bool throwOnNotFound = true); /// <summary> /// Gets the application bin directories from where application is loaded. /// </summary> /// <returns> /// The application bin directories. /// </returns> IEnumerable<string> GetAppBinLocations(); /// <summary> /// Gets the application directories where configuration files are stored. /// </summary> /// <returns> /// The application configuration directories. /// </returns> IEnumerable<string> GetAppConfigLocations(); /// <summary> /// Gets the application directories where license files are stored. /// </summary> /// <returns> /// The application configuration directories. /// </returns> IEnumerable<string> GetAppLicenseLocations(); /// <summary> /// Gets the application assemblies. /// </summary> /// <param name="assemblyFilter">A filter for the assemblies (optional).</param> /// <returns> /// An enumeration of application assemblies. /// </returns> IEnumerable<Assembly> GetAppAssemblies(Func<AssemblyName, bool>? assemblyFilter = null); /// <summary> /// Gets the application's underlying .NET framework identifier. /// </summary> /// <returns> /// The application's underlying .NET framework identifier. /// </returns> string GetAppFramework(); /// <summary> /// Gets host address. /// </summary> /// <returns> /// The host address. /// </returns> IPAddress GetHostAddress(); /// <summary> /// Gets host name. /// </summary> /// <returns> /// The host name. /// </returns> string GetHostName(); /// <summary> /// Attempts to load an assembly from its given assembly name. /// </summary> /// <param name="assemblyName">The name of the assembly to be loaded.</param> /// <returns> /// The resolved assembly reference. /// </returns> Assembly LoadAssemblyFromName(AssemblyName assemblyName); /// <summary> /// Attempts to load an assembly. /// </summary> /// <param name="assemblyFilePath">The file path of the assembly to be loaded.</param> /// <returns> /// The resolved assembly reference. /// </returns> Assembly LoadAssemblyFromPath(string assemblyFilePath); } /// <summary> /// Extension methods for <see cref="IAppRuntime"/>. /// </summary> public static class AppRuntimeExtensions { /// <summary> /// Gets the identifier of the application. /// </summary> /// <param name="appRuntime">The app runtime to act on.</param> /// <returns> /// The identifier of the application. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsRoot(this IAppRuntime appRuntime) => appRuntime?[AppRuntimeBase.IsRootKey] as bool? ?? false; /// <summary> /// Gets the identifier of the application. /// </summary> /// <param name="appRuntime">The app runtime to act on.</param> /// <returns> /// The identifier of the application. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string? GetAppId(this IAppRuntime appRuntime) => appRuntime?[AppRuntimeBase.AppIdKey] as string; /// <summary> /// Gets the version of the application. /// </summary> /// <param name="appRuntime">The app runtime to act on.</param> /// <returns> /// The version of the application. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string? GetAppVersion(this IAppRuntime appRuntime) => appRuntime?[AppRuntimeBase.AppVersionKey] as string; /// <summary> /// Gets the application identity. /// </summary> /// <param name="appRuntime">The app runtime to act on.</param> /// <returns> /// The application identity. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static AppIdentity? GetAppIdentity(this IAppRuntime appRuntime) => appRuntime?[AppRuntimeBase.AppIdentityKey] as AppIdentity; /// <summary> /// Gets the running environment. /// </summary> /// <param name="appRuntime">The application runtime.</param> /// <returns>The running environment.</returns> public static string? GetEnvironment(this IAppRuntime appRuntime) => appRuntime?[AppRuntimeBase.EnvKey] as string; /// <summary> /// Gets a value indicating whether the running environment is development. /// </summary> /// <param name="appRuntime">The application runtime.</param> /// <returns>A value indicating whether the running environment is development.</returns> public static bool IsDevelopment(this IAppRuntime appRuntime) => string.Equals(EnvironmentName.Development, appRuntime.GetEnvironment(), StringComparison.OrdinalIgnoreCase); /// <summary> /// Gets the identifier of the application instance. /// </summary> /// <param name="appRuntime">The app runtime to act on.</param> /// <returns> /// The identifier of the application instance. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string? GetAppInstanceId(this IAppRuntime appRuntime) => appRuntime?[AppRuntimeBase.AppInstanceIdKey] as string; /// <summary> /// Gets the full path of the file or folder. If the name is a relative path, it will be made relative to the application location. /// </summary> /// <param name="appRuntime">The app runtime to act on.</param> /// <param name="path">Relative or absolute path of the file or folder.</param> /// <returns> /// The full path of the file or folder. /// </returns> public static string GetFullPath(this IAppRuntime appRuntime, string? path) { if (string.IsNullOrEmpty(path)) { return appRuntime.GetAppLocation(); } path = FileSystem.NormalizePath(path!); return Path.GetFullPath(Path.IsPathRooted(path) ? path : Path.Combine(appRuntime.GetAppLocation(), path)); } } }
// <copyright file="IncompleteLU.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2013 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra.Solvers; using MathNet.Numerics.Properties; namespace MathNet.Numerics.LinearAlgebra.Double.Solvers { /// <summary> /// An incomplete, level 0, LU factorization preconditioner. /// </summary> /// <remarks> /// The ILU(0) algorithm was taken from: <br/> /// Iterative methods for sparse linear systems <br/> /// Yousef Saad <br/> /// Algorithm is described in Chapter 10, section 10.3.2, page 275 <br/> /// </remarks> public sealed class ILU0Preconditioner : IPreconditioner<double> { /// <summary> /// The matrix holding the lower (L) and upper (U) matrices. The /// decomposition matrices are combined to reduce storage. /// </summary> SparseMatrix _decompositionLU; /// <summary> /// Returns the upper triagonal matrix that was created during the LU decomposition. /// </summary> /// <returns>A new matrix containing the upper triagonal elements.</returns> internal Matrix<double> UpperTriangle() { var result = new SparseMatrix(_decompositionLU.RowCount); for (var i = 0; i < _decompositionLU.RowCount; i++) { for (var j = i; j < _decompositionLU.ColumnCount; j++) { result[i, j] = _decompositionLU[i, j]; } } return result; } /// <summary> /// Returns the lower triagonal matrix that was created during the LU decomposition. /// </summary> /// <returns>A new matrix containing the lower triagonal elements.</returns> internal Matrix<double> LowerTriangle() { var result = new SparseMatrix(_decompositionLU.RowCount); for (var i = 0; i < _decompositionLU.RowCount; i++) { for (var j = 0; j <= i; j++) { if (i == j) { result[i, j] = 1.0; } else { result[i, j] = _decompositionLU[i, j]; } } } return result; } /// <summary> /// Initializes the preconditioner and loads the internal data structures. /// </summary> /// <param name="matrix">The matrix upon which the preconditioner is based. </param> /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">If <paramref name="matrix"/> is not a square matrix.</exception> public void Initialize(Matrix<double> matrix) { if (matrix == null) { throw new ArgumentNullException("matrix"); } if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix"); } _decompositionLU = SparseMatrix.OfMatrix(matrix); // M == A // for i = 2, ... , n do // for k = 1, .... , i - 1 do // if (i,k) == NZ(Z) then // compute z(i,k) = z(i,k) / z(k,k); // for j = k + 1, ...., n do // if (i,j) == NZ(Z) then // compute z(i,j) = z(i,j) - z(i,k) * z(k,j) // end // end // end // end // end for (var i = 0; i < _decompositionLU.RowCount; i++) { for (var k = 0; k < i; k++) { if (_decompositionLU[i, k] != 0.0) { var t = _decompositionLU[i, k]/_decompositionLU[k, k]; _decompositionLU[i, k] = t; if (_decompositionLU[k, i] != 0.0) { _decompositionLU[i, i] = _decompositionLU[i, i] - (t*_decompositionLU[k, i]); } for (var j = k + 1; j < _decompositionLU.RowCount; j++) { if (j == i) { continue; } if (_decompositionLU[i, j] != 0.0) { _decompositionLU[i, j] = _decompositionLU[i, j] - (t*_decompositionLU[k, j]); } } } } } } /// <summary> /// Approximates the solution to the matrix equation <b>Ax = b</b>. /// </summary> /// <param name="rhs">The right hand side vector.</param> /// <param name="lhs">The left hand side vector. Also known as the result vector.</param> public void Approximate(Vector<double> rhs, Vector<double> lhs) { if (_decompositionLU == null) { throw new ArgumentException(Resources.ArgumentMatrixDoesNotExist); } if ((lhs.Count != rhs.Count) || (lhs.Count != _decompositionLU.RowCount)) { throw new ArgumentException(Resources.ArgumentVectorsSameLength); } // Solve: // Lz = y // Which gives // for (int i = 1; i < matrix.RowLength; i++) // { // z_i = l_ii^-1 * (y_i - SUM_(j<i) l_ij * z_j) // } // NOTE: l_ii should be 1 because u_ii has to be the value var rowValues = new DenseVector(_decompositionLU.RowCount); for (var i = 0; i < _decompositionLU.RowCount; i++) { // Clear the rowValues rowValues.Clear(); _decompositionLU.Row(i, rowValues); var sum = 0.0; for (var j = 0; j < i; j++) { sum += rowValues[j]*lhs[j]; } lhs[i] = rhs[i] - sum; } // Solve: // Ux = z // Which gives // for (int i = matrix.RowLength - 1; i > -1; i--) // { // x_i = u_ii^-1 * (z_i - SUM_(j > i) u_ij * x_j) // } for (var i = _decompositionLU.RowCount - 1; i > -1; i--) { _decompositionLU.Row(i, rowValues); var sum = 0.0; for (var j = _decompositionLU.RowCount - 1; j > i; j--) { sum += rowValues[j]*lhs[j]; } lhs[i] = 1/rowValues[i]*(lhs[i] - sum); } } } }
using System; using System.Linq; using NUnit.Framework; using StructureMap.Configuration.DSL; using StructureMap.Pipeline; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget3; namespace StructureMap.Testing.Configuration.DSL { [TestFixture] public class CreatePluginFamilyTester { #region Setup/Teardown [SetUp] public void SetUp() { } #endregion public interface Something { } public class RedSomething : Something { } public class GreenSomething : Something { } public class ClassWithStringInConstructor { public ClassWithStringInConstructor(string name) { } } [Test] public void Add_an_instance_by_lambda() { var container = new Container(r => { r.For<IWidget>().Add(c => new AWidget()); }); container.GetAllInstances<IWidget>() .First() .ShouldBeOfType<AWidget>(); } [Test] public void add_an_instance_by_literal_object() { var aWidget = new AWidget(); var container = new Container(x => { x.For<IWidget>().Use(aWidget); }); container.GetAllInstances<IWidget>().First().ShouldBeTheSameAs(aWidget); } [Test] public void AddInstanceByNameOnlyAddsOneInstanceToStructureMap() { var container = new Container(r => { r.For<Something>().Add<RedSomething>().Named("Red"); }); container.GetAllInstances<Something>().Count().ShouldEqual(1); } [Test] public void AddInstanceWithNameOnlyAddsOneInstanceToStructureMap() { var container = new Container(x => { x.For<Something>().Add<RedSomething>().Named("Red"); }); container.GetAllInstances<Something>() .Count().ShouldEqual(1); } [Test] public void as_another_lifecycle() { var registry = new Registry(); var expression = registry.For<IGateway>(Lifecycles.ThreadLocal); Assert.IsNotNull(expression); var pluginGraph = registry.Build(); var family = pluginGraph.Families[typeof (IGateway)]; family.Lifecycle.ShouldBeOfType<ThreadLocalStorageLifecycle>(); } [Test] public void BuildInstancesOfType() { var registry = new Registry(); registry.For<IGateway>(); var pluginGraph = registry.Build(); Assert.IsTrue(pluginGraph.Families.Has(typeof (IGateway))); } [Test] public void BuildPluginFamilyAsPerRequest() { var registry = new Registry(); var expression = registry.For<IGateway>(); Assert.IsNotNull(expression); var pluginGraph = registry.Build(); var family = pluginGraph.Families[typeof (IGateway)]; family.Lifecycle.ShouldBeNull(); } [Test] public void BuildPluginFamilyAsSingleton() { var registry = new Registry(); var expression = registry.For<IGateway>().Singleton(); Assert.IsNotNull(expression); var pluginGraph = registry.Build(); var family = pluginGraph.Families[typeof (IGateway)]; family.Lifecycle.ShouldBeOfType<SingletonLifecycle>(); } [Test] public void CanOverrideTheDefaultInstance1() { var registry = new Registry(); // Specify the default implementation for an interface registry.For<IGateway>().Use<StubbedGateway>(); var pluginGraph = registry.Build(); Assert.IsTrue(pluginGraph.Families.Has(typeof (IGateway))); var manager = new Container(pluginGraph); var gateway = (IGateway) manager.GetInstance(typeof (IGateway)); gateway.ShouldBeOfType<StubbedGateway>(); } [Test] public void CanOverrideTheDefaultInstanceAndCreateAnAllNewPluginOnTheFly() { var registry = new Registry(); registry.For<IGateway>().Use<FakeGateway>(); var pluginGraph = registry.Build(); Assert.IsTrue(pluginGraph.Families.Has(typeof (IGateway))); var container = new Container(pluginGraph); var gateway = (IGateway) container.GetInstance(typeof (IGateway)); gateway.ShouldBeOfType<FakeGateway>(); } [Test] public void CreatePluginFamilyWithADefault() { var container = new Container(r => { r.For<IWidget>().Use<ColorWidget>() .Ctor<string>("color").Is("Red"); }); container.GetInstance<IWidget>().ShouldBeOfType<ColorWidget>().Color.ShouldEqual("Red"); } [Test] public void PutAnInterceptorIntoTheInterceptionChainOfAPluginFamilyInTheDSL() { var lifecycle = new StubbedLifecycle(); var registry = new Registry(); registry.For<IGateway>().LifecycleIs(lifecycle); var pluginGraph = registry.Build(); pluginGraph.Families[typeof (IGateway)].Lifecycle.ShouldBeTheSameAs(lifecycle); } [Test] public void Set_the_default_by_a_lambda() { var manager = new Container( registry => registry.For<IWidget>().Use(() => new AWidget())); manager.GetInstance<IWidget>().ShouldBeOfType<AWidget>(); } [Test] public void Set_the_default_to_a_built_object() { var aWidget = new AWidget(); var manager = new Container( registry => registry.For<IWidget>().Use(aWidget)); Assert.AreSame(aWidget, manager.GetInstance<IWidget>()); } [Test( Description = "Guid test based on problems encountered by Paul Segaro. See http://groups.google.com/group/structuremap-users/browse_thread/thread/34ddaf549ebb14f7?hl=en" )] public void TheDefaultInstanceIsALambdaForGuidNewGuid() { var manager = new Container( registry => registry.For<Guid>().Use(() => Guid.NewGuid())); manager.GetInstance<Guid>().ShouldBeOfType<Guid>(); } [Test] public void TheDefaultInstanceIsConcreteType() { IContainer manager = new Container( registry => registry.For<Rule>().Use<ARule>()); manager.GetInstance<Rule>().ShouldBeOfType<ARule>(); } } public class StubbedLifecycle : ILifecycle { public void EjectAll(ILifecycleContext context) { throw new NotImplementedException(); } public IObjectCache FindCache(ILifecycleContext context) { throw new NotImplementedException(); } public string Description { get { return "Stubbed"; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/logging/v2/logging_metrics.proto // Original file comments: // Copyright 2016 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. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Google.Cloud.Logging.V2 { /// <summary> /// Service for configuring logs-based metrics. /// </summary> public static class MetricsServiceV2 { static readonly string __ServiceName = "google.logging.v2.MetricsServiceV2"; static readonly Marshaller<global::Google.Cloud.Logging.V2.ListLogMetricsRequest> __Marshaller_ListLogMetricsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListLogMetricsRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> __Marshaller_ListLogMetricsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.ListLogMetricsResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Logging.V2.GetLogMetricRequest> __Marshaller_GetLogMetricRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.GetLogMetricRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Logging.V2.LogMetric> __Marshaller_LogMetric = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.LogMetric.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Logging.V2.CreateLogMetricRequest> __Marshaller_CreateLogMetricRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.CreateLogMetricRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Logging.V2.UpdateLogMetricRequest> __Marshaller_UpdateLogMetricRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.UpdateLogMetricRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Logging.V2.DeleteLogMetricRequest> __Marshaller_DeleteLogMetricRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Logging.V2.DeleteLogMetricRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly Method<global::Google.Cloud.Logging.V2.ListLogMetricsRequest, global::Google.Cloud.Logging.V2.ListLogMetricsResponse> __Method_ListLogMetrics = new Method<global::Google.Cloud.Logging.V2.ListLogMetricsRequest, global::Google.Cloud.Logging.V2.ListLogMetricsResponse>( MethodType.Unary, __ServiceName, "ListLogMetrics", __Marshaller_ListLogMetricsRequest, __Marshaller_ListLogMetricsResponse); static readonly Method<global::Google.Cloud.Logging.V2.GetLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric> __Method_GetLogMetric = new Method<global::Google.Cloud.Logging.V2.GetLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric>( MethodType.Unary, __ServiceName, "GetLogMetric", __Marshaller_GetLogMetricRequest, __Marshaller_LogMetric); static readonly Method<global::Google.Cloud.Logging.V2.CreateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric> __Method_CreateLogMetric = new Method<global::Google.Cloud.Logging.V2.CreateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric>( MethodType.Unary, __ServiceName, "CreateLogMetric", __Marshaller_CreateLogMetricRequest, __Marshaller_LogMetric); static readonly Method<global::Google.Cloud.Logging.V2.UpdateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric> __Method_UpdateLogMetric = new Method<global::Google.Cloud.Logging.V2.UpdateLogMetricRequest, global::Google.Cloud.Logging.V2.LogMetric>( MethodType.Unary, __ServiceName, "UpdateLogMetric", __Marshaller_UpdateLogMetricRequest, __Marshaller_LogMetric); static readonly Method<global::Google.Cloud.Logging.V2.DeleteLogMetricRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteLogMetric = new Method<global::Google.Cloud.Logging.V2.DeleteLogMetricRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "DeleteLogMetric", __Marshaller_DeleteLogMetricRequest, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Logging.V2.LoggingMetricsReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of MetricsServiceV2</summary> public abstract class MetricsServiceV2Base { /// <summary> /// Lists logs-based metrics. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> ListLogMetrics(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets a logs-based metric. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.LogMetric> GetLogMetric(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Creates a logs-based metric. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.LogMetric> CreateLogMetric(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Logging.V2.LogMetric> UpdateLogMetric(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a logs-based metric. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetric(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for MetricsServiceV2</summary> public class MetricsServiceV2Client : ClientBase<MetricsServiceV2Client> { /// <summary>Creates a new client for MetricsServiceV2</summary> /// <param name="channel">The channel to use to make remote calls.</param> public MetricsServiceV2Client(Channel channel) : base(channel) { } /// <summary>Creates a new client for MetricsServiceV2 that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public MetricsServiceV2Client(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected MetricsServiceV2Client() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected MetricsServiceV2Client(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Lists logs-based metrics. /// </summary> public virtual global::Google.Cloud.Logging.V2.ListLogMetricsResponse ListLogMetrics(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListLogMetrics(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists logs-based metrics. /// </summary> public virtual global::Google.Cloud.Logging.V2.ListLogMetricsResponse ListLogMetrics(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListLogMetrics, null, options, request); } /// <summary> /// Lists logs-based metrics. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> ListLogMetricsAsync(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListLogMetricsAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists logs-based metrics. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Logging.V2.ListLogMetricsResponse> ListLogMetricsAsync(global::Google.Cloud.Logging.V2.ListLogMetricsRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListLogMetrics, null, options, request); } /// <summary> /// Gets a logs-based metric. /// </summary> public virtual global::Google.Cloud.Logging.V2.LogMetric GetLogMetric(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetLogMetric(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a logs-based metric. /// </summary> public virtual global::Google.Cloud.Logging.V2.LogMetric GetLogMetric(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetLogMetric, null, options, request); } /// <summary> /// Gets a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> GetLogMetricAsync(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetLogMetricAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> GetLogMetricAsync(global::Google.Cloud.Logging.V2.GetLogMetricRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetLogMetric, null, options, request); } /// <summary> /// Creates a logs-based metric. /// </summary> public virtual global::Google.Cloud.Logging.V2.LogMetric CreateLogMetric(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateLogMetric(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a logs-based metric. /// </summary> public virtual global::Google.Cloud.Logging.V2.LogMetric CreateLogMetric(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateLogMetric, null, options, request); } /// <summary> /// Creates a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> CreateLogMetricAsync(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateLogMetricAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> CreateLogMetricAsync(global::Google.Cloud.Logging.V2.CreateLogMetricRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateLogMetric, null, options, request); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> public virtual global::Google.Cloud.Logging.V2.LogMetric UpdateLogMetric(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateLogMetric(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> public virtual global::Google.Cloud.Logging.V2.LogMetric UpdateLogMetric(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateLogMetric, null, options, request); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> UpdateLogMetricAsync(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateLogMetricAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Logging.V2.LogMetric> UpdateLogMetricAsync(global::Google.Cloud.Logging.V2.UpdateLogMetricRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateLogMetric, null, options, request); } /// <summary> /// Deletes a logs-based metric. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLogMetric(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteLogMetric(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a logs-based metric. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLogMetric(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteLogMetric, null, options, request); } /// <summary> /// Deletes a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetricAsync(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteLogMetricAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetricAsync(global::Google.Cloud.Logging.V2.DeleteLogMetricRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteLogMetric, null, options, request); } protected override MetricsServiceV2Client NewInstance(ClientBaseConfiguration configuration) { return new MetricsServiceV2Client(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(MetricsServiceV2Base serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_ListLogMetrics, serviceImpl.ListLogMetrics) .AddMethod(__Method_GetLogMetric, serviceImpl.GetLogMetric) .AddMethod(__Method_CreateLogMetric, serviceImpl.CreateLogMetric) .AddMethod(__Method_UpdateLogMetric, serviceImpl.UpdateLogMetric) .AddMethod(__Method_DeleteLogMetric, serviceImpl.DeleteLogMetric).Build(); } } } #endregion
/************************************************************************************ Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. Licensed under the Oculus SDK License Version 3.4.1 (the "License"); you may not use the Oculus SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at https://developer.oculus.com/licenses/sdk-3.4.1 Unless required by applicable law or agreed to in writing, the Oculus SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ #if !UNITY_5_6_OR_NEWER #error Oculus Utilities require Unity 5.6 or higher. #endif using System; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif /// <summary> /// Configuration data for Oculus virtual reality. /// </summary> public class OVRManager : MonoBehaviour { public enum TrackingOrigin { EyeLevel = OVRPlugin.TrackingOrigin.EyeLevel, FloorLevel = OVRPlugin.TrackingOrigin.FloorLevel, } public enum EyeTextureFormat { Default = OVRPlugin.EyeTextureFormat.Default, R16G16B16A16_FP = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP, R11G11B10_FP = OVRPlugin.EyeTextureFormat.R11G11B10_FP, } public enum TiledMultiResLevel { Off = OVRPlugin.TiledMultiResLevel.Off, LMSLow = OVRPlugin.TiledMultiResLevel.LMSLow, LMSMedium = OVRPlugin.TiledMultiResLevel.LMSMedium, LMSHigh = OVRPlugin.TiledMultiResLevel.LMSHigh, } /// <summary> /// Gets the singleton instance. /// </summary> public static OVRManager instance { get; private set; } /// <summary> /// Gets a reference to the active display. /// </summary> public static OVRDisplay display { get; private set; } /// <summary> /// Gets a reference to the active sensor. /// </summary> public static OVRTracker tracker { get; private set; } /// <summary> /// Gets a reference to the active boundary system. /// </summary> public static OVRBoundary boundary { get; private set; } private static OVRProfile _profile; /// <summary> /// Gets the current profile, which contains information about the user's settings and body dimensions. /// </summary> public static OVRProfile profile { get { if (_profile == null) _profile = new OVRProfile(); return _profile; } } private IEnumerable<Camera> disabledCameras; float prevTimeScale; /// <summary> /// Occurs when an HMD attached. /// </summary> public static event Action HMDAcquired; /// <summary> /// Occurs when an HMD detached. /// </summary> public static event Action HMDLost; /// <summary> /// Occurs when an HMD is put on the user's head. /// </summary> public static event Action HMDMounted; /// <summary> /// Occurs when an HMD is taken off the user's head. /// </summary> public static event Action HMDUnmounted; /// <summary> /// Occurs when VR Focus is acquired. /// </summary> public static event Action VrFocusAcquired; /// <summary> /// Occurs when VR Focus is lost. /// </summary> public static event Action VrFocusLost; /// <summary> /// Occurs when Input Focus is acquired. /// </summary> public static event Action InputFocusAcquired; /// <summary> /// Occurs when Input Focus is lost. /// </summary> public static event Action InputFocusLost; /// <summary> /// Occurs when the active Audio Out device has changed and a restart is needed. /// </summary> public static event Action AudioOutChanged; /// <summary> /// Occurs when the active Audio In device has changed and a restart is needed. /// </summary> public static event Action AudioInChanged; /// <summary> /// Occurs when the sensor gained tracking. /// </summary> public static event Action TrackingAcquired; /// <summary> /// Occurs when the sensor lost tracking. /// </summary> public static event Action TrackingLost; /// <summary> /// Occurs when Health & Safety Warning is dismissed. /// </summary> //Disable the warning about it being unused. It's deprecated. #pragma warning disable 0067 [Obsolete] public static event Action HSWDismissed; #pragma warning restore private static bool _isHmdPresentCached = false; private static bool _isHmdPresent = false; private static bool _wasHmdPresent = false; /// <summary> /// If true, a head-mounted display is connected and present. /// </summary> public static bool isHmdPresent { get { if (!_isHmdPresentCached) { _isHmdPresentCached = true; _isHmdPresent = OVRNodeStateProperties.IsHmdPresent(); } return _isHmdPresent; } private set { _isHmdPresentCached = true; _isHmdPresent = value; } } /// <summary> /// Gets the audio output device identifier. /// </summary> /// <description> /// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use. /// </description> public static string audioOutId { get { return OVRPlugin.audioOutId; } } /// <summary> /// Gets the audio input device identifier. /// </summary> /// <description> /// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use. /// </description> public static string audioInId { get { return OVRPlugin.audioInId; } } private static bool _hasVrFocusCached = false; private static bool _hasVrFocus = false; private static bool _hadVrFocus = false; /// <summary> /// If true, the app has VR Focus. /// </summary> public static bool hasVrFocus { get { if (!_hasVrFocusCached) { _hasVrFocusCached = true; _hasVrFocus = OVRPlugin.hasVrFocus; } return _hasVrFocus; } private set { _hasVrFocusCached = true; _hasVrFocus = value; } } private static bool _hadInputFocus = true; /// <summary> /// If true, the app has Input Focus. /// </summary> public static bool hasInputFocus { get { return OVRPlugin.hasInputFocus; } } /// <summary> /// If true, chromatic de-aberration will be applied, improving the image at the cost of texture bandwidth. /// </summary> public bool chromatic { get { if (!isHmdPresent) return false; return OVRPlugin.chromatic; } set { if (!isHmdPresent) return; OVRPlugin.chromatic = value; } } [Header("Performance/Quality")] /// <summary> /// If true, distortion rendering work is submitted a quarter-frame early to avoid pipeline stalls and increase CPU-GPU parallelism. /// </summary> [Tooltip("If true, distortion rendering work is submitted a quarter-frame early to avoid pipeline stalls and increase CPU-GPU parallelism.")] public bool queueAhead = true; /// <summary> /// If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware. /// </summary> [Tooltip("If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware.")] public bool useRecommendedMSAALevel = false; /// <summary> /// If true, both eyes will see the same image, rendered from the center eye pose, saving performance. /// </summary> [SerializeField] [Tooltip("If true, both eyes will see the same image, rendered from the center eye pose, saving performance.")] private bool _monoscopic = false; public bool monoscopic { get { if (!isHmdPresent) return _monoscopic; return OVRPlugin.monoscopic; } set { if (!isHmdPresent) return; OVRPlugin.monoscopic = value; _monoscopic = value; } } /// <summary> /// If true, dynamic resolution will be enabled /// </summary> [Tooltip("If true, dynamic resolution will be enabled On PC")] public bool enableAdaptiveResolution = false; /// <summary> /// Adaptive Resolution is based on Unity engine's renderViewportScale/eyeTextureResolutionScale feature /// But renderViewportScale was broken in an array of Unity engines, this function help to filter out those broken engines /// </summary> public static bool IsAdaptiveResSupportedByEngine() { #if UNITY_2017_1_OR_NEWER return Application.unityVersion != "2017.1.0f1"; #else return false; #endif } /// <summary> /// Min RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = true ); /// </summary> [RangeAttribute(0.5f, 2.0f)] [Tooltip("Min RenderScale the app can reach under adaptive resolution mode")] public float minRenderScale = 0.7f; /// <summary> /// Max RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = true ); /// </summary> [RangeAttribute(0.5f, 2.0f)] [Tooltip("Max RenderScale the app can reach under adaptive resolution mode")] public float maxRenderScale = 1.0f; /// <summary> /// Set the relative offset rotation of head poses /// </summary> [SerializeField] [Tooltip("Set the relative offset rotation of head poses")] private Vector3 _headPoseRelativeOffsetRotation; public Vector3 headPoseRelativeOffsetRotation { get { return _headPoseRelativeOffsetRotation; } set { OVRPlugin.Quatf rotation; OVRPlugin.Vector3f translation; if (OVRPlugin.GetHeadPoseModifier(out rotation, out translation)) { Quaternion finalRotation = Quaternion.Euler(value); rotation = finalRotation.ToQuatf(); OVRPlugin.SetHeadPoseModifier(ref rotation, ref translation); } _headPoseRelativeOffsetRotation = value; } } /// <summary> /// Set the relative offset translation of head poses /// </summary> [SerializeField] [Tooltip("Set the relative offset translation of head poses")] private Vector3 _headPoseRelativeOffsetTranslation; public Vector3 headPoseRelativeOffsetTranslation { get { return _headPoseRelativeOffsetTranslation; } set { OVRPlugin.Quatf rotation; OVRPlugin.Vector3f translation; if (OVRPlugin.GetHeadPoseModifier(out rotation, out translation)) { if (translation.FromFlippedZVector3f() != value) { translation = value.ToFlippedZVector3f(); OVRPlugin.SetHeadPoseModifier(ref rotation, ref translation); } } _headPoseRelativeOffsetTranslation = value; } } #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN /// <summary> /// If true, the MixedRealityCapture properties will be displayed /// </summary> [HideInInspector] public bool expandMixedRealityCapturePropertySheet = false; /// <summary> /// If true, Mixed Reality mode will be enabled /// </summary> [HideInInspector, Tooltip("If true, Mixed Reality mode will be enabled. It would be always set to false when the game is launching without editor")] public bool enableMixedReality = false; public enum CompositionMethod { External, Direct, Sandwich } /// <summary> /// Composition method /// </summary> [HideInInspector] public CompositionMethod compositionMethod = CompositionMethod.External; /// <summary> /// Extra hidden layers /// </summary> [HideInInspector, Tooltip("Extra hidden layers")] public LayerMask extraHiddenLayers; /// <summary> /// If true, Mixed Reality mode will use direct composition from the first web camera /// </summary> public enum CameraDevice { WebCamera0, WebCamera1, ZEDCamera } /// <summary> /// The camera device for direct composition /// </summary> [HideInInspector, Tooltip("The camera device for direct composition")] public CameraDevice capturingCameraDevice = CameraDevice.WebCamera0; /// <summary> /// Flip the camera frame horizontally /// </summary> [HideInInspector, Tooltip("Flip the camera frame horizontally")] public bool flipCameraFrameHorizontally = false; /// <summary> /// Flip the camera frame vertically /// </summary> [HideInInspector, Tooltip("Flip the camera frame vertically")] public bool flipCameraFrameVertically = false; /// <summary> /// Delay the touch controller pose by a short duration (0 to 0.5 second) to match the physical camera latency /// </summary> [HideInInspector, Tooltip("Delay the touch controller pose by a short duration (0 to 0.5 second) to match the physical camera latency")] public float handPoseStateLatency = 0.0f; /// <summary> /// Delay the foreground / background image in the sandwich composition to match the physical camera latency. The maximum duration is sandwichCompositionBufferedFrames / {Game FPS} /// </summary> [HideInInspector, Tooltip("Delay the foreground / background image in the sandwich composition to match the physical camera latency. The maximum duration is sandwichCompositionBufferedFrames / {Game FPS}")] public float sandwichCompositionRenderLatency = 0.0f; /// <summary> /// The number of frames are buffered in the SandWich composition. The more buffered frames, the more memory it would consume. /// </summary> [HideInInspector, Tooltip("The number of frames are buffered in the SandWich composition. The more buffered frames, the more memory it would consume.")] public int sandwichCompositionBufferedFrames = 8; /// <summary> /// Chroma Key Color /// </summary> [HideInInspector, Tooltip("Chroma Key Color")] public Color chromaKeyColor = Color.green; /// <summary> /// Chroma Key Similarity /// </summary> [HideInInspector, Tooltip("Chroma Key Similarity")] public float chromaKeySimilarity = 0.60f; /// <summary> /// Chroma Key Smooth Range /// </summary> [HideInInspector, Tooltip("Chroma Key Smooth Range")] public float chromaKeySmoothRange = 0.03f; /// <summary> /// Chroma Key Spill Range /// </summary> [HideInInspector, Tooltip("Chroma Key Spill Range")] public float chromaKeySpillRange = 0.06f; /// <summary> /// Use dynamic lighting (Depth sensor required) /// </summary> [HideInInspector, Tooltip("Use dynamic lighting (Depth sensor required)")] public bool useDynamicLighting = false; public enum DepthQuality { Low, Medium, High } /// <summary> /// The quality level of depth image. The lighting could be more smooth and accurate with high quality depth, but it would also be more costly in performance. /// </summary> [HideInInspector, Tooltip("The quality level of depth image. The lighting could be more smooth and accurate with high quality depth, but it would also be more costly in performance.")] public DepthQuality depthQuality = DepthQuality.Medium; /// <summary> /// Smooth factor in dynamic lighting. Larger is smoother /// </summary> [HideInInspector, Tooltip("Smooth factor in dynamic lighting. Larger is smoother")] public float dynamicLightingSmoothFactor = 8.0f; /// <summary> /// The maximum depth variation across the edges. Make it smaller to smooth the lighting on the edges. /// </summary> [HideInInspector, Tooltip("The maximum depth variation across the edges. Make it smaller to smooth the lighting on the edges.")] public float dynamicLightingDepthVariationClampingValue = 0.001f; public enum VirtualGreenScreenType { Off, OuterBoundary, PlayArea } /// <summary> /// Set the current type of the virtual green screen /// </summary> [HideInInspector, Tooltip("Type of virutal green screen ")] public VirtualGreenScreenType virtualGreenScreenType = VirtualGreenScreenType.Off; /// <summary> /// Top Y of virtual screen /// </summary> [HideInInspector, Tooltip("Top Y of virtual green screen")] public float virtualGreenScreenTopY = 10.0f; /// <summary> /// Bottom Y of virtual screen /// </summary> [HideInInspector, Tooltip("Bottom Y of virtual green screen")] public float virtualGreenScreenBottomY = -10.0f; /// <summary> /// When using a depth camera (e.g. ZED), whether to use the depth in virtual green screen culling. /// </summary> [HideInInspector, Tooltip("When using a depth camera (e.g. ZED), whether to use the depth in virtual green screen culling.")] public bool virtualGreenScreenApplyDepthCulling = false; /// <summary> /// The tolerance value (in meter) when using the virtual green screen with a depth camera. Make it bigger if the foreground objects got culled incorrectly. /// </summary> [HideInInspector, Tooltip("The tolerance value (in meter) when using the virtual green screen with a depth camera. Make it bigger if the foreground objects got culled incorrectly.")] public float virtualGreenScreenDepthTolerance = 0.2f; #endif /// <summary> /// The number of expected display frames per rendered frame. /// </summary> public int vsyncCount { get { if (!isHmdPresent) return 1; return OVRPlugin.vsyncCount; } set { if (!isHmdPresent) return; OVRPlugin.vsyncCount = value; } } /// <summary> /// Gets the current battery level. /// </summary> /// <returns><c>battery level in the range [0.0,1.0]</c> /// <param name="batteryLevel">Battery level.</param> public static float batteryLevel { get { if (!isHmdPresent) return 1f; return OVRPlugin.batteryLevel; } } /// <summary> /// Gets the current battery temperature. /// </summary> /// <returns><c>battery temperature in Celsius</c> /// <param name="batteryTemperature">Battery temperature.</param> public static float batteryTemperature { get { if (!isHmdPresent) return 0f; return OVRPlugin.batteryTemperature; } } /// <summary> /// Gets the current battery status. /// </summary> /// <returns><c>battery status</c> /// <param name="batteryStatus">Battery status.</param> public static int batteryStatus { get { if (!isHmdPresent) return -1; return (int)OVRPlugin.batteryStatus; } } /// <summary> /// Gets the current volume level. /// </summary> /// <returns><c>volume level in the range [0,1].</c> public static float volumeLevel { get { if (!isHmdPresent) return 0f; return OVRPlugin.systemVolume; } } /// <summary> /// Gets or sets the current CPU performance level (0-2). Lower performance levels save more power. /// </summary> public static int cpuLevel { get { if (!isHmdPresent) return 2; return OVRPlugin.cpuLevel; } set { if (!isHmdPresent) return; OVRPlugin.cpuLevel = value; } } /// <summary> /// Gets or sets the current GPU performance level (0-2). Lower performance levels save more power. /// </summary> public static int gpuLevel { get { if (!isHmdPresent) return 2; return OVRPlugin.gpuLevel; } set { if (!isHmdPresent) return; OVRPlugin.gpuLevel = value; } } /// <summary> /// If true, the CPU and GPU are currently throttled to save power and/or reduce the temperature. /// </summary> public static bool isPowerSavingActive { get { if (!isHmdPresent) return false; return OVRPlugin.powerSaving; } } /// <summary> /// Gets or sets the eye texture format. /// </summary> public static EyeTextureFormat eyeTextureFormat { get { return (OVRManager.EyeTextureFormat)OVRPlugin.GetDesiredEyeTextureFormat(); } set { OVRPlugin.SetDesiredEyeTextureFormat((OVRPlugin.EyeTextureFormat)value); } } /// <summary> /// Gets if tiled-based multi-resolution technique is supported /// This feature is only supported on QCOMM-based Android devices /// </summary> public static bool tiledMultiResSupported { get { return OVRPlugin.tiledMultiResSupported; } } /// <summary> /// Gets or sets the tiled-based multi-resolution level /// This feature is only supported on QCOMM-based Android devices /// </summary> public static TiledMultiResLevel tiledMultiResLevel { get { if (!OVRPlugin.tiledMultiResSupported) { Debug.LogWarning("Tiled-based Multi-resolution feature is not supported"); } return (TiledMultiResLevel)OVRPlugin.tiledMultiResLevel; } set { if (!OVRPlugin.tiledMultiResSupported) { Debug.LogWarning("Tiled-based Multi-resolution feature is not supported"); } OVRPlugin.tiledMultiResLevel = (OVRPlugin.TiledMultiResLevel)value; } } /// <summary> /// Gets if the GPU Utility is supported /// This feature is only supported on QCOMM-based Android devices /// </summary> public static bool gpuUtilSupported { get { return OVRPlugin.gpuUtilSupported; } } /// <summary> /// Gets the GPU Utilised Level (0.0 - 1.0) /// This feature is only supported on QCOMM-based Android devices /// </summary> public static float gpuUtilLevel { get { if (!OVRPlugin.gpuUtilSupported) { Debug.LogWarning("GPU Util is not supported"); } return OVRPlugin.gpuUtilLevel; } } [Header("Tracking")] [SerializeField] [Tooltip("Defines the current tracking origin type.")] private OVRManager.TrackingOrigin _trackingOriginType = OVRManager.TrackingOrigin.EyeLevel; /// <summary> /// Defines the current tracking origin type. /// </summary> public OVRManager.TrackingOrigin trackingOriginType { get { if (!isHmdPresent) return _trackingOriginType; return (OVRManager.TrackingOrigin)OVRPlugin.GetTrackingOriginType(); } set { if (!isHmdPresent) return; if (OVRPlugin.SetTrackingOriginType((OVRPlugin.TrackingOrigin)value)) { // Keep the field exposed in the Unity Editor synchronized with any changes. _trackingOriginType = value; } } } /// <summary> /// If true, head tracking will affect the position of each OVRCameraRig's cameras. /// </summary> [Tooltip("If true, head tracking will affect the position of each OVRCameraRig's cameras.")] public bool usePositionTracking = true; /// <summary> /// If true, head tracking will affect the rotation of each OVRCameraRig's cameras. /// </summary> [HideInInspector] public bool useRotationTracking = true; /// <summary> /// If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras. /// </summary> [Tooltip("If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras.")] public bool useIPDInPositionTracking = true; /// <summary> /// If true, each scene load will cause the head pose to reset. /// </summary> [Tooltip("If true, each scene load will cause the head pose to reset.")] public bool resetTrackerOnLoad = false; /// <summary> /// If true, the Reset View in the universal menu will cause the pose to be reset. This should generally be /// enabled for applications with a stationary position in the virtual world and will allow the View Reset /// command to place the person back to a predefined location (such as a cockpit seat). /// Set this to false if you have a locomotion system because resetting the view would effectively teleport /// the player to potentially invalid locations. /// </summary> [Tooltip("If true, the Reset View in the universal menu will cause the pose to be reset. This should generally be enabled for applications with a stationary position in the virtual world and will allow the View Reset command to place the person back to a predefined location (such as a cockpit seat). Set this to false if you have a locomotion system because resetting the view would effectively teleport the player to potentially invalid locations.")] public bool AllowRecenter = true; [SerializeField] [Tooltip("Specifies HMD recentering behavior when controller recenter is performed. True recenters the HMD as well, false does not.")] private bool _reorientHMDOnControllerRecenter = true; /// <summary> /// Defines the recentering mode specified in the tooltip above. /// </summary> public bool reorientHMDOnControllerRecenter { get { if (!isHmdPresent) return false; return OVRPlugin.GetReorientHMDOnControllerRecenter(); } set { if (!isHmdPresent) return; OVRPlugin.SetReorientHMDOnControllerRecenter(value); } } /// <summary> /// True if the current platform supports virtual reality. /// </summary> public bool isSupportedPlatform { get; private set; } private static bool _isUserPresentCached = false; private static bool _isUserPresent = false; private static bool _wasUserPresent = false; /// <summary> /// True if the user is currently wearing the display. /// </summary> public bool isUserPresent { get { if (!_isUserPresentCached) { _isUserPresentCached = true; _isUserPresent = OVRPlugin.userPresent; } return _isUserPresent; } private set { _isUserPresentCached = true; _isUserPresent = value; } } private static bool prevAudioOutIdIsCached = false; private static bool prevAudioInIdIsCached = false; private static string prevAudioOutId = string.Empty; private static string prevAudioInId = string.Empty; private static bool wasPositionTracked = false; public static System.Version utilitiesVersion { get { return OVRPlugin.wrapperVersion; } } public static System.Version pluginVersion { get { return OVRPlugin.version; } } public static System.Version sdkVersion { get { return OVRPlugin.nativeSDKVersion; } } #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN private static bool prevEnableMixedReality = false; private static bool MixedRealityEnabledFromCmd() { var args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-mixedreality") return true; } return false; } private static bool UseDirectCompositionFromCmd() { var args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-directcomposition") return true; } return false; } private static bool UseExternalCompositionFromCmd() { var args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-externalcomposition") return true; } return false; } private static bool CreateMixedRealityCaptureConfigurationFileFromCmd() { var args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-create_mrc_config") return true; } return false; } private static bool LoadMixedRealityCaptureConfigurationFileFromCmd() { var args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-load_mrc_config") return true; } return false; } #endif internal static bool IsUnityAlphaOrBetaVersion() { string ver = Application.unityVersion; int pos = ver.Length - 1; while (pos >= 0 && ver[pos] >= '0' && ver[pos] <= '9') { --pos; } if (pos >= 0 && (ver[pos] == 'a' || ver[pos] == 'b')) return true; return false; } internal static string UnityAlphaOrBetaVersionWarningMessage = "WARNING: It's not recommended to use Unity alpha/beta release in Oculus development. Use a stable release if you encounter any issue."; #region Unity Messages private void Awake() { // Only allow one instance at runtime. if (instance != null) { enabled = false; DestroyImmediate(this); return; } instance = this; Debug.Log("Unity v" + Application.unityVersion + ", " + "Oculus Utilities v" + OVRPlugin.wrapperVersion + ", " + "OVRPlugin v" + OVRPlugin.version + ", " + "SDK v" + OVRPlugin.nativeSDKVersion + "."); #if !UNITY_EDITOR if (IsUnityAlphaOrBetaVersion()) { Debug.LogWarning(UnityAlphaOrBetaVersionWarningMessage); } #endif #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN var supportedTypes = UnityEngine.Rendering.GraphicsDeviceType.Direct3D11.ToString() + ", " + UnityEngine.Rendering.GraphicsDeviceType.Direct3D12.ToString(); if (!supportedTypes.Contains(SystemInfo.graphicsDeviceType.ToString())) Debug.LogWarning("VR rendering requires one of the following device types: (" + supportedTypes + "). Your graphics device: " + SystemInfo.graphicsDeviceType.ToString()); #endif // Detect whether this platform is a supported platform RuntimePlatform currPlatform = Application.platform; if (currPlatform == RuntimePlatform.Android || // currPlatform == RuntimePlatform.LinuxPlayer || currPlatform == RuntimePlatform.OSXEditor || currPlatform == RuntimePlatform.OSXPlayer || currPlatform == RuntimePlatform.WindowsEditor || currPlatform == RuntimePlatform.WindowsPlayer) { isSupportedPlatform = true; } else { isSupportedPlatform = false; } if (!isSupportedPlatform) { Debug.LogWarning("This platform is unsupported"); return; } #if UNITY_ANDROID && !UNITY_EDITOR // Turn off chromatic aberration by default to save texture bandwidth. chromatic = false; #endif #if UNITY_STANDALONE_WIN && !UNITY_EDITOR enableMixedReality = false; // we should never start the standalone game in MxR mode, unless the command-line parameter is provided #endif #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN bool loadMrcConfig = LoadMixedRealityCaptureConfigurationFileFromCmd(); bool createMrcConfig = CreateMixedRealityCaptureConfigurationFileFromCmd(); if (loadMrcConfig || createMrcConfig) { OVRMixedRealityCaptureSettings mrcSettings = ScriptableObject.CreateInstance<OVRMixedRealityCaptureSettings>(); mrcSettings.ReadFrom(this); if (loadMrcConfig) { mrcSettings.CombineWithConfigurationFile(); mrcSettings.ApplyTo(this); } if (createMrcConfig) { mrcSettings.WriteToConfigurationFile(); } ScriptableObject.Destroy(mrcSettings); } if (MixedRealityEnabledFromCmd()) { enableMixedReality = true; } if (enableMixedReality) { Debug.Log("OVR: Mixed Reality mode enabled"); if (UseDirectCompositionFromCmd()) { compositionMethod = CompositionMethod.Direct; } if (UseExternalCompositionFromCmd()) { compositionMethod = CompositionMethod.External; } Debug.Log("OVR: CompositionMethod : " + compositionMethod); } #endif #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN if (enableAdaptiveResolution && !OVRManager.IsAdaptiveResSupportedByEngine()) { enableAdaptiveResolution = false; UnityEngine.Debug.LogError("Your current Unity Engine " + Application.unityVersion + " might have issues to support adaptive resolution, please disable it under OVRManager"); } #endif Initialize(); if (resetTrackerOnLoad) display.RecenterPose(); #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN // Force OcculusionMesh on all the time, you can change the value to false if you really need it be off for some reasons, // be aware there are performance drops if you don't use occlusionMesh. OVRPlugin.occlusionMesh = true; #endif } #if UNITY_EDITOR private static bool _scriptsReloaded; [UnityEditor.Callbacks.DidReloadScripts] static void ScriptsReloaded() { _scriptsReloaded = true; } #endif void Initialize() { if (display == null) display = new OVRDisplay(); if (tracker == null) tracker = new OVRTracker(); if (boundary == null) boundary = new OVRBoundary(); reorientHMDOnControllerRecenter = _reorientHMDOnControllerRecenter; } #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN private bool suppressDisableMixedRealityBecauseOfNoMainCameraWarning = false; #endif private void Update() { #if UNITY_EDITOR if (_scriptsReloaded) { _scriptsReloaded = false; instance = this; Initialize(); } #endif if (OVRPlugin.shouldQuit) Application.Quit(); if (AllowRecenter && OVRPlugin.shouldRecenter) { OVRManager.display.RecenterPose(); } if (trackingOriginType != _trackingOriginType) trackingOriginType = _trackingOriginType; tracker.isEnabled = usePositionTracking; OVRPlugin.rotation = useRotationTracking; OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking; // Dispatch HMD events. isHmdPresent = OVRNodeStateProperties.IsHmdPresent(); if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel) { Debug.Log("The current MSAA level is " + QualitySettings.antiAliasing + ", but the recommended MSAA level is " + display.recommendedMSAALevel + ". Switching to the recommended level."); QualitySettings.antiAliasing = display.recommendedMSAALevel; } if (monoscopic != _monoscopic) { monoscopic = _monoscopic; } if (headPoseRelativeOffsetRotation != _headPoseRelativeOffsetRotation) { headPoseRelativeOffsetRotation = _headPoseRelativeOffsetRotation; } if (headPoseRelativeOffsetTranslation != _headPoseRelativeOffsetTranslation) { headPoseRelativeOffsetTranslation = _headPoseRelativeOffsetTranslation; } if (_wasHmdPresent && !isHmdPresent) { try { if (HMDLost != null) HMDLost(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_wasHmdPresent && isHmdPresent) { try { if (HMDAcquired != null) HMDAcquired(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _wasHmdPresent = isHmdPresent; // Dispatch HMD mounted events. isUserPresent = OVRPlugin.userPresent; if (_wasUserPresent && !isUserPresent) { try { if (HMDUnmounted != null) HMDUnmounted(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_wasUserPresent && isUserPresent) { try { if (HMDMounted != null) HMDMounted(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _wasUserPresent = isUserPresent; // Dispatch VR Focus events. hasVrFocus = OVRPlugin.hasVrFocus; if (_hadVrFocus && !hasVrFocus) { try { if (VrFocusLost != null) VrFocusLost(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_hadVrFocus && hasVrFocus) { try { if (VrFocusAcquired != null) VrFocusAcquired(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _hadVrFocus = hasVrFocus; // Dispatch VR Input events. bool hasInputFocus = OVRPlugin.hasInputFocus; if (_hadInputFocus && !hasInputFocus) { try { if (InputFocusLost != null) InputFocusLost(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_hadInputFocus && hasInputFocus) { try { if (InputFocusAcquired != null) InputFocusAcquired(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _hadInputFocus = hasInputFocus; // Changing effective rendering resolution dynamically according performance #if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN) if (enableAdaptiveResolution) { #if UNITY_2017_2_OR_NEWER if (UnityEngine.XR.XRSettings.eyeTextureResolutionScale < maxRenderScale) { // Allocate renderScale to max to avoid re-allocation UnityEngine.XR.XRSettings.eyeTextureResolutionScale = maxRenderScale; } else { // Adjusting maxRenderScale in case app started with a larger renderScale value maxRenderScale = Mathf.Max(maxRenderScale, UnityEngine.XR.XRSettings.eyeTextureResolutionScale); } minRenderScale = Mathf.Min(minRenderScale, maxRenderScale); float minViewportScale = minRenderScale / UnityEngine.XR.XRSettings.eyeTextureResolutionScale; float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / UnityEngine.XR.XRSettings.eyeTextureResolutionScale; recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f); UnityEngine.XR.XRSettings.renderViewportScale = recommendedViewportScale; #else if (UnityEngine.VR.VRSettings.renderScale < maxRenderScale) { // Allocate renderScale to max to avoid re-allocation UnityEngine.VR.VRSettings.renderScale = maxRenderScale; } else { // Adjusting maxRenderScale in case app started with a larger renderScale value maxRenderScale = Mathf.Max(maxRenderScale, UnityEngine.VR.VRSettings.renderScale); } minRenderScale = Mathf.Min(minRenderScale, maxRenderScale); float minViewportScale = minRenderScale / UnityEngine.VR.VRSettings.renderScale; float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / UnityEngine.VR.VRSettings.renderScale; recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f); UnityEngine.VR.VRSettings.renderViewportScale = recommendedViewportScale; #endif } #endif // Dispatch Audio Device events. string audioOutId = OVRPlugin.audioOutId; if (!prevAudioOutIdIsCached) { prevAudioOutId = audioOutId; prevAudioOutIdIsCached = true; } else if (audioOutId != prevAudioOutId) { try { if (AudioOutChanged != null) AudioOutChanged(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } prevAudioOutId = audioOutId; } string audioInId = OVRPlugin.audioInId; if (!prevAudioInIdIsCached) { prevAudioInId = audioInId; prevAudioInIdIsCached = true; } else if (audioInId != prevAudioInId) { try { if (AudioInChanged != null) AudioInChanged(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } prevAudioInId = audioInId; } // Dispatch tracking events. if (wasPositionTracked && !tracker.isPositionTracked) { try { if (TrackingLost != null) TrackingLost(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!wasPositionTracked && tracker.isPositionTracked) { try { if (TrackingAcquired != null) TrackingAcquired(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } wasPositionTracked = tracker.isPositionTracked; display.Update(); OVRInput.Update(); #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN if (enableMixedReality || prevEnableMixedReality) { Camera mainCamera = FindMainCamera(); if (Camera.main != null) { suppressDisableMixedRealityBecauseOfNoMainCameraWarning = false; if (enableMixedReality) { OVRMixedReality.Update(this.gameObject, mainCamera, compositionMethod, useDynamicLighting, capturingCameraDevice, depthQuality); } if (prevEnableMixedReality && !enableMixedReality) { OVRMixedReality.Cleanup(); } prevEnableMixedReality = enableMixedReality; } else { if (!suppressDisableMixedRealityBecauseOfNoMainCameraWarning) { Debug.LogWarning("Main Camera is not set, Mixed Reality disabled"); suppressDisableMixedRealityBecauseOfNoMainCameraWarning = true; } } } #endif } private bool multipleMainCameraWarningPresented = false; private Camera FindMainCamera() { GameObject[] objects = GameObject.FindGameObjectsWithTag("MainCamera"); List<Camera> cameras = new List<Camera>(4); foreach (GameObject obj in objects) { Camera camera = obj.GetComponent<Camera>(); if (camera != null && camera.enabled) { OVRCameraRig cameraRig = camera.GetComponentInParent<OVRCameraRig>(); if (cameraRig != null && cameraRig.trackingSpace != null) { cameras.Add(camera); } } } if (cameras.Count == 0) { return Camera.main; // pick one of the cameras which tagged as "MainCamera" } else if (cameras.Count == 1) { return cameras[0]; } else { if (!multipleMainCameraWarningPresented) { Debug.LogWarning("Multiple MainCamera found. Assume the real MainCamera is the camera with the least depth"); multipleMainCameraWarningPresented = true; } // return the camera with least depth cameras.Sort((Camera c0, Camera c1) => { return c0.depth < c1.depth ? -1 : (c0.depth > c1.depth ? 1 : 0); }); return cameras[0]; } } private void OnDisable() { #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN OVRMixedReality.Cleanup(); #endif } private void LateUpdate() { OVRHaptics.Process(); } private void FixedUpdate() { OVRInput.FixedUpdate(); } /// <summary> /// Leaves the application/game and returns to the launcher/dashboard /// </summary> public void ReturnToLauncher() { // show the platform UI quit prompt OVRManager.PlatformUIConfirmQuit(); } #endregion public static void PlatformUIConfirmQuit() { if (!isHmdPresent) return; OVRPlugin.ShowUI(OVRPlugin.PlatformUI.ConfirmQuit); } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using NUnit.Framework; using Newtonsoft.Json; using GlmSharp; // ReSharper disable InconsistentNaming namespace GlmSharpTest.Generated.Swizzle { [TestFixture] public class HalfSwizzleVec2Test { [Test] public void XYZW() { { var ov = new hvec2(new Half(8.5), new Half(9)); var v = ov.swizzle.xx; Assert.AreEqual(new Half(8.5), v.x); Assert.AreEqual(new Half(8.5), v.y); } { var ov = new hvec2(new Half(9.5), new Half(5.5)); var v = ov.swizzle.xxx; Assert.AreEqual(new Half(9.5), v.x); Assert.AreEqual(new Half(9.5), v.y); Assert.AreEqual(new Half(9.5), v.z); } { var ov = new hvec2(new Half(2.5), new Half(-9.5)); var v = ov.swizzle.xxxx; Assert.AreEqual(new Half(2.5), v.x); Assert.AreEqual(new Half(2.5), v.y); Assert.AreEqual(new Half(2.5), v.z); Assert.AreEqual(new Half(2.5), v.w); } { var ov = new hvec2(new Half(-2), new Half(7)); var v = ov.swizzle.xxxy; Assert.AreEqual(new Half(-2), v.x); Assert.AreEqual(new Half(-2), v.y); Assert.AreEqual(new Half(-2), v.z); Assert.AreEqual(new Half(7), v.w); } { var ov = new hvec2(new Half(-3.5), new Half(-7)); var v = ov.swizzle.xxy; Assert.AreEqual(new Half(-3.5), v.x); Assert.AreEqual(new Half(-3.5), v.y); Assert.AreEqual(new Half(-7), v.z); } { var ov = new hvec2(Half.One, new Half(-2)); var v = ov.swizzle.xxyx; Assert.AreEqual(Half.One, v.x); Assert.AreEqual(Half.One, v.y); Assert.AreEqual(new Half(-2), v.z); Assert.AreEqual(Half.One, v.w); } { var ov = new hvec2(new Half(-8.5), new Half(4.5)); var v = ov.swizzle.xxyy; Assert.AreEqual(new Half(-8.5), v.x); Assert.AreEqual(new Half(-8.5), v.y); Assert.AreEqual(new Half(4.5), v.z); Assert.AreEqual(new Half(4.5), v.w); } { var ov = new hvec2(new Half(7), new Half(-1.5)); var v = ov.swizzle.xy; Assert.AreEqual(new Half(7), v.x); Assert.AreEqual(new Half(-1.5), v.y); } { var ov = new hvec2(new Half(0.5), new Half(-3)); var v = ov.swizzle.xyx; Assert.AreEqual(new Half(0.5), v.x); Assert.AreEqual(new Half(-3), v.y); Assert.AreEqual(new Half(0.5), v.z); } { var ov = new hvec2(new Half(-8), new Half(5)); var v = ov.swizzle.xyxx; Assert.AreEqual(new Half(-8), v.x); Assert.AreEqual(new Half(5), v.y); Assert.AreEqual(new Half(-8), v.z); Assert.AreEqual(new Half(-8), v.w); } { var ov = new hvec2(new Half(7), Half.One); var v = ov.swizzle.xyxy; Assert.AreEqual(new Half(7), v.x); Assert.AreEqual(Half.One, v.y); Assert.AreEqual(new Half(7), v.z); Assert.AreEqual(Half.One, v.w); } { var ov = new hvec2(new Half(-4.5), new Half(-7)); var v = ov.swizzle.xyy; Assert.AreEqual(new Half(-4.5), v.x); Assert.AreEqual(new Half(-7), v.y); Assert.AreEqual(new Half(-7), v.z); } { var ov = new hvec2(new Half(6), new Half(-9.5)); var v = ov.swizzle.xyyx; Assert.AreEqual(new Half(6), v.x); Assert.AreEqual(new Half(-9.5), v.y); Assert.AreEqual(new Half(-9.5), v.z); Assert.AreEqual(new Half(6), v.w); } { var ov = new hvec2(new Half(7), new Half(5.5)); var v = ov.swizzle.xyyy; Assert.AreEqual(new Half(7), v.x); Assert.AreEqual(new Half(5.5), v.y); Assert.AreEqual(new Half(5.5), v.z); Assert.AreEqual(new Half(5.5), v.w); } { var ov = new hvec2(new Half(-5.5), new Half(2)); var v = ov.swizzle.yx; Assert.AreEqual(new Half(2), v.x); Assert.AreEqual(new Half(-5.5), v.y); } { var ov = new hvec2(new Half(-4), new Half(8.5)); var v = ov.swizzle.yxx; Assert.AreEqual(new Half(8.5), v.x); Assert.AreEqual(new Half(-4), v.y); Assert.AreEqual(new Half(-4), v.z); } { var ov = new hvec2(new Half(8.5), new Half(-3)); var v = ov.swizzle.yxxx; Assert.AreEqual(new Half(-3), v.x); Assert.AreEqual(new Half(8.5), v.y); Assert.AreEqual(new Half(8.5), v.z); Assert.AreEqual(new Half(8.5), v.w); } { var ov = new hvec2(new Half(-2), Half.Zero); var v = ov.swizzle.yxxy; Assert.AreEqual(Half.Zero, v.x); Assert.AreEqual(new Half(-2), v.y); Assert.AreEqual(new Half(-2), v.z); Assert.AreEqual(Half.Zero, v.w); } { var ov = new hvec2(new Half(-9), new Half(2.5)); var v = ov.swizzle.yxy; Assert.AreEqual(new Half(2.5), v.x); Assert.AreEqual(new Half(-9), v.y); Assert.AreEqual(new Half(2.5), v.z); } { var ov = new hvec2(new Half(-3), new Half(3)); var v = ov.swizzle.yxyx; Assert.AreEqual(new Half(3), v.x); Assert.AreEqual(new Half(-3), v.y); Assert.AreEqual(new Half(3), v.z); Assert.AreEqual(new Half(-3), v.w); } { var ov = new hvec2(new Half(-9.5), new Half(-2)); var v = ov.swizzle.yxyy; Assert.AreEqual(new Half(-2), v.x); Assert.AreEqual(new Half(-9.5), v.y); Assert.AreEqual(new Half(-2), v.z); Assert.AreEqual(new Half(-2), v.w); } { var ov = new hvec2(new Half(-0.5), Half.One); var v = ov.swizzle.yy; Assert.AreEqual(Half.One, v.x); Assert.AreEqual(Half.One, v.y); } { var ov = new hvec2(new Half(6), new Half(-5.5)); var v = ov.swizzle.yyx; Assert.AreEqual(new Half(-5.5), v.x); Assert.AreEqual(new Half(-5.5), v.y); Assert.AreEqual(new Half(6), v.z); } { var ov = new hvec2(new Half(-3), new Half(5)); var v = ov.swizzle.yyxx; Assert.AreEqual(new Half(5), v.x); Assert.AreEqual(new Half(5), v.y); Assert.AreEqual(new Half(-3), v.z); Assert.AreEqual(new Half(-3), v.w); } { var ov = new hvec2(Half.Zero, Half.One); var v = ov.swizzle.yyxy; Assert.AreEqual(Half.One, v.x); Assert.AreEqual(Half.One, v.y); Assert.AreEqual(Half.Zero, v.z); Assert.AreEqual(Half.One, v.w); } { var ov = new hvec2(new Half(-1), new Half(-9)); var v = ov.swizzle.yyy; Assert.AreEqual(new Half(-9), v.x); Assert.AreEqual(new Half(-9), v.y); Assert.AreEqual(new Half(-9), v.z); } { var ov = new hvec2(new Half(-4.5), new Half(8)); var v = ov.swizzle.yyyx; Assert.AreEqual(new Half(8), v.x); Assert.AreEqual(new Half(8), v.y); Assert.AreEqual(new Half(8), v.z); Assert.AreEqual(new Half(-4.5), v.w); } { var ov = new hvec2(new Half(-3), new Half(6.5)); var v = ov.swizzle.yyyy; Assert.AreEqual(new Half(6.5), v.x); Assert.AreEqual(new Half(6.5), v.y); Assert.AreEqual(new Half(6.5), v.z); Assert.AreEqual(new Half(6.5), v.w); } } [Test] public void RGBA() { { var ov = new hvec2(new Half(-6.5), new Half(9.5)); var v = ov.swizzle.rr; Assert.AreEqual(new Half(-6.5), v.x); Assert.AreEqual(new Half(-6.5), v.y); } { var ov = new hvec2(new Half(-2.5), new Half(-8.5)); var v = ov.swizzle.rrr; Assert.AreEqual(new Half(-2.5), v.x); Assert.AreEqual(new Half(-2.5), v.y); Assert.AreEqual(new Half(-2.5), v.z); } { var ov = new hvec2(new Half(-8), new Half(6)); var v = ov.swizzle.rrrr; Assert.AreEqual(new Half(-8), v.x); Assert.AreEqual(new Half(-8), v.y); Assert.AreEqual(new Half(-8), v.z); Assert.AreEqual(new Half(-8), v.w); } { var ov = new hvec2(new Half(3.5), new Half(9.5)); var v = ov.swizzle.rrrg; Assert.AreEqual(new Half(3.5), v.x); Assert.AreEqual(new Half(3.5), v.y); Assert.AreEqual(new Half(3.5), v.z); Assert.AreEqual(new Half(9.5), v.w); } { var ov = new hvec2(new Half(-6), Half.Zero); var v = ov.swizzle.rrg; Assert.AreEqual(new Half(-6), v.x); Assert.AreEqual(new Half(-6), v.y); Assert.AreEqual(Half.Zero, v.z); } { var ov = new hvec2(new Half(-5), new Half(8)); var v = ov.swizzle.rrgr; Assert.AreEqual(new Half(-5), v.x); Assert.AreEqual(new Half(-5), v.y); Assert.AreEqual(new Half(8), v.z); Assert.AreEqual(new Half(-5), v.w); } { var ov = new hvec2(new Half(-9), new Half(6.5)); var v = ov.swizzle.rrgg; Assert.AreEqual(new Half(-9), v.x); Assert.AreEqual(new Half(-9), v.y); Assert.AreEqual(new Half(6.5), v.z); Assert.AreEqual(new Half(6.5), v.w); } { var ov = new hvec2(new Half(-8.5), new Half(9.5)); var v = ov.swizzle.rg; Assert.AreEqual(new Half(-8.5), v.x); Assert.AreEqual(new Half(9.5), v.y); } { var ov = new hvec2(new Half(7), new Half(-4)); var v = ov.swizzle.rgr; Assert.AreEqual(new Half(7), v.x); Assert.AreEqual(new Half(-4), v.y); Assert.AreEqual(new Half(7), v.z); } { var ov = new hvec2(new Half(-2), new Half(-5)); var v = ov.swizzle.rgrr; Assert.AreEqual(new Half(-2), v.x); Assert.AreEqual(new Half(-5), v.y); Assert.AreEqual(new Half(-2), v.z); Assert.AreEqual(new Half(-2), v.w); } { var ov = new hvec2(new Half(7.5), new Half(7)); var v = ov.swizzle.rgrg; Assert.AreEqual(new Half(7.5), v.x); Assert.AreEqual(new Half(7), v.y); Assert.AreEqual(new Half(7.5), v.z); Assert.AreEqual(new Half(7), v.w); } { var ov = new hvec2(new Half(4), new Half(2.5)); var v = ov.swizzle.rgg; Assert.AreEqual(new Half(4), v.x); Assert.AreEqual(new Half(2.5), v.y); Assert.AreEqual(new Half(2.5), v.z); } { var ov = new hvec2(new Half(0.5), new Half(-5)); var v = ov.swizzle.rggr; Assert.AreEqual(new Half(0.5), v.x); Assert.AreEqual(new Half(-5), v.y); Assert.AreEqual(new Half(-5), v.z); Assert.AreEqual(new Half(0.5), v.w); } { var ov = new hvec2(new Half(-4.5), new Half(-1.5)); var v = ov.swizzle.rggg; Assert.AreEqual(new Half(-4.5), v.x); Assert.AreEqual(new Half(-1.5), v.y); Assert.AreEqual(new Half(-1.5), v.z); Assert.AreEqual(new Half(-1.5), v.w); } { var ov = new hvec2(new Half(-6.5), new Half(-5.5)); var v = ov.swizzle.gr; Assert.AreEqual(new Half(-5.5), v.x); Assert.AreEqual(new Half(-6.5), v.y); } { var ov = new hvec2(new Half(1.5), new Half(-2)); var v = ov.swizzle.grr; Assert.AreEqual(new Half(-2), v.x); Assert.AreEqual(new Half(1.5), v.y); Assert.AreEqual(new Half(1.5), v.z); } { var ov = new hvec2(Half.Zero, Half.One); var v = ov.swizzle.grrr; Assert.AreEqual(Half.One, v.x); Assert.AreEqual(Half.Zero, v.y); Assert.AreEqual(Half.Zero, v.z); Assert.AreEqual(Half.Zero, v.w); } { var ov = new hvec2(new Half(5), new Half(4.5)); var v = ov.swizzle.grrg; Assert.AreEqual(new Half(4.5), v.x); Assert.AreEqual(new Half(5), v.y); Assert.AreEqual(new Half(5), v.z); Assert.AreEqual(new Half(4.5), v.w); } { var ov = new hvec2(Half.One, Half.Zero); var v = ov.swizzle.grg; Assert.AreEqual(Half.Zero, v.x); Assert.AreEqual(Half.One, v.y); Assert.AreEqual(Half.Zero, v.z); } { var ov = new hvec2(new Half(2), new Half(8.5)); var v = ov.swizzle.grgr; Assert.AreEqual(new Half(8.5), v.x); Assert.AreEqual(new Half(2), v.y); Assert.AreEqual(new Half(8.5), v.z); Assert.AreEqual(new Half(2), v.w); } { var ov = new hvec2(new Half(-8.5), new Half(-4)); var v = ov.swizzle.grgg; Assert.AreEqual(new Half(-4), v.x); Assert.AreEqual(new Half(-8.5), v.y); Assert.AreEqual(new Half(-4), v.z); Assert.AreEqual(new Half(-4), v.w); } { var ov = new hvec2(new Half(5.5), new Half(-1)); var v = ov.swizzle.gg; Assert.AreEqual(new Half(-1), v.x); Assert.AreEqual(new Half(-1), v.y); } { var ov = new hvec2(Half.Zero, new Half(-6.5)); var v = ov.swizzle.ggr; Assert.AreEqual(new Half(-6.5), v.x); Assert.AreEqual(new Half(-6.5), v.y); Assert.AreEqual(Half.Zero, v.z); } { var ov = new hvec2(new Half(-5), new Half(-6.5)); var v = ov.swizzle.ggrr; Assert.AreEqual(new Half(-6.5), v.x); Assert.AreEqual(new Half(-6.5), v.y); Assert.AreEqual(new Half(-5), v.z); Assert.AreEqual(new Half(-5), v.w); } { var ov = new hvec2(new Half(0.5), new Half(3)); var v = ov.swizzle.ggrg; Assert.AreEqual(new Half(3), v.x); Assert.AreEqual(new Half(3), v.y); Assert.AreEqual(new Half(0.5), v.z); Assert.AreEqual(new Half(3), v.w); } { var ov = new hvec2(new Half(-8.5), new Half(5)); var v = ov.swizzle.ggg; Assert.AreEqual(new Half(5), v.x); Assert.AreEqual(new Half(5), v.y); Assert.AreEqual(new Half(5), v.z); } { var ov = new hvec2(new Half(1.5), new Half(6)); var v = ov.swizzle.gggr; Assert.AreEqual(new Half(6), v.x); Assert.AreEqual(new Half(6), v.y); Assert.AreEqual(new Half(6), v.z); Assert.AreEqual(new Half(1.5), v.w); } { var ov = new hvec2(new Half(8), new Half(-5)); var v = ov.swizzle.gggg; Assert.AreEqual(new Half(-5), v.x); Assert.AreEqual(new Half(-5), v.y); Assert.AreEqual(new Half(-5), v.z); Assert.AreEqual(new Half(-5), v.w); } } [Test] public void InlineXYZW() { { var v0 = new hvec2(new Half(-4.5), new Half(-9.5)); var v1 = new hvec2(new Half(-6.5), new Half(9)); var v2 = v0.xy; v0.xy = v1; var v3 = v0.xy; Assert.AreEqual(v1, v3); Assert.AreEqual(new Half(-6.5), v0.x); Assert.AreEqual(new Half(9), v0.y); Assert.AreEqual(new Half(-4.5), v2.x); Assert.AreEqual(new Half(-9.5), v2.y); } } [Test] public void InlineRGBA() { { var v0 = new hvec2(new Half(6), new Half(6.5)); var v1 = new Half(new Half(-7)); var v2 = v0.r; v0.r = v1; var v3 = v0.r; Assert.AreEqual(v1, v3); Assert.AreEqual(new Half(-7), v0.x); Assert.AreEqual(new Half(6.5), v0.y); Assert.AreEqual(new Half(6), v2); } { var v0 = new hvec2(new Half(6), new Half(-0.5)); var v1 = new Half(new Half(-6)); var v2 = v0.g; v0.g = v1; var v3 = v0.g; Assert.AreEqual(v1, v3); Assert.AreEqual(new Half(6), v0.x); Assert.AreEqual(new Half(-6), v0.y); Assert.AreEqual(new Half(-0.5), v2); } { var v0 = new hvec2(new Half(1.5), Half.One); var v1 = new hvec2(new Half(6.5), new Half(-8)); var v2 = v0.rg; v0.rg = v1; var v3 = v0.rg; Assert.AreEqual(v1, v3); Assert.AreEqual(new Half(6.5), v0.x); Assert.AreEqual(new Half(-8), v0.y); Assert.AreEqual(new Half(1.5), v2.x); Assert.AreEqual(Half.One, v2.y); } } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Apache License, Version 2.0. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections; using System.IO; using System.Xml; using System.Xml.Schema; using Common; using System.Collections.ObjectModel; using System.Security; namespace Randoop { public enum IsNull { Unknown, Yes, No }; public class ResultElementExecutionProperties { public IsNull isNull = IsNull.Unknown; } /// <summary> /// A plan is the data structure that represents a test. /// /// A plan represents a state transformation and the /// values (objects and primitives) resulting from the transformation. /// /// You can also think of a plan as a DAG that represents /// a set of constructor/method calls and their dependencies. /// /// The tests that Randoop creates are string representations /// of plans. /// /// WARNING: THIS CODE IS VERY CONFUSING! We should simplify /// the data structure. If you have questions about it, /// ask Shuvendu Lahiri (shuvendu). /// /// </summary> public class Plan { /// <summary> /// A unique number, different for every plan ever created. /// </summary> public readonly long uniqueId; // Counter that is incremented every time a new plan is created. public static long uniqueIdCounter = 0; private int treenodes; /// <summary> /// The transfomer specifies the state change for this plan. /// </summary> public readonly Transformer transformer; /// <summary> /// The plans to be executed before this plan's transformation. /// </summary> public readonly Plan[] parentPlans; /// <summary> /// The mappings from transformation parameter indices to the /// relevant parent plan results that provides the parameters. /// </summary> public readonly ParameterChooser[] parameterChoosers; public Exception exceptionThrown = null; private readonly bool[] activeTupleElements; private readonly ResultElementExecutionProperties[] resultElementProperties; public override string ToString() { StringBuilder b = new StringBuilder(); foreach (Plan p in parentPlans) { b.Append(p.ToString()); b.AppendLine(); } b.Append("plan " + uniqueId + " transformer=" + transformer.ToString() + " parents=[ "); foreach (Plan p in parentPlans) { b.Append(p.uniqueId + " "); } b.Append("], inputs=[ "); foreach (ParameterChooser pc in parameterChoosers) { b.Append(pc.ToString() + " "); } b.Append("]"); return b.ToString(); } public int NumTupleElements { get { return activeTupleElements.Length; } } public long TestCaseId { get { return uniqueId; } } public ResultElementExecutionProperties GetResultElementProperty(int i) { Util.Assert(i >= 0 && i < resultElementProperties.Length); return resultElementProperties[i]; } public bool IsActiveTupleElement(int i) { Util.Assert(i >= 0 && i < activeTupleElements.Length); return activeTupleElements[i]; } public void SetActiveTupleElement(int i, bool value) { Util.Assert(i >= 0 && i < activeTupleElements.Length); Util.Assert(((this.transformer is ConstructorCallTransformer) ? i != 0 : true)); activeTupleElements[i] = value; } public void SetResultElementProperty(int i, ResultElementExecutionProperties value) { Util.Assert(i >= 0 && i < resultElementProperties.Length); Util.Assert(((this.transformer is ConstructorCallTransformer) ? i != 0 : true)); resultElementProperties[i] = value; } public int numTimesExecuted = 0; public double executionTimeAccum = 0; public double AverageExecutionTime { get { return executionTimeAccum / ((double)numTimesExecuted); } } public double TotalExecutionTime { get { return executionTimeAccum; } } /// <summary> /// Checks that the fparameterChoosers mapping is consistent /// with the result tuples of the parent plans and the /// parameters of the transformer. /// </summary> public void RepOk() { for (int i = 0; i < parameterChoosers.Length; i++) { ParameterChooser c = parameterChoosers[i]; Util.Assert(c.planIndex >= 0 && c.planIndex < parentPlans.Length); Util.Assert(c.resultIndex >= 0 && c.resultIndex < parentPlans[c.planIndex].transformer.TupleTypes.Length); Util.Assert(parentPlans[c.planIndex].transformer.TupleTypes[c.resultIndex] .Equals(transformer.ParameterTypes[i])); } } /// <summary> /// Two plans are equal if their transformers and parent plans are /// equals, and their mapping from parent plan results to /// transformer parameters are the same. /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { Plan o = obj as Plan; if (obj == null) return false; if (this == obj) return true; if (!this.transformer.Equals(o.transformer)) return false; if (this.parentPlans.Length != o.parentPlans.Length) return false; for (int i = 0; i < parentPlans.Length; i++) if (!this.parentPlans[i].Equals(o.parentPlans[i])) return false; if (this.parameterChoosers.Length != o.parameterChoosers.Length) return false; for (int i = 0; i < parameterChoosers.Length; i++) if (!this.parameterChoosers[i].Equals(o.parameterChoosers[i])) return false; return true; } private int hashCodeCached = 0; private bool computedHashCode = false; public override int GetHashCode() { if (!computedHashCode) { hashCodeCached = ComputeHashCode(); } return hashCodeCached; } private int ComputeHashCode() { int result = 7; result = 37 * result + transformer.GetHashCode(); foreach (Plan p in parentPlans) result = 37 * result + p.GetHashCode(); if (parentPlans.Length > 0) { foreach (ParameterChooser c in parameterChoosers) result = 37 * result + c.GetHashCode(); } return result; } /// <summary> /// Specifies a value among all result tuples in the parent plans. /// </summary> public class ParameterChooser { /// <summary> /// Index into array of parent plans. /// </summary> public int planIndex; /// <summary> /// For a given parent plan, index into the array of results for the plan. /// </summary> public int resultIndex; public override bool Equals(object obj) { ParameterChooser c = obj as ParameterChooser; if (c == null) return false; return (this.planIndex == c.planIndex && this.resultIndex == c.resultIndex); } public override int GetHashCode() { return planIndex.GetHashCode() + resultIndex.GetHashCode(); } public ParameterChooser(int planIndex, int resultIndex) { this.planIndex = planIndex; this.resultIndex = resultIndex; } public override string ToString() { return "(" + planIndex + " " + resultIndex + ")"; } } protected Plan() { } private class SingletonDummyVoidPlan : Plan { public SingletonDummyVoidPlan() : base() { } public override bool Equals(object obj) { return obj == this; } public override int GetHashCode() { return 0; } } public static Plan DummyVoidPlan = new SingletonDummyVoidPlan(); /// <summary> /// Creates a Plan. /// </summary> /// <param name="transfomer">The state transformer that this plan represents.</param> /// <param name="parentPlans">The parent plans for this plan.</param> /// <param name="parameterChoosers">The parameter choosers for the parent plans.</param> /// <param name="resultTypes">The types (and number of) results that executing this plan yields.</param> public Plan(Transformer transfomer, Plan[] parentPlans, ParameterChooser[] parameterChoosers) { this.uniqueId = uniqueIdCounter++; this.transformer = transfomer; this.parentPlans = parentPlans; this.parameterChoosers = parameterChoosers; this.activeTupleElements = transformer.DefaultActiveTupleTypes; this.resultElementProperties = new ResultElementExecutionProperties[this.activeTupleElements.Length]; for (int i = 0; i < this.resultElementProperties.Length; i++) this.resultElementProperties[i] = new ResultElementExecutionProperties(); this.treenodes = 1; foreach (Plan p in parentPlans) this.treenodes += p.treenodes; } /// <summary> /// Creates a plan that represents a constant value. /// </summary> /// <param name="t"></param> /// <param name="constantValue"></param> /// <returns></returns> public static Plan Constant(Type t, object constantValue) { return new Plan(PrimitiveValueTransformer.Get(t, constantValue), new Plan[0], new ParameterChooser[0]); } /// <summary> /// Invokes the code that this plan represents. /// TODO: what's the difference between this and the other Execute method? /// </summary> /// <param name="executionResults"></param> /// <returns></returns> public bool ExecuteHelper(out ResultTuple executionResult, TextWriter executionLog, TextWriter debugLog, out Exception exceptionThrown, out bool contractViolated, bool forbidNull) { // Execute parent plans ResultTuple[] results1 = new ResultTuple[parentPlans.Length]; for (int i = 0; i < parentPlans.Length; i++) { Plan plan = parentPlans[i]; ResultTuple tempResults; if (!plan.ExecuteHelper(out tempResults, executionLog, debugLog, out exceptionThrown, out contractViolated, forbidNull)) { executionResult = null; return false; } results1[i] = tempResults; } //// Execute if (!transformer.Execute(out executionResult, results1, parameterChoosers, executionLog, debugLog, out exceptionThrown, out contractViolated, forbidNull)) { executionResult = null; return false; } return true; } /// <summary> /// Invokes the code that this plan represents. /// </summary> /// <param name="executionResults"></param> /// <returns></returns> public bool Execute(out ResultTuple executionResult, TextWriter executionLog, TextWriter debugLog, out Exception exceptionThrown, out bool contractViolated, bool forbidNull, bool monkey) { this.numTimesExecuted++; long startTime = 0; Timer.QueryPerformanceCounter(ref startTime); // Execute parent plans ResultTuple[] results1 = new ResultTuple[parentPlans.Length]; for (int i = 0; i < parentPlans.Length; i++) { Plan plan = parentPlans[i]; ResultTuple tempResults; if (!plan.ExecuteHelper(out tempResults, executionLog, debugLog, out exceptionThrown, out contractViolated, forbidNull)) { executionResult = null; return false; } results1[i] = tempResults; } // Execute. if (!transformer.Execute(out executionResult, results1, parameterChoosers, executionLog, debugLog, out exceptionThrown, out contractViolated, forbidNull)) { executionResult = null; return false; } RecordExecutionTime(startTime); return true; } private void AppendOmitMethodsFile() { //StreamWriter w = File.AppendText("omitmethods.txt"); } public String ToStringAsCSharpCode() { StringBuilder b = new StringBuilder(); foreach (string codeLine in CodeGenerator.AsCSharpCode(this)) { b.AppendLine(codeLine); } return b.ToString(); } public TestCase ToTestCase(Type exceptionThrown, bool printPlanToString, string className) { // Create imports list. Collection<string> imports = new Collection<string>(); foreach (string nameSpace in GetNameSpaces()) imports.Add("using " + nameSpace + ";"); // Create test code list. Collection<string> testCode = new Collection<string>(); foreach (string codeLine in CodeGenerator.AsCSharpCode(this)) { testCode.Add(codeLine); } if (printPlanToString) { testCode.Add("/*"); testCode.Add(this.ToString()); testCode.Add("*/"); } // Create assemblies list. Collection<string> assemblies = GetAssemblies(); // Create LastAction. ////xiao.qu@us.abb.com changes for capture last return value -- start //string last_ret_val = "null"; //string last_ret_type = "null"; //if (this.transformer.ReturnValue.Count != 0) //actions other than "MethodCall" do not have ReturnValue //{ // if (this.transformer.ReturnValue[this.transformer.ReturnValue.Count-1] != null) // { // last_ret_val = this.transformer.ReturnValue[this.transformer.ReturnValue.Count - 1].ToString().Replace("\n", "\\n").Replace("\r", "\\r"); // last_ret_type = this.transformer.ReturnValue[this.transformer.ReturnValue.Count - 1].GetType().ToString(); // } //} ////xiao.qu@us.abb.com changes for capture last return value -- end TestCase.LastAction lastAction = new TestCase.LastAction(TestCase.LastAction.LASTACTION_MARKER // + this.transformer.ToString() //xiao.qu@us.abb.com changes for capture last return value // + " type: " + last_ret_type // + " val: " + last_ret_val); + this.transformer.ToString()); // Create exception. TestCase.ExceptionDescription exception; if (exceptionThrown == null) exception = TestCase.ExceptionDescription.NoException(); else exception = TestCase.ExceptionDescription.GetDescription(exceptionThrown); // Put everything together, return TestCase. return new TestCase(lastAction, exception, imports, assemblies, className, testCode); } private Collection<string> GetNameSpaces() { CollectReferencedAssembliesVisitor v = new CollectReferencedAssembliesVisitor(); this.Visit(v); Collection<string> ret = new Collection<string>(); foreach (string t in v.GetDeclaringTypes()) ret.Add(t); return ret; } private Collection<string> GetAssemblies() { CollectReferencedAssembliesVisitor v = new CollectReferencedAssembliesVisitor(); this.Visit(v); Collection<string> ret = new Collection<string>(); foreach (string t in v.GetAssemblies()) ret.Add(t); return ret; } private void RecordExecutionTime(long startTime) { long endTime = 0; Timer.QueryPerformanceCounter(ref endTime); double executionTime = ((double)(endTime - startTime)) / ((double)(Timer.PerfTimerFrequency)); this.executionTimeAccum += executionTime; } #region IWeightedElement Members public double Weight() { return 1.0 / (1.0 + (double)this.treenodes); } #endregion // TODO this is weird: A plan does not visit a visitor--it's the other way around! public void Visit(IVisitor a) { a.Accept(this); a.Accept(this.transformer); foreach (Plan pp in this.parentPlans) pp.Visit(a); } } /// <summary> /// Collects the objects and primitives resulting from an execution /// as an array of objects. /// </summary> public class ResultTuple { public readonly object[] tuple; public ResultTuple(FieldInfo field, object receiver) { //Util.Assert(receiver != null && field.DeclaringType.IsInstanceOfType(receiver)); tuple = new object[1]; tuple[0] = receiver; } public ResultTuple(ConstructorInfo constructor, object newObject, object[] results) { CheckParams(constructor, newObject, results); tuple = new object[results.Length + 1]; tuple[0] = newObject; for (int i = 0; i < results.Length; i++) tuple[i + 1] = results[i]; } public ResultTuple(MethodInfo method, object receiver, object returnValue, object[] results) { CheckParams(method, receiver, results); tuple = new object[results.Length + 2]; tuple[0] = receiver; tuple[1] = returnValue; for (int i = 0; i < results.Length; i++) tuple[i + 2] = results[i]; } private void CheckParams(MethodBase method, object receiver, object[] results) { ParameterInfo[] parameters = method.GetParameters(); //Util.Assert(receiver != null && method.DeclaringType.IsInstanceOfType(receiver)); for (int i = 0; i < results.Length; i++) { Type t = parameters[i].ParameterType; if (t.IsPrimitive) Util.Assert(results[i] != null); else { //Util.Assert(results[i] == null || t.IsInstanceOfType(results[i])); } } } public ResultTuple(Type t, object[] results) { Util.Assert(results.Length == 1); tuple = new object[1]; tuple[0] = results[0]; } public ResultTuple(ArrayOrArrayListBuilderTransformer arrayBuilder, object resultingArray) { tuple = new object[1]; tuple[0] = resultingArray; } } }
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Security.Permissions; namespace MCEBuddy.Service { #region Win32 API Declarations [Flags] enum ServiceControlAccessRights : int { SC_MANAGER_CONNECT = 0x0001, // Required to connect to the service control manager. SC_MANAGER_CREATE_SERVICE = 0x0002, // Required to call the CreateService function to create a service object and add it to the database. SC_MANAGER_ENUMERATE_SERVICE = 0x0004, // Required to call the EnumServicesStatusEx function to list the services that are in the database. SC_MANAGER_LOCK = 0x0008, // Required to call the LockServiceDatabase function to acquire a lock on the database. SC_MANAGER_QUERY_LOCK_STATUS = 0x0010, // Required to call the QueryServiceLockStatus function to retrieve the lock status information for the database SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020, // Required to call the NotifyBootConfigStatus function. SC_MANAGER_ALL_ACCESS = 0xF003F // Includes STANDARD_RIGHTS_REQUIRED, in addition to all access rights in this table. } [Flags] enum ServiceAccessRights : int { SERVICE_QUERY_CONFIG = 0x0001, // Required to call the QueryServiceConfig and QueryServiceConfig2 functions to query the service configuration. SERVICE_CHANGE_CONFIG = 0x0002, // Required to call the ChangeServiceConfig or ChangeServiceConfig2 function to change the service configuration. Because this grants the caller the right to change the executable file that the system runs, it should be granted only to administrators. SERVICE_QUERY_STATUS = 0x0004, // Required to call the QueryServiceStatusEx function to ask the service control manager about the status of the service. SERVICE_ENUMERATE_DEPENDENTS = 0x0008, // Required to call the EnumDependentServices function to enumerate all the services dependent on the service. SERVICE_START = 0x0010, // Required to call the StartService function to start the service. SERVICE_STOP = 0x0020, // Required to call the ControlService function to stop the service. SERVICE_PAUSE_CONTINUE = 0x0040, // Required to call the ControlService function to pause or continue the service. SERVICE_INTERROGATE = 0x0080, // Required to call the ControlService function to ask the service to report its status immediately. SERVICE_USER_DEFINED_CONTROL = 0x0100, // Required to call the ControlService function to specify a user-defined control code. SERVICE_ALL_ACCESS = 0xF01FF // Includes STANDARD_RIGHTS_REQUIRED in addition to all access rights in this table. } enum ServiceConfig2InfoLevel : int { SERVICE_CONFIG_DESCRIPTION = 0x00000001, // The lpBuffer parameter is a pointer to a SERVICE_DESCRIPTION structure. SERVICE_CONFIG_FAILURE_ACTIONS = 0x00000002 // The lpBuffer parameter is a pointer to a SERVICE_FAILURE_ACTIONS structure. } enum SC_ACTION_TYPE : uint { SC_ACTION_NONE = 0x00000000, // No action. SC_ACTION_RESTART = 0x00000001, // Restart the service. SC_ACTION_REBOOT = 0x00000002, // Reboot the computer. SC_ACTION_RUN_COMMAND = 0x00000003 // Run a command. } struct SERVICE_FAILURE_ACTIONS { [MarshalAs(UnmanagedType.U4)] public UInt32 dwResetPeriod; [MarshalAs(UnmanagedType.LPStr)] public String lpRebootMsg; [MarshalAs(UnmanagedType.LPStr)] public String lpCommand; [MarshalAs(UnmanagedType.U4)] public UInt32 cActions; public IntPtr lpsaActions; } struct SC_ACTION { [MarshalAs(UnmanagedType.U4)] public SC_ACTION_TYPE Type; [MarshalAs(UnmanagedType.U4)] public UInt32 Delay; } #endregion #region Native Methods class NativeMethods { private NativeMethods() { } [DllImport("advapi32.dll", EntryPoint = "OpenSCManager")] public static extern IntPtr OpenSCManager( string machineName, string databaseName, ServiceControlAccessRights desiredAccess); [DllImport("advapi32.dll", EntryPoint = "CloseServiceHandle")] public static extern int CloseServiceHandle(IntPtr hSCObject); [DllImport("advapi32.dll", EntryPoint = "OpenService")] public static extern IntPtr OpenService( IntPtr hSCManager, string serviceName, ServiceAccessRights desiredAccess); [DllImport("advapi32.dll", EntryPoint = "QueryServiceConfig2")] public static extern int QueryServiceConfig2( IntPtr hService, ServiceConfig2InfoLevel dwInfoLevel, IntPtr lpBuffer, int cbBufSize, out int pcbBytesNeeded); [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2")] public static extern int ChangeServiceConfig2( IntPtr hService, ServiceConfig2InfoLevel dwInfoLevel, IntPtr lpInfo); } #endregion public class ServiceControlManager: IDisposable { private IntPtr SCManager; private bool disposed; /// <summary> /// Calls the Win32 OpenService function and performs error checking. /// </summary> /// <exception cref="ComponentModel.Win32Exception">"Unable to open the requested Service."</exception> private IntPtr OpenService(string serviceName, ServiceAccessRights desiredAccess) { // Open the service IntPtr service = NativeMethods.OpenService( SCManager, serviceName, desiredAccess); // Verify if the service is opened if (service == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to open the requested Service."); } return service; } /// <summary> /// Initializes a new instance of the <see cref="ServiceControlManager"/> class. /// </summary> /// <exception cref="ComponentModel.Win32Exception">"Unable to open Service Control Manager."</exception> [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] public ServiceControlManager() { // Open the service control manager SCManager = NativeMethods.OpenSCManager( null, null, ServiceControlAccessRights.SC_MANAGER_CONNECT); // Verify if the SC is opened if (SCManager == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to open Service Control Manager."); } } /// <summary> /// Dertermines whether the nominated service is set to restart on failure. /// </summary> /// <exception cref="ComponentModel.Win32Exception">"Unable to query the Service configuration."</exception> [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] public bool HasRestartOnFailure(string serviceName) { const int bufferSize = 1024 * 8; IntPtr service = IntPtr.Zero; IntPtr bufferPtr = IntPtr.Zero; bool result = false; try { // Open the service service = OpenService(serviceName, ServiceAccessRights.SERVICE_QUERY_CONFIG); int dwBytesNeeded = 0; // Allocate memory for struct bufferPtr = Marshal.AllocHGlobal(bufferSize); int queryResult = NativeMethods.QueryServiceConfig2( service, ServiceConfig2InfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, bufferPtr, bufferSize, out dwBytesNeeded); if (queryResult == 0) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to query the Service configuration."); } // Cast the buffer to a QUERY_SERVICE_CONFIG struct SERVICE_FAILURE_ACTIONS config = (SERVICE_FAILURE_ACTIONS)Marshal.PtrToStructure(bufferPtr, typeof(SERVICE_FAILURE_ACTIONS)); // Determine whether the service is set to auto restart if (config.cActions != 0) { SC_ACTION action = (SC_ACTION)Marshal.PtrToStructure(config.lpsaActions, typeof(SC_ACTION)); result = (action.Type == SC_ACTION_TYPE.SC_ACTION_RESTART); } return result; } finally { // Clean up if (bufferPtr != IntPtr.Zero) { Marshal.FreeHGlobal(bufferPtr); } if (service != IntPtr.Zero) { NativeMethods.CloseServiceHandle(service); } } } /// <summary> /// Sets the nominated service to restart on failure. /// </summary> [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] public void SetRestartOnFailure(string serviceName) { const int actionCount = 2; const uint delay = 60000; IntPtr service = IntPtr.Zero; IntPtr failureActionsPtr = IntPtr.Zero; IntPtr actionPtr = IntPtr.Zero; try { // Open the service service = OpenService(serviceName, ServiceAccessRights.SERVICE_CHANGE_CONFIG | ServiceAccessRights.SERVICE_START); // Allocate memory for the individual actions actionPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SC_ACTION)) * actionCount); // Set up the restart action SC_ACTION action1 = new SC_ACTION(); action1.Type = SC_ACTION_TYPE.SC_ACTION_RESTART; action1.Delay = delay; Marshal.StructureToPtr(action1, actionPtr, false); // Set up the "do nothing" action SC_ACTION action2 = new SC_ACTION(); action2.Type = SC_ACTION_TYPE.SC_ACTION_NONE; action2.Delay = delay; Marshal.StructureToPtr(action2, (IntPtr)((Int64)actionPtr + Marshal.SizeOf(typeof(SC_ACTION))), false); // Set up the failure actions SERVICE_FAILURE_ACTIONS failureActions = new SERVICE_FAILURE_ACTIONS(); failureActions.dwResetPeriod = 1*24*60*60; //Time after which to reset the failure count in seconds, set to 1 day failureActions.cActions = actionCount; failureActions.lpsaActions = actionPtr; failureActionsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SERVICE_FAILURE_ACTIONS))); Marshal.StructureToPtr(failureActions, failureActionsPtr, false); // Make the change int changeResult = NativeMethods.ChangeServiceConfig2( service, ServiceConfig2InfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, failureActionsPtr); // Check that the change occurred if (changeResult == 0) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to change the Service configuration."); } } finally { // Clean up if (failureActionsPtr != IntPtr.Zero) { Marshal.FreeHGlobal(failureActionsPtr); } if (actionPtr != IntPtr.Zero) { Marshal.FreeHGlobal(actionPtr); } if (service != IntPtr.Zero) { NativeMethods.CloseServiceHandle(service); } } } #region IDisposable Members /// <summary> /// See <see cref="IDisposable.Dispose"/>. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Implements the Dispose(bool) pattern outlined by MSDN and enforced by FxCop. /// </summary> private void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { // Dispose managed resources here } // Unmanaged resources always need disposing if (SCManager != IntPtr.Zero) { NativeMethods.CloseServiceHandle(SCManager); SCManager = IntPtr.Zero; } } disposed = true; } /// <summary> /// Finalizer for the <see cref="ServiceControlManager"/> class. /// </summary> ~ServiceControlManager() { Dispose(false); } #endregion } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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; namespace SharpDX.XAudio2 { public partial class Voice { protected readonly XAudio2 device; protected Voice(XAudio2 device) : base(IntPtr.Zero) { this.device = device; } /// <summary> /// <p>Returns information about the creation flags, input channels, and sample rate of a voice.</p> /// </summary> /// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='IXAudio2Voice::GetVoiceDetails']/*"/> /// <msdn-id>microsoft.directx_sdk.ixaudio2voice.ixaudio2voice.getvoicedetails</msdn-id> /// <unmanaged>GetVoiceDetails</unmanaged> /// <unmanaged-short>GetVoiceDetails</unmanaged-short> /// <unmanaged>void IXAudio2Voice::GetVoiceDetails([Out] XAUDIO2_VOICE_DETAILS* pVoiceDetails)</unmanaged> public SharpDX.XAudio2.VoiceDetails VoiceDetails { get { SharpDX.XAudio2.VoiceDetails __output__; GetVoiceDetails(out __output__); // Handle 2.7 version changes here if (device.Version == XAudio2Version.Version27) { __output__.InputSampleRate = __output__.InputChannelCount; __output__.InputChannelCount = __output__.ActiveFlags; __output__.ActiveFlags = 0; } return __output__; } } /// <summary> /// Enables the effect at a given position in the effect chain of the voice. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect in the effect chain of the voice. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::EnableEffect([None] UINT32 EffectIndex,[None] UINT32 OperationSet)</unmanaged> public void EnableEffect(int effectIndex) { EnableEffect(effectIndex, 0); } /// <summary> /// Disables the effect at a given position in the effect chain of the voice. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect in the effect chain of the voice. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::DisableEffect([None] UINT32 EffectIndex,[None] UINT32 OperationSet)</unmanaged> public void DisableEffect(int effectIndex) { DisableEffect(effectIndex, 0); } /// <summary> /// Sets parameters for a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <returns>Returns the current values of the effect-specific parameters.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged> public T GetEffectParameters<T>(int effectIndex) where T : struct { unsafe { var effectParameter = default(T); byte* pEffectParameter = stackalloc byte[Utilities.SizeOf<T>()]; GetEffectParameters(effectIndex, (IntPtr)pEffectParameter, Utilities.SizeOf<T>()); Utilities.Read((IntPtr)pEffectParameter, ref effectParameter); return effectParameter; } } /// <summary> /// Returns the current effect-specific parameters of a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <param name="effectParameters">[out] Returns the current values of the effect-specific parameters. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::GetEffectParameters([None] UINT32 EffectIndex,[Out, Buffer] void* pParameters,[None] UINT32 ParametersByteSize)</unmanaged> public void GetEffectParameters(int effectIndex, byte[] effectParameters) { unsafe { fixed (void* pEffectParameter = &effectParameters[0]) GetEffectParameters(effectIndex, (IntPtr)pEffectParameter, effectParameters.Length); } } /// <summary> /// Sets parameters for a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged> public void SetEffectParameters(int effectIndex, byte[] effectParameter) { SetEffectParameters(effectIndex, effectParameter, 0); } /// <summary> /// Sets parameters for a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param> /// <param name="operationSet">[in] Identifies this call as part of a deferred batch. See the {{XAudio2 Operation Sets}} overview for more information. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged> public void SetEffectParameters(int effectIndex, byte[] effectParameter, int operationSet) { unsafe { fixed (void* pEffectParameter = &effectParameter[0]) SetEffectParameters(effectIndex, (IntPtr)pEffectParameter, effectParameter.Length, operationSet); } } /// <summary> /// Sets parameters for a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged> public void SetEffectParameters<T>(int effectIndex, T effectParameter) where T : struct { this.SetEffectParameters<T>(effectIndex, effectParameter, 0); } /// <summary> /// Sets parameters for a given effect in the voice's effect chain. /// </summary> /// <param name="effectIndex">[in] Zero-based index of an effect within the voice's effect chain. </param> /// <param name="effectParameter">[in] Returns the current values of the effect-specific parameters. </param> /// <param name="operationSet">[in] Identifies this call as part of a deferred batch. See the {{XAudio2 Operation Sets}} overview for more information. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectParameters([None] UINT32 EffectIndex,[In, Buffer] const void* pParameters,[None] UINT32 ParametersByteSize,[None] UINT32 OperationSet)</unmanaged> public void SetEffectParameters<T>(int effectIndex, T effectParameter, int operationSet) where T : struct { unsafe { byte* pEffectParameter = stackalloc byte[Utilities.SizeOf<T>()]; Utilities.Write((IntPtr)pEffectParameter, ref effectParameter); SetEffectParameters(effectIndex, (IntPtr) pEffectParameter, Utilities.SizeOf<T>(), operationSet); } } /// <summary> /// Replaces the effect chain of the voice. /// </summary> /// <param name="effectDescriptors">[in, optional] an array of <see cref="SharpDX.XAudio2.EffectDescriptor"/> structure that describes the new effect chain to use. If NULL is passed, the current effect chain is removed. If array is non null, its length must be at least of 1. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetEffectChain([In, Optional] const XAUDIO2_EFFECT_CHAIN* pEffectChain)</unmanaged> public void SetEffectChain(params EffectDescriptor[] effectDescriptors) { unsafe { if (effectDescriptors != null) { var tempSendDescriptor = new EffectChain(); var effectDescriptorNatives = new EffectDescriptor.__Native[effectDescriptors.Length]; for (int i = 0; i < effectDescriptorNatives.Length; i++) effectDescriptors[i].__MarshalTo(ref effectDescriptorNatives[i]); tempSendDescriptor.EffectCount = effectDescriptorNatives.Length; fixed (void* pEffectDescriptors = &effectDescriptorNatives[0]) { tempSendDescriptor.EffectDescriptorPointer = (IntPtr)pEffectDescriptors; SetEffectChain(tempSendDescriptor); } } else { SetEffectChain((EffectChain?) null); } } } /// <summary> /// Designates a new set of submix or mastering voices to receive the output of the voice. /// </summary> /// <param name="outputVoices">[in] Array of <see cref="VoiceSendDescriptor"/> structure pointers to destination voices. If outputVoices is NULL, the voice will send its output to the current mastering voice. To set the voice to not send its output anywhere set an array of length 0. All of the voices in a send list must have the same input sample rate, see {{XAudio2 Sample Rate Conversions}} for additional information. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetOutputVoices([In, Optional] const XAUDIO2_VOICE_SENDS* pSendList)</unmanaged> public void SetOutputVoices(params VoiceSendDescriptor[] outputVoices) { unsafe { if (outputVoices != null) { var tempSendDescriptor = new VoiceSendDescriptors {SendCount = outputVoices.Length}; if(outputVoices.Length > 0) { fixed(void* pVoiceSendDescriptors = &outputVoices[0]) { tempSendDescriptor.SendPointer = (IntPtr)pVoiceSendDescriptors; SetOutputVoices(tempSendDescriptor); } } else { tempSendDescriptor.SendPointer = IntPtr.Zero; } } else { SetOutputVoices((VoiceSendDescriptors?) null); } } } /// <summary> /// Sets the volume level of each channel of the final output for the voice. These channels are mapped to the input channels of a specified destination voice. /// </summary> /// <param name="sourceChannels">[in] Confirms the output channel count of the voice. This is the number of channels that are produced by the last effect in the chain. </param> /// <param name="destinationChannels">[in] Confirms the input channel count of the destination voice. </param> /// <param name="levelMatrixRef">[in] Array of [SourceChannels ? DestinationChannels] volume levels sent to the destination voice. The level sent from source channel S to destination channel D is specified in the form pLevelMatrix[SourceChannels ? D + S]. For example, when rendering two-channel stereo input into 5.1 output that is weighted toward the front channels?but is absent from the center and low-frequency channels?the matrix might have the values shown in the following table. OutputLeft InputRight Input Left1.00.0 Right0.01.0 Front Center0.00.0 LFE0.00.0 Rear Left0.80.0 Rear Right0.00.8 Note that the left and right input are fully mapped to the output left and right channels; 80 percent of the left and right input is mapped to the rear left and right channels. See Remarks for more information on volume levels. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetOutputMatrix([In, Optional] IXAudio2Voice* pDestinationVoice,[None] UINT32 SourceChannels,[None] UINT32 DestinationChannels,[In, Buffer] const float* pLevelMatrix,[None] UINT32 OperationSet)</unmanaged> public void SetOutputMatrix(int sourceChannels, int destinationChannels, float[] levelMatrixRef) { this.SetOutputMatrix(sourceChannels, destinationChannels, levelMatrixRef, 0); } /// <summary> /// Sets the volume level of each channel of the final output for the voice. These channels are mapped to the input channels of a specified destination voice. /// </summary> /// <param name="destinationVoiceRef">[in] Pointer to a destination <see cref="SharpDX.XAudio2.Voice"/> for which to set volume levels. Note If the voice sends to a single target voice then specifying NULL will cause SetOutputMatrix to operate on that target voice. </param> /// <param name="sourceChannels">[in] Confirms the output channel count of the voice. This is the number of channels that are produced by the last effect in the chain. </param> /// <param name="destinationChannels">[in] Confirms the input channel count of the destination voice. </param> /// <param name="levelMatrixRef">[in] Array of [SourceChannels ? DestinationChannels] volume levels sent to the destination voice. The level sent from source channel S to destination channel D is specified in the form pLevelMatrix[SourceChannels ? D + S]. For example, when rendering two-channel stereo input into 5.1 output that is weighted toward the front channels?but is absent from the center and low-frequency channels?the matrix might have the values shown in the following table. OutputLeft InputRight Input Left1.00.0 Right0.01.0 Front Center0.00.0 LFE0.00.0 Rear Left0.80.0 Rear Right0.00.8 Note that the left and right input are fully mapped to the output left and right channels; 80 percent of the left and right input is mapped to the rear left and right channels. See Remarks for more information on volume levels. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetOutputMatrix([In, Optional] IXAudio2Voice* pDestinationVoice,[None] UINT32 SourceChannels,[None] UINT32 DestinationChannels,[In, Buffer] const float* pLevelMatrix,[None] UINT32 OperationSet)</unmanaged> public void SetOutputMatrix(SharpDX.XAudio2.Voice destinationVoiceRef, int sourceChannels, int destinationChannels, float[] levelMatrixRef) { this.SetOutputMatrix(destinationVoiceRef, sourceChannels, destinationChannels, levelMatrixRef, 0); } /// <summary> /// Sets the volume level of each channel of the final output for the voice. These channels are mapped to the input channels of a specified destination voice. /// </summary> /// <param name="sourceChannels">[in] Confirms the output channel count of the voice. This is the number of channels that are produced by the last effect in the chain. </param> /// <param name="destinationChannels">[in] Confirms the input channel count of the destination voice. </param> /// <param name="levelMatrixRef">[in] Array of [SourceChannels ? DestinationChannels] volume levels sent to the destination voice. The level sent from source channel S to destination channel D is specified in the form pLevelMatrix[SourceChannels ? D + S]. For example, when rendering two-channel stereo input into 5.1 output that is weighted toward the front channels?but is absent from the center and low-frequency channels?the matrix might have the values shown in the following table. OutputLeft InputRight Input Left1.00.0 Right0.01.0 Front Center0.00.0 LFE0.00.0 Rear Left0.80.0 Rear Right0.00.8 Note that the left and right input are fully mapped to the output left and right channels; 80 percent of the left and right input is mapped to the rear left and right channels. See Remarks for more information on volume levels. </param> /// <param name="operationSet">[in] Identifies this call as part of a deferred batch. See the {{XAudio2 Operation Sets}} overview for more information. </param> /// <returns>No documentation.</returns> /// <unmanaged>HRESULT IXAudio2Voice::SetOutputMatrix([In, Optional] IXAudio2Voice* pDestinationVoice,[None] UINT32 SourceChannels,[None] UINT32 DestinationChannels,[In, Buffer] const float* pLevelMatrix,[None] UINT32 OperationSet)</unmanaged> public void SetOutputMatrix(int sourceChannels, int destinationChannels, float[] levelMatrixRef, int operationSet) { this.SetOutputMatrix(null, sourceChannels, destinationChannels, levelMatrixRef, operationSet); } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.ComponentModel; /// <summary> /// Represents a collection of members of GroupMember type. /// </summary> public sealed class GroupMemberCollection : ComplexPropertyCollection<GroupMember>, ICustomUpdateSerializer { /// <summary> /// If the collection is cleared, then store PDL members collection is updated with "SetItemField". /// If the collection is not cleared, then store PDL members collection is updated with "AppendToItemField". /// </summary> private bool collectionIsCleared = false; /// <summary> /// Initializes a new instance of the <see cref="GroupMemberCollection"/> class. /// </summary> public GroupMemberCollection() : base() { } /// <summary> /// Finds the member with the specified key in the collection. /// Members that have not yet been saved do not have a key. /// </summary> /// <param name="key">The key of the member to find.</param> /// <returns>The member with the specified key.</returns> public GroupMember Find(string key) { EwsUtilities.ValidateParam(key, "key"); foreach (GroupMember item in this.Items) { if (item.Key == key) { return item; } } return null; } /// <summary> /// Clears the collection. /// </summary> public void Clear() { // mark the whole collection for deletion this.InternalClear(); this.collectionIsCleared = true; } /// <summary> /// Adds a member to the collection. /// </summary> /// <param name="member">The member to add.</param> public void Add(GroupMember member) { EwsUtilities.ValidateParam(member, "member"); EwsUtilities.Assert( member.Key == null, "GroupMemberCollection.Add", "member.Key is not null."); EwsUtilities.Assert( !this.Contains(member), "GroupMemberCollection.Add", "The member is already in the collection"); this.InternalAdd(member); } /// <summary> /// Adds multiple members to the collection. /// </summary> /// <param name="members">The members to add.</param> public void AddRange(IEnumerable<GroupMember> members) { EwsUtilities.ValidateParam(members, "members"); foreach (GroupMember member in members) { this.Add(member); } } /// <summary> /// Adds a member linked to a Contact Group. /// </summary> /// <param name="contactGroupId">The Id of the contact group.</param> public void AddContactGroup(ItemId contactGroupId) { this.Add(new GroupMember(contactGroupId)); } /// <summary> /// Adds a member linked to a specific contact's e-mail address. /// </summary> /// <param name="contactId">The Id of the contact.</param> /// <param name="addressToLink">The contact's address to link to.</param> public void AddPersonalContact(ItemId contactId, string addressToLink) { this.Add(new GroupMember(contactId, addressToLink)); } /// <summary> /// Adds a member linked to a contact's first available e-mail address. /// </summary> /// <param name="contactId">The Id of the contact.</param> public void AddPersonalContact(ItemId contactId) { this.AddPersonalContact(contactId, null); } /// <summary> /// Adds a member linked to an Active Directory user. /// </summary> /// <param name="smtpAddress">The SMTP address of the member.</param> public void AddDirectoryUser(string smtpAddress) { this.AddDirectoryUser(smtpAddress, EmailAddress.SmtpRoutingType); } /// <summary> /// Adds a member linked to an Active Directory user. /// </summary> /// <param name="address">The address of the member.</param> /// <param name="routingType">The routing type of the address.</param> public void AddDirectoryUser(string address, string routingType) { this.Add(new GroupMember(address, routingType, MailboxType.Mailbox)); } /// <summary> /// Adds a member linked to an Active Directory contact. /// </summary> /// <param name="smtpAddress">The SMTP address of the Active Directory contact.</param> public void AddDirectoryContact(string smtpAddress) { this.AddDirectoryContact(smtpAddress, EmailAddress.SmtpRoutingType); } /// <summary> /// Adds a member linked to an Active Directory contact. /// </summary> /// <param name="address">The address of the Active Directory contact.</param> /// <param name="routingType">The routing type of the address.</param> public void AddDirectoryContact(string address, string routingType) { this.Add(new GroupMember(address, routingType, MailboxType.Contact)); } /// <summary> /// Adds a member linked to a Public Group. /// </summary> /// <param name="smtpAddress">The SMTP address of the Public Group.</param> public void AddPublicGroup(string smtpAddress) { this.Add(new GroupMember(smtpAddress, EmailAddress.SmtpRoutingType, MailboxType.PublicGroup)); } /// <summary> /// Adds a member linked to a mail-enabled Public Folder. /// </summary> /// <param name="smtpAddress">The SMTP address of the mail-enabled Public Folder.</param> public void AddDirectoryPublicFolder(string smtpAddress) { this.Add(new GroupMember(smtpAddress, EmailAddress.SmtpRoutingType, MailboxType.PublicFolder)); } /// <summary> /// Adds a one-off member. /// </summary> /// <param name="displayName">The display name of the member.</param> /// <param name="address">The address of the member.</param> /// <param name="routingType">The routing type of the address.</param> public void AddOneOff(string displayName, string address, string routingType) { this.Add(new GroupMember(displayName, address, routingType)); } /// <summary> /// Adds a one-off member. /// </summary> /// <param name="displayName">The display name of the member.</param> /// <param name="smtpAddress">The SMTP address of the member.</param> public void AddOneOff(string displayName, string smtpAddress) { this.AddOneOff(displayName, smtpAddress, EmailAddress.SmtpRoutingType); } /// <summary> /// Adds a member that is linked to a specific e-mail address of a contact. /// </summary> /// <param name="contact">The contact to link to.</param> /// <param name="emailAddressKey">The contact's e-mail address to link to.</param> public void AddContactEmailAddress(Contact contact, EmailAddressKey emailAddressKey) { this.Add(new GroupMember(contact, emailAddressKey)); } /// <summary> /// Removes a member at the specified index. /// </summary> /// <param name="index">The index of the member to remove.</param> public void RemoveAt(int index) { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException("index", Strings.IndexIsOutOfRange); } this.InternalRemoveAt(index); } /// <summary> /// Removes a member from the collection. /// </summary> /// <param name="member">The member to remove.</param> /// <returns>True if the group member was successfully removed from the collection, false otherwise.</returns> public bool Remove(GroupMember member) { return this.InternalRemove(member); } /// <summary> /// Writes the update to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="ownerObject">The ews object.</param> /// <param name="propertyDefinition">Property definition.</param> /// <returns>True if property generated serialization.</returns> bool ICustomUpdateSerializer.WriteSetUpdateToXml( EwsServiceXmlWriter writer, ServiceObject ownerObject, PropertyDefinition propertyDefinition) { if (this.collectionIsCleared) { if (this.AddedItems.Count == 0) { // Delete the whole members collection this.WriteDeleteMembersCollectionToXml(writer); } else { // The collection is cleared, so Set this.WriteSetOrAppendMembersToXml(writer, this.AddedItems, true); } } else { // The collection is not cleared, i.e. dl.Members.Clear() is not called. // Append AddedItems. this.WriteSetOrAppendMembersToXml(writer, this.AddedItems, false); // Since member replacement is not supported by server // Delete old ModifiedItems, then recreate new instead. this.WriteDeleteMembersToXml(writer, this.ModifiedItems); this.WriteSetOrAppendMembersToXml(writer, this.ModifiedItems, false); // Delete RemovedItems. this.WriteDeleteMembersToXml(writer, this.RemovedItems); } return true; } /// <summary> /// Writes the deletion update to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="ewsObject">The ews object.</param> /// <returns>True if property generated serialization.</returns> bool ICustomUpdateSerializer.WriteDeleteUpdateToXml(EwsServiceXmlWriter writer, ServiceObject ewsObject) { return false; } /// <summary> /// Creates a GroupMember object from an XML element name. /// </summary> /// <param name="xmlElementName">The XML element name from which to create the e-mail address.</param> /// <returns>An GroupMember object.</returns> internal override GroupMember CreateComplexProperty(string xmlElementName) { return new GroupMember(); } /// <summary> /// Clears the change log. /// </summary> internal override void ClearChangeLog() { base.ClearChangeLog(); this.collectionIsCleared = false; } /// <summary> /// Retrieves the XML element name corresponding to the provided GroupMember object. /// </summary> /// <param name="member">The GroupMember object from which to determine the XML element name.</param> /// <returns>The XML element name corresponding to the provided GroupMember object.</returns> internal override string GetCollectionItemXmlElementName(GroupMember member) { return XmlElementNames.Member; } /// <summary> /// Delete the whole members collection. /// </summary> /// <param name="writer">Xml writer.</param> private void WriteDeleteMembersCollectionToXml(EwsServiceXmlWriter writer) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.DeleteItemField); ContactGroupSchema.Members.WriteToXml(writer); writer.WriteEndElement(); } /// <summary> /// Generate XML to delete individual members. /// </summary> /// <param name="writer">Xml writer.</param> /// <param name="members">Members to delete.</param> private void WriteDeleteMembersToXml(EwsServiceXmlWriter writer, List<GroupMember> members) { if (members.Count != 0) { GroupMemberPropertyDefinition memberPropDef = new GroupMemberPropertyDefinition(); foreach (GroupMember member in members) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.DeleteItemField); memberPropDef.Key = member.Key; memberPropDef.WriteToXml(writer); writer.WriteEndElement(); // DeleteItemField } } } /// <summary> /// Generate XML to Set or Append members. /// When members are set, the existing PDL member collection is cleared. /// On append members are added to the PDL existing members collection. /// </summary> /// <param name="writer">Xml writer.</param> /// <param name="members">Members to set or append.</param> /// <param name="setMode">True - set members, false - append members.</param> private void WriteSetOrAppendMembersToXml(EwsServiceXmlWriter writer, List<GroupMember> members, bool setMode) { if (members.Count != 0) { writer.WriteStartElement(XmlNamespace.Types, setMode ? XmlElementNames.SetItemField : XmlElementNames.AppendToItemField); ContactGroupSchema.Members.WriteToXml(writer); writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.DistributionList); writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Members); foreach (GroupMember member in members) { member.WriteToXml(writer, XmlElementNames.Member); } writer.WriteEndElement(); // Members writer.WriteEndElement(); // Group writer.WriteEndElement(); // setMode ? SetItemField : AppendItemField } } /// <summary> /// Validates this instance. /// </summary> internal override void InternalValidate() { base.InternalValidate(); foreach (GroupMember groupMember in this.ModifiedItems) { if (string.IsNullOrEmpty(groupMember.Key)) { throw new ServiceValidationException(Strings.ContactGroupMemberCannotBeUpdatedWithoutBeingLoadedFirst); } } } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Newtonsoft.Json; using Sensus.Exceptions; using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Text.RegularExpressions; namespace Sensus.DataStores.Local { public class FileLocalDataStore : LocalDataStore { private const double REMOTE_COMMIT_TRIGGER_STORAGE_DIRECTORY_SIZE_MB = 10; private const double MAX_FILE_SIZE_MB = 1; private string _path; private readonly object _storageDirectoryLocker = new object(); [JsonIgnore] public string StorageDirectory { get { string directory = Path.Combine(Protocol.StorageDirectory, GetType().FullName); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); return directory; } } [JsonIgnore] public override string DisplayName { get { return "File"; } } [JsonIgnore] public override bool Clearable { get { return true; } } [JsonIgnore] public override string SizeDescription { get { string desc = null; try { desc = Math.Round(SensusServiceHelper.GetDirectorySizeMB(StorageDirectory), 1) + " MB"; } catch (Exception) { } return desc; } } public override void Start() { // file needs to be ready to accept data immediately, so set file path before calling base.Start WriteToNewPath(); base.Start(); } protected override Task<List<Datum>> CommitAsync(IEnumerable<Datum> data, CancellationToken cancellationToken) { return Task.Run(async () => { List<Datum> committedData = new List<Datum>(); lock (_storageDirectoryLocker) { try { using (StreamWriter file = new StreamWriter(_path, true)) { foreach (Datum datum in data) { if (cancellationToken.IsCancellationRequested) break; // get JSON for datum string datumJSON = null; try { datumJSON = datum.GetJSON(Protocol.JsonAnonymizer, false); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to get JSON for datum: " + ex.Message, LoggingLevel.Normal, GetType()); } // write JSON to file if (datumJSON != null) { try { file.WriteLine(datumJSON); committedData.Add(datum); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to write datum JSON to local file: " + ex.Message, LoggingLevel.Normal, GetType()); // something went wrong with file write...switch to a new file in the hope that it will work better try { WriteToNewPath(); SensusServiceHelper.Get().Logger.Log("Initialized new local file.", LoggingLevel.Normal, GetType()); } catch (Exception ex2) { SensusServiceHelper.Get().Logger.Log("Failed to initialize new file after failing to write the old one: " + ex2.Message, LoggingLevel.Normal, GetType()); } } } } } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to write data: " + ex.Message, LoggingLevel.Normal, GetType()); // something went wrong with file write...switch to a new file in the hope that it will work better try { WriteToNewPath(); SensusServiceHelper.Get().Logger.Log("Initialized new local file.", LoggingLevel.Normal, GetType()); } catch (Exception ex2) { SensusServiceHelper.Get().Logger.Log("Failed to initialize new file after failing to write the old one: " + ex2.Message, LoggingLevel.Normal, GetType()); } } // switch to a new path if the current one has grown too large if (SensusServiceHelper.GetFileSizeMB(_path) >= MAX_FILE_SIZE_MB) WriteToNewPath(); } await CommitToRemoteIfTooLargeAsync(cancellationToken); return committedData; }); } public override void CommitToRemote(CancellationToken cancellationToken) { lock (_storageDirectoryLocker) { string[] pathsToCommit = Directory.GetFiles(StorageDirectory); // get path for uncommitted data WriteToNewPath(); string uncommittedDataPath = _path; // reset _path for standard commits WriteToNewPath(); using (StreamWriter uncommittedDataFile = new StreamWriter(uncommittedDataPath)) { foreach (string pathToCommit in pathsToCommit) { if (cancellationToken.IsCancellationRequested) break; // wrap in try-catch to ensure that we process all files try { using (StreamReader fileToCommit = new StreamReader(pathToCommit)) { // commit data in small batches. all data will end up in the uncommitted file, in the batch object, or // in the remote data store. HashSet<Datum> batch = new HashSet<Datum>(); string datumJSON; while ((datumJSON = fileToCommit.ReadLine()) != null) { // if we have been canceled, dump the rest of the file into the uncommitted data file. if (cancellationToken.IsCancellationRequested) uncommittedDataFile.WriteLine(datumJSON); else { // wrap in try-catch to ensure that we process all lines try { batch.Add(Datum.FromJSON(datumJSON)); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to add datum to batch from JSON: " + ex.Message, LoggingLevel.Normal, GetType()); } if (batch.Count >= 50000) CommitAndReleaseBatchToRemote(batch, cancellationToken, uncommittedDataFile); } } // commit partial batch if (batch.Count > 0) { CommitAndReleaseBatchToRemote(batch, cancellationToken, uncommittedDataFile); } } // we've read all lines in the file and either committed them to the remote data store or written them // to the uncommitted data file. we can delete the current path. File.Delete(pathToCommit); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to commit: " + ex.Message, LoggingLevel.Normal, GetType()); } } } } } private void CommitAndReleaseBatchToRemote(HashSet<Datum> batch, CancellationToken cancellationToken, StreamWriter uncommittedDataFile) { if (!cancellationToken.IsCancellationRequested) CommitAndReleaseAsync(batch, Protocol.RemoteDataStore, cancellationToken).Wait(); // any leftover data should be dumped to the uncommitted file to maintain memory limits. the data will be committed next time. foreach (Datum datum in batch) uncommittedDataFile.WriteLine(datum.GetJSON(Protocol.JsonAnonymizer, false)); // all data were either commmitted or dumped to the uncommitted file. clear the batch. batch.Clear(); } protected override bool TooLarge() { lock (_storageDirectoryLocker) { return SensusServiceHelper.GetDirectorySizeMB(StorageDirectory) >= REMOTE_COMMIT_TRIGGER_STORAGE_DIRECTORY_SIZE_MB; } } protected override IEnumerable<Tuple<string, string>> GetDataLinesToWrite(CancellationToken cancellationToken, Action<string, double> progressCallback) { lock (_storageDirectoryLocker) { // "$type":"SensusService.Probes.Movement.AccelerometerDatum, SensusiOS" Regex datumTypeRegex = new Regex(@"""\$type""\s*:\s*""(?<type>[^,]+),"); double storageDirectoryMbToRead = SensusServiceHelper.GetDirectorySizeMB(StorageDirectory); double storageDirectoryMbRead = 0; string[] localPaths = Directory.GetFiles(StorageDirectory); for (int localPathNum = 0; localPathNum < localPaths.Length; ++localPathNum) { string localPath = localPaths[localPathNum]; using (StreamReader localFile = new StreamReader(localPath)) { long localFilePosition = 0; string line; while ((line = localFile.ReadLine()) != null) { cancellationToken.ThrowIfCancellationRequested(); string type = datumTypeRegex.Match(line).Groups["type"].Value; type = type.Substring(type.LastIndexOf('.') + 1); yield return new Tuple<string, string>(type, line); if (localFile.BaseStream.Position > localFilePosition) { int oldMbRead = (int)storageDirectoryMbRead; storageDirectoryMbRead += (localFile.BaseStream.Position - localFilePosition) / (1024d * 1024d); int newMbRead = (int)storageDirectoryMbRead; if (newMbRead > oldMbRead && progressCallback != null && storageDirectoryMbToRead > 0) progressCallback(null, storageDirectoryMbRead / storageDirectoryMbToRead); localFilePosition = localFile.BaseStream.Position; } } } } if (progressCallback != null) progressCallback(null, 1); } } private void WriteToNewPath() { lock (_storageDirectoryLocker) { _path = null; int pathNumber = 0; while (pathNumber++ < int.MaxValue && _path == null) { try { _path = Path.Combine(StorageDirectory, pathNumber.ToString()); } catch (Exception ex) { throw new SensusException("Failed to get path to local file: " + ex.Message, ex); } // create an empty file at the path if one does not exist if (File.Exists(_path)) _path = null; else File.Create(_path).Dispose(); } if (_path == null) throw new SensusException("Failed to find new path."); } } public override void Clear() { base.Clear(); lock (_storageDirectoryLocker) { if (Protocol != null) { foreach (string path in Directory.GetFiles(StorageDirectory)) { try { File.Delete(path); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to delete local file \"" + path + "\": " + ex.Message, LoggingLevel.Normal, GetType()); } } } } } public override void Reset() { base.Reset(); _path = null; } public override bool TestHealth(ref string error, ref string warning, ref string misc) { bool restart = base.TestHealth(ref error, ref warning, ref misc); lock (_storageDirectoryLocker) { int fileCount = Directory.GetFiles(StorageDirectory).Length; string name = GetType().Name; misc += "Number of files (" + name + "): " + fileCount + Environment.NewLine + "Average file size (MB) (" + name + "): " + Math.Round(SensusServiceHelper.GetDirectorySizeMB(StorageDirectory) / (float)fileCount, 2) + Environment.NewLine; } return restart; } } }
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 DogSimWeb.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Linq; using System.Linq.Expressions; using System.Collections; using System.Collections.Generic; namespace Shielded { /// <summary> /// A shielded red-black tree, for keeping sorted data. Each node is a /// Shielded struct, so parallel operations are possible. Multiple items /// may be added under the same key. 'Nc' stands for 'no count', which /// enables it to be a bit faster. /// </summary> public class ShieldedTreeNc<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>> { private enum Color : byte { Red = 0, Black } private struct Node { public Color Color; public TKey Key; public TValue Value; public Shielded<Node> Left; public Shielded<Node> Right; public Shielded<Node> Parent; } private void ClearLinks(Shielded<Node> node) { node.Modify((ref Node n) => n.Left = n.Right = n.Parent = null); } private readonly Shielded<Shielded<Node>> _head; private readonly IComparer<TKey> _comparer; private readonly object _owner; /// <summary> /// Initializes a new tree, which will use a given comparer, or using the .NET default /// comparer if none is specified. /// </summary> public ShieldedTreeNc(IComparer<TKey> comparer = null, object owner = null) { _owner = owner ?? this; _head = new Shielded<Shielded<Node>>(this); _comparer = comparer != null ? comparer : Comparer<TKey>.Default; } private Shielded<Node> FindInternal(TKey key) { return Shield.InTransaction(() => { var curr = _head.Value; int comparison; while (curr != null && (comparison = _comparer.Compare(curr.Value.Key, key)) != 0) { if (comparison > 0) curr = curr.Value.Left; else curr = curr.Value.Right; } return curr; }); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<KeyValuePair<TKey, TValue>>)this).GetEnumerator(); } /// <summary> /// Gets an enumerator for all the key-value pairs in the tree. /// </summary> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { Shield.AssertInTransaction(); Stack<Shielded<Node>> centerStack = new Stack<Shielded<Node>>(); var curr = _head.Value; while (curr != null) { while (curr.Value.Left != null) { centerStack.Push(curr); curr = curr.Value.Left; } yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value); while (curr.Value.Right == null && centerStack.Count > 0) { curr = centerStack.Pop(); yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value); } curr = curr.Value.Right; } } /// <summary> /// Gets an enuerable which enumerates the tree in descending key order. (Does not /// involve any copying, just as efficient as <see cref="GetEnumerator"/>.) /// </summary> public IEnumerable<KeyValuePair<TKey, TValue>> Descending { get { Shield.AssertInTransaction(); Stack<Shielded<Node>> centerStack = new Stack<Shielded<Node>>(); var curr = _head.Value; while (curr != null) { while (curr.Value.Right != null) { centerStack.Push(curr); curr = curr.Value.Right; } yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value); while (curr.Value.Left == null && centerStack.Count > 0) { curr = centerStack.Pop(); yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value); } curr = curr.Value.Left; } } } /// <summary> /// Enumerate all key-value pairs, whose keys are in the given range. The range /// is inclusive, both from and to are included in the result (if the tree contains /// those keys). The items are returned sorted. If from is greater than to, the /// enumerable will not return anything. For backwards enumeration you must explicitly /// use <see cref="RangeDescending"/>. /// </summary> public IEnumerable<KeyValuePair<TKey, TValue>> Range(TKey from, TKey to) { foreach (var n in RangeInternal(from, to)) yield return new KeyValuePair<TKey, TValue>(n.Value.Key, n.Value.Value); } /// <summary> /// Enumerates only over the nodes in the range. Borders included. /// </summary> private IEnumerable<Shielded<Node>> RangeInternal(TKey from, TKey to) { if (_comparer.Compare(from, to) > 0) yield break; Shield.AssertInTransaction(); Stack<Shielded<Node>> centerStack = new Stack<Shielded<Node>>(); var curr = _head.Value; while (curr != null) { while (curr.Value.Left != null && _comparer.Compare(curr.Value.Key, from) >= 0) { centerStack.Push(curr); curr = curr.Value.Left; } if (_comparer.Compare(curr.Value.Key, to) > 0) yield break; if (_comparer.Compare(curr.Value.Key, from) >= 0) yield return curr; while (curr.Value.Right == null && centerStack.Count > 0) { curr = centerStack.Pop(); if (_comparer.Compare(curr.Value.Key, to) <= 0) yield return curr; else yield break; } curr = curr.Value.Right; } } /// <summary> /// Enumerate all key-value pairs, whose keys are in the given range, but in descending /// key order. The range is inclusive, both from and to are included in the result (if /// the tree contains those keys). If from is smaller than to, the enumerable will not /// return anything. For forward enumeration you must explicitly use <see cref="Range"/>. /// </summary> public IEnumerable<KeyValuePair<TKey, TValue>> RangeDescending(TKey from, TKey to) { if (_comparer.Compare(from, to) < 0) yield break; Shield.AssertInTransaction(); Stack<Shielded<Node>> centerStack = new Stack<Shielded<Node>>(); var curr = _head.Value; while (curr != null) { while (curr.Value.Right != null && _comparer.Compare(curr.Value.Key, from) <= 0) { centerStack.Push(curr); curr = curr.Value.Right; } if (_comparer.Compare(curr.Value.Key, to) < 0) yield break; if (_comparer.Compare(curr.Value.Key, from) <= 0) yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value); while (curr.Value.Left == null && centerStack.Count > 0) { curr = centerStack.Pop(); if (_comparer.Compare(curr.Value.Key, to) >= 0) yield return new KeyValuePair<TKey, TValue>(curr.Value.Key, curr.Value.Value); else yield break; } curr = curr.Value.Left; } } private void InsertInternal(TKey key, TValue item) { Shield.AssertInTransaction(); Shielded<Node> parent = null; var targetLoc = _head.Value; int comparison = 0; while (targetLoc != null) { parent = targetLoc; if ((comparison = _comparer.Compare(targetLoc.Value.Key, key)) > 0) targetLoc = targetLoc.Value.Left; else targetLoc = targetLoc.Value.Right; } var shN = new Shielded<Node>(new Node() { //Color = Color.Red, // the default anyway. Parent = parent, Key = key, Value = item }, _owner); if (parent != null) { if (comparison > 0) parent.Modify((ref Node p) => p.Left = shN); else parent.Modify((ref Node p) => p.Right = shN); } else _head.Value = shN; InsertProcedure(shN); OnInsert(); } /// <summary> /// Called after inserting a new node. /// </summary> protected virtual void OnInsert() { } #region Wikipedia, insertion private Shielded<Node> Grandparent(Shielded<Node> n) { if (n != null && n.Value.Parent != null) return n.Value.Parent.Value.Parent; else return null; } private Shielded<Node> Uncle(Shielded<Node> n) { Shielded<Node> g = Grandparent(n); if (g == null) return null; if (n.Value.Parent == g.Value.Left) return g.Value.Right; else return g.Value.Left; } private void RotateLeft(Shielded<Node> p) { Shielded<Node> right = null; Shielded<Node> parent = null; p.Modify((ref Node pInner) => { right = pInner.Right; parent = pInner.Parent; pInner.Right = right.Value.Left; pInner.Parent = right; }); right.Modify((ref Node r) => { if (r.Left != null) r.Left.Modify((ref Node n) => n.Parent = p); r.Left = p; r.Parent = parent; }); if (parent != null) parent.Modify((ref Node n) => { if (n.Left == p) n.Left = right; else n.Right = right; }); else _head.Value = right; } private void RotateRight(Shielded<Node> p) { Shielded<Node> left = null; Shielded<Node> parent = null; p.Modify((ref Node pInner) => { left = pInner.Left; parent = pInner.Parent; pInner.Left = left.Value.Right; pInner.Parent = left; }); left.Modify((ref Node l) => { if (l.Right != null) l.Right.Modify((ref Node n) => n.Parent = p); l.Right = p; l.Parent = parent; }); if (parent != null) parent.Modify((ref Node n) => { if (n.Left == p) n.Left = left; else n.Right = left; }); else _head.Value = left; } private void InsertProcedure(Shielded<Node> n) { while (true) { if (n.Value.Parent == null) n.Modify((ref Node nInn) => nInn.Color = Color.Black); else if (n.Value.Parent.Value.Color == Color.Black) return; else { Shielded<Node> u = Uncle(n); Shielded<Node> g = Grandparent(n); if (u != null && u.Value.Color == Color.Red) { n.Value.Parent.Modify((ref Node p) => p.Color = Color.Black); u.Modify((ref Node uInn) => uInn.Color = Color.Black); g.Modify((ref Node gInn) => gInn.Color = Color.Red); n = g; continue; } else { if (n == n.Value.Parent.Value.Right && n.Value.Parent == g.Value.Left) { RotateLeft(n.Value.Parent); n = n.Value.Left; } else if (n == n.Value.Parent.Value.Left && n.Value.Parent == g.Value.Right) { RotateRight(n.Value.Parent); n = n.Value.Right; } n.Value.Parent.Modify((ref Node p) => p.Color = Color.Black); g.Modify((ref Node gInn) => gInn.Color = Color.Red); if (n == n.Value.Parent.Value.Left) RotateRight(g); else RotateLeft(g); } } break; } } #endregion /// <summary> /// Removes an item and returns it. Useful if you could have multiple items under the same key. /// </summary> public bool RemoveAndReturn(TKey key, out TValue val) { var node = RangeInternal(key, key).FirstOrDefault(); if (node != null) { val = node.Value.Value; RemoveInternal(node); return true; } else { val = default(TValue); return false; } } private void RemoveInternal(Shielded<Node> node) { Shield.AssertInTransaction(); // find the first follower in the right subtree (arbitrary choice..) Shielded<Node> follower; if (node.Value.Right == null) follower = node; else { follower = node.Value.Right; while (follower.Value.Left != null) follower = follower.Value.Left; // loosing the node value right now! node.Modify((ref Node n) => { var f = follower.Value; n.Key = f.Key; n.Value = f.Value; }); } DeleteOneChild(follower); OnRemove(); } /// <summary> /// Called after a node is removed from the tree. /// </summary> protected virtual void OnRemove() { } #region Wikipedia, removal Shielded<Node> Sibling(Shielded<Node> n) { var parent = n.Value.Parent.Value; if (n == parent.Left) return parent.Right; else return parent.Left; } void ReplaceNode(Shielded<Node> target, Shielded<Node> source) { var targetParent = target.Value.Parent; if (source != null) source.Modify((ref Node s) => s.Parent = targetParent); if (targetParent == null) _head.Value = source; else targetParent.Modify((ref Node p) => { if (p.Left == target) p.Left = source; else p.Right = source; }); ClearLinks(target); } void DeleteOneChild(Shielded<Node> node) { // node has at most one child! Shielded<Node> child = node.Value.Right == null ? node.Value.Left : node.Value.Right; bool deleted = false; if (child != null) { ReplaceNode(node, child); deleted = true; } if (node.Value.Color == Color.Black) { if (child != null && child.Value.Color == Color.Red) child.Modify((ref Node c) => c.Color = Color.Black); else { // since we don't represent null leaves as nodes, we must start // the process with the not yet removed parent in this case. if (!deleted) child = node; while (true) { // delete case 1 if (child.Value.Parent != null) { // delete case 2 Shielded<Node> s = Sibling(child); if (s.Value.Color == Color.Red) { child.Value.Parent.Modify((ref Node p) => p.Color = Color.Red); s.Modify((ref Node sInn) => sInn.Color = Color.Black); if (child == child.Value.Parent.Value.Left) RotateLeft(child.Value.Parent); else RotateRight(child.Value.Parent); s = Sibling(child); } // delete case 3 if ((child.Value.Parent.Value.Color == Color.Black) && (s.Value.Color == Color.Black) && (s.Value.Left == null || s.Value.Left.Value.Color == Color.Black) && (s.Value.Right == null || s.Value.Right.Value.Color == Color.Black)) { s.Modify((ref Node sInn) => sInn.Color = Color.Red); child = child.Value.Parent; continue; // back to 1 } else { // delete case 4 if ((child.Value.Parent.Value.Color == Color.Red) && (s.Value.Color == Color.Black) && (s.Value.Left == null || s.Value.Left.Value.Color == Color.Black) && (s.Value.Right == null || s.Value.Right.Value.Color == Color.Black)) { s.Modify((ref Node sInn) => sInn.Color = Color.Red); child.Value.Parent.Modify((ref Node p) => p.Color = Color.Black); } else { // delete case 5 if (s.Value.Color == Color.Black) { if ((child == child.Value.Parent.Value.Left) && (s.Value.Right == null || s.Value.Right.Value.Color == Color.Black) && (s.Value.Left != null && s.Value.Left.Value.Color == Color.Red)) { s.Modify((ref Node sInn) => { sInn.Color = Color.Red; sInn.Left.Modify((ref Node l) => l.Color = Color.Black); }); RotateRight(s); s = Sibling(child); } else if ((child == child.Value.Parent.Value.Right) && (s.Value.Left == null || s.Value.Left.Value.Color == Color.Black) && (s.Value.Right != null && s.Value.Right.Value.Color == Color.Red)) { s.Modify((ref Node sInn) => { sInn.Color = Color.Red; sInn.Right.Modify((ref Node r) => r.Color = Color.Black); }); RotateLeft(s); s = Sibling(child); } } // delete case 6 child.Value.Parent.Modify((ref Node p) => { var c = p.Color; s.Modify((ref Node sInn) => sInn.Color = c); p.Color = Color.Black; }); if (child == child.Value.Parent.Value.Left) { s.Value.Right.Modify((ref Node r) => r.Color = Color.Black); RotateLeft(child.Value.Parent); } else { s.Value.Left.Modify((ref Node l) => l.Color = Color.Black); RotateRight(child.Value.Parent); } } } } break; } } } if (!deleted) { // original node is still in the tree, and it still has no children. if (node.Value.Parent != null) node.Value.Parent.Modify((ref Node p) => { if (p.Left == node) p.Left = null; else p.Right = null; }); else _head.Value = null; ClearLinks(node); } } #endregion /// <summary> /// Clear this instance. Efficient, O(1). /// </summary> public virtual void Clear() { // ridiculously simple :) _head.Value = null; } /// <summary> /// Checks both the key and value, which may be useful due to the tree supporting multiple /// entries with the same key. /// </summary> public bool Contains(KeyValuePair<TKey, TValue> item) { var valueComp = EqualityComparer<TValue>.Default; return Shield.InTransaction(() => RangeInternal(item.Key, item.Key).Any(n => valueComp.Equals(n.Value.Value, item.Value))); } /// <summary> /// Copy the tree contents into an array. /// </summary> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { Shield.InTransaction(() => { foreach (var kvp in this) array[arrayIndex++] = kvp; }); } /// <summary> /// Remove the given key-value pair from the tree. Checks both the key and /// value, which may be useful due to the tree supporting multiple entries /// with the same key. /// </summary> public bool Remove(KeyValuePair<TKey, TValue> item) { var target = RangeInternal(item.Key, item.Key).FirstOrDefault(n => EqualityComparer<TValue>.Default.Equals(n.Value.Value, item.Value)); if (target == null) return false; RemoveInternal(target); return true; } /// <summary> /// Add the given key and value to the tree. Same key can be added multiple times /// into the tree! /// </summary> public void Add(TKey key, TValue value) { InsertInternal(key, value); } /// <summary> /// Check if the key is present in the tree. /// </summary> public bool ContainsKey(TKey key) { return FindInternal(key) != null; } /// <summary> /// Remove an item with the specified key. If you want to know what got removed, use /// RemoveAndReturn. /// </summary> public bool Remove(TKey key) { TValue val; return RemoveAndReturn(key, out val); } /// <summary> /// Try to get any one of the values stored under the given key. There may be multiple items /// under the same key! /// </summary> public bool TryGetValue(TKey key, out TValue value) { bool res = false; value = Shield.InTransaction(() => { var n = FindInternal(key); res = n != null; return res ? n.Value.Value : default(TValue); }); return res; } /// <summary> /// Gets or sets the item with the specified key. /// If there are many with the same key, acts on the first one it finds! /// </summary> public TValue this[TKey key] { get { return Shield.InTransaction(() => { var n = FindInternal(key); if (n == null) throw new KeyNotFoundException(); return n.Value.Value; }); } set { Shield.AssertInTransaction(); // replaces the first occurrence... var n = FindInternal(key); if (n == null) Add(key, value); else n.Modify((ref Node nInner) => nInner.Value = value); } } /// <summary> /// Get a collection of the keys in the tree. Works out of transaction. /// The result is a copy, it does not get updated with later changes. /// Count will be equal to the tree count, i.e. if there are multiple /// entries with the same key, that key will be in this collection /// multiple times. /// </summary> public ICollection<TKey> Keys { get { return Shield.InTransaction( () => ((IEnumerable<KeyValuePair<TKey, TValue>>)this) .Select(kvp => kvp.Key) .ToList()); } } /// <summary> /// Get a collection of the values in the tree. Works out of transaction. /// The result is a copy, it does not get updated with later changes. /// </summary> public ICollection<TValue> Values { get { return Shield.InTransaction( () => ((IEnumerable<KeyValuePair<TKey, TValue>>)this) .Select(kvp => kvp.Value) .ToList()); } } } }
using System; using NUnit.Framework; using static PeanutButter.RandomGenerators.RandomValueGen; using NExpect; using static NExpect.Expectations; namespace PeanutButter.Utils.Tests { [TestFixture] public class TestBuilder { [TestFixture] public class FailureToBuild { [Test] public void ShouldThrowNotImplementedIfAttemptingToBuildInterface() { // Arrange // Act Expect(() => FooInterfaceBuilder.Create().Build()) .To.Throw<NotImplementedException>() .With.Message.Containing("override ConstructEntity"); // Assert } public interface IFoo { } public class FooInterfaceBuilder : Builder<FooInterfaceBuilder, IFoo> { } [Test] public void ShouldThrowNotImplementedIfEntityRequiresConstructorParams() { // Arrange // Act Expect(() => FooConcreteBuilder.Create().Build()) .To.Throw<NotImplementedException>() .With.Message.Containing("override ConstructEntity"); // Assert } public class Foo { public string Name { get; } public Foo(string name) { Name = name; } } public class FooConcreteBuilder : Builder<FooConcreteBuilder, Foo> { } } [TestFixture] public class NormalOperations { [Test] public void ShouldBeAbleToConstructDefaultEntity() { // Arrange // Act var result = SomeEntityBuilder.Create().Build(); // Assert Expect(result).Not.To.Be.Null(); Expect(result.Name).To.Equal(default); Expect(result.Id).To.Equal(default); } [Test] public void ShouldApplyTransforms() { // Arrange var name = GetRandomString(1); var id = GetRandomInt(1); // Act var result = SomeEntityBuilder.Create() .WithProp(o => o.Name = name) .WithProp(o => o.Id = id) .Build(); // Assert Expect(result).Not.To.Be.Null(); Expect(result.Id).To.Equal(id); Expect(result.Name).To.Equal(name); } public class SomeEntity { public int Id { get; set; } public string Name { get; set; } } public class SomeEntityBuilder : Builder<SomeEntityBuilder, SomeEntity> { } } [TestFixture] public class Overrides { [Test] public void ShouldBeAbleToOverrideEntityConstruction() { // Arrange // Act var result1 = SomeEntityBuilderOverridingConstruction.Create() .WithProp(o => o.Name = GetRandomString()) .Build(); var result2 = SomeEntityBuilderOverridingConstruction.Create() .WithProp(o => o.Name = GetRandomString()) .Build(); // Assert Expect(result1).Not.To.Be.Null(); Expect(result2).Not.To.Be.Null(); Expect(result1.Id).To.Equal(1); Expect(result2.Id).To.Equal(2); } public class SomeEntity { public int Id { get; set; } public string Name { get; set; } public SomeEntity( int id) { Id = id; } } public class SomeEntityBuilderOverridingConstruction : Builder<SomeEntityBuilderOverridingConstruction, SomeEntity> { private static int _id = 0; protected override SomeEntity ConstructEntity() { return new SomeEntity(++_id); } } [Test] public void ShouldBeAbleToOverrideBuilding() { // Arrange // Act var result1 = SomeEntityBuilderOverridingBuild.Create() .WithProp(o => o.Name = GetRandomString()) .Build(); var result2 = SomeEntityBuilderOverridingBuild.Create() .WithProp(o => o.Name = GetRandomString()) .Build(); // Assert Expect(result1).Not.To.Be.Null(); Expect(result2).Not.To.Be.Null(); Expect(result1.Id).To.Equal(1); Expect(result2.Id).To.Equal(2); } public class SomeEntityBuilderOverridingBuild : Builder<SomeEntityBuilderOverridingBuild, SomeEntity> { private static int _id = 0; protected override SomeEntity ConstructEntity() { return new SomeEntity(0); } public override SomeEntity Build() { var result = base.Build(); result.Id = ++_id; return result; } } } [TestFixture] public class OperatingOnStructs { [Test] public void ShouldBeAbleToConstructTheStructType() { // Arrange var id = GetRandomInt(1); var name = GetRandomString(1); // Act var result = FooBuilder.Create() .WithProp((ref Foo o) => o.Id = id) .WithProp((ref Foo o) => o.Name = name) .Build(); // Assert Expect(result.Id).To.Equal(id); Expect(result.Name).To.Equal(name); } public struct Foo { public int Id; public string Name; } public class FooBuilder : Builder<FooBuilder, Foo> { } } [TestFixture] public class BuildTimeTransforms { [Test] public void ShouldApplyBuildTimeTransform() { // Arrange // Act var result = FooBuilder.Create() .WithId(42) .Build(); // Assert Expect(result.Id).To.Equal(42); Expect(result.Name).To.Equal("Id: 42"); } [Test] public void ShouldNotKeepBuildTimeTransformsBetweenInstanceUsages() { // Arrange var builder = FooBuilder.Create(); // Act builder .WithId(13) .Build(); builder.Depth = 0; Expect(() => builder.Build()) .Not.To.Throw(); // Assert } public class Foo { public int Id { get; set; } public string Name { get; set; } } public class FooBuilder : Builder<FooBuilder, Foo> { public int Depth = 0; public FooBuilder WithId(int id) { return WithProp(o => { o.Id = id; WithProp(o2 => { if (Depth++ > 1) { throw new InvalidOperationException("Have already set id"); } o2.Name = $"Id: {id}"; }); Depth++; }); } } [Test] public void ShouldNotStackOverflowOnBuildTimeTransforms() { // Arrange // Act Expect(() => ReEntrantBuilder.Create() .WithId(12) .Build() ).To.Throw<InvalidOperationException>() .With.Message.Containing("re-entrant"); // Assert } public class ReEntrantBuilder : Builder<ReEntrantBuilder, Foo> { public ReEntrantBuilder WithId(int id) { return WithProp(o => { WithId(id); }); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Contacts.Data.SqlServer.Models; using Contacts.Domain.Interfaces; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Contact = Contacts.Domain.Models.Contact; namespace Contacts.Data.SqlServer { [ExcludeFromCodeCoverage] public class SqlServerDataStore: IContactDataStore { private readonly ContactContext _contactContext; private readonly Mapper _mapper; public SqlServerDataStore(IConfiguration configuration) { _contactContext = new ContactContext(configuration); var mapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfile<ContactProfile>(); }); _mapper = new Mapper(mapperConfiguration); } public Contact GetContact(int contactId) { var dbContact = _contactContext.Contacts .FirstOrDefault(c => c.ContactId == contactId); var contact = _mapper.Map<Contact>(dbContact); return contact; } public async Task<Contact> GetContactAsync(int contactId) { var dbContact = await _contactContext.Contacts .FirstOrDefaultAsync(c => c.ContactId == contactId); var contact = _mapper.Map<Contact>(dbContact); return contact; } public List<Contact> GetContacts() { var contacts = _contactContext.Contacts.ToList(); return _mapper.Map<List<Contact>>(contacts); } public async Task<List<Contact>> GetContactsAsync() { var contacts = await _contactContext.Contacts.ToListAsync(); return _mapper.Map<List<Contact>>(contacts); } public List<Contact> GetContacts(string firstName, string lastName) { ValidationForGetContacts(firstName, lastName); var dbContact = _contactContext.Contacts .Where(contact => contact.LastName == lastName && contact.FirstName == firstName).ToList(); return _mapper.Map<List<Contact>>(dbContact); } public async Task<List<Contact>> GetContactsAsync(string firstName, string lastName) { ValidationForGetContacts(firstName, lastName); var dbContact = await _contactContext.Contacts .Where(contact => contact.LastName == lastName && contact.FirstName == firstName).ToListAsync(); return _mapper.Map<List<Contact>>(dbContact); } private static void ValidationForGetContacts(string firstName, string lastName) { if (string.IsNullOrEmpty(lastName)) { throw new ArgumentNullException(nameof(lastName), "LastName is a required field"); } if (string.IsNullOrEmpty(firstName)) { throw new ArgumentNullException(nameof(firstName), "FirstName is a required field"); } } public Contact SaveContact(Contact contact) { var dbContact = _mapper.Map<SqlServer.Models.Contact>(contact); _contactContext.Entry(dbContact).State = dbContact.ContactId == 0 ? EntityState.Added : EntityState.Modified; var wasSaved = _contactContext.SaveChanges() != 0; if (wasSaved) { contact.ContactId = dbContact.ContactId; return contact; } return null; } public async Task<Contact> SaveContactAsync(Contact contact) { var dbContact = _mapper.Map<SqlServer.Models.Contact>(contact); _contactContext.Entry(dbContact).State = dbContact.ContactId == 0 ? EntityState.Added : EntityState.Modified; var wasSaved = await _contactContext.SaveChangesAsync() != 0; if (wasSaved) { contact.ContactId = dbContact.ContactId; return contact; } return null; } public bool DeleteContact(int contactId) { var contact = _contactContext.Contacts .Include(c => c.Addresses) .Include(c => c.Phones) .FirstOrDefault(c => c.ContactId == contactId); if (contact == null) { return false; } _contactContext.Contacts.Remove(contact); foreach (var contactAddress in contact.Addresses) { _contactContext.Addresses.Remove(contactAddress); } foreach (var contactPhone in contact.Phones) { _contactContext.Phones.Remove(contactPhone); } return _contactContext.SaveChanges() != 0; } public async Task<bool> DeleteContactAsync(int contactId) { var contact = await _contactContext.Contacts .Include(c => c.Addresses) .Include(c => c.Phones) .FirstOrDefaultAsync(c => c.ContactId == contactId); if (contact == null) { return false; } _contactContext.Contacts.Remove(contact); foreach (var contactAddress in contact.Addresses) { _contactContext.Addresses.Remove(contactAddress); } foreach (var contactPhone in contact.Phones) { _contactContext.Phones.Remove(contactPhone); } return await _contactContext.SaveChangesAsync() != 0; } public bool DeleteContact(Contact contact) { return ValidateDeleteContact(contact) && DeleteContact(contact.ContactId); } public async Task<bool> DeleteContactAsync(Contact contact) { return ValidateDeleteContact(contact) && await DeleteContactAsync(contact.ContactId); } private static bool ValidateDeleteContact(Contact contact) { return contact != null; } public List<Domain.Models.Phone> GetContactPhones(int contactId) { var dbPhones = _contactContext.Phones .Where(p => p.Contact.ContactId == contactId).ToList(); var phones = _mapper.Map<List<Domain.Models.Phone>>(dbPhones); return phones; } public async Task<List<Domain.Models.Phone>> GetContactPhonesAsync(int contactId) { var dbPhones = await _contactContext.Phones .Where(p => p.Contact.ContactId == contactId).ToListAsync(); var phones = _mapper.Map<List<Domain.Models.Phone>>(dbPhones); return phones; } public Domain.Models.Phone GetContactPhone(int contactId, int phoneId) { var dbPhone = _contactContext.Phones .FirstOrDefault(p => p.Contact.ContactId == contactId && p.PhoneId == phoneId); var phone = _mapper.Map<Domain.Models.Phone>(dbPhone); return phone; } public async Task<Domain.Models.Phone> GetContactPhoneAsync(int contactId, int phoneId) { var dbPhone = await _contactContext.Phones .FirstOrDefaultAsync(p => p.Contact.ContactId == contactId && p.PhoneId == phoneId); var phone = _mapper.Map<Domain.Models.Phone>(dbPhone); return phone; } public List<Domain.Models.Address> GetContactAddresses(int contactId) { var dbAddresses = _contactContext.Addresses .Where(a => a.Contact.ContactId == contactId).ToList(); var addresses = _mapper.Map<List<Domain.Models.Address>>(dbAddresses); return addresses; } public async Task<List<Domain.Models.Address>> GetContactAddressesAsync(int contactId) { var dbAddresses = await _contactContext.Addresses .Where(a => a.Contact.ContactId == contactId).ToListAsync(); var addresses = _mapper.Map<List<Domain.Models.Address>>(dbAddresses); return addresses; } public Domain.Models.Address GetContactAddress(int contactId, int addressId) { var dbAddress = _contactContext.Addresses .FirstOrDefault(a => a.Contact.ContactId == contactId && a.AddressId == addressId); var address = _mapper.Map<Domain.Models.Address>(dbAddress); return address; } public async Task<Domain.Models.Address> GetContactAddressAsync(int contactId, int addressId) { var dbAddress = await _contactContext.Addresses .FirstOrDefaultAsync(a => a.Contact.ContactId == contactId && a.AddressId == addressId); var address = _mapper.Map<Domain.Models.Address>(dbAddress); return address; } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace WeifenLuo.WinFormsUI.Docking { using WeifenLuo.WinFormsUI.ThemeVS2012Light; /// <summary> /// Visual Studio 2013 Light theme. /// </summary> public class VS2013BlueTheme : ThemeBase { /// <summary> /// Applies the specified theme to the dock panel. /// </summary> /// <param name="dockPanel">The dock panel.</param> public override void Apply(DockPanel dockPanel) { if (dockPanel == null) { throw new NullReferenceException("dockPanel"); } Measures.SplitterSize = 6; dockPanel.Extender.DockPaneCaptionFactory = new VS2013BlueDockPaneCaptionFactory(); dockPanel.Extender.AutoHideStripFactory = new VS2013BlueAutoHideStripFactory(); dockPanel.Extender.AutoHideWindowFactory = new VS2013BlueAutoHideWindowFactory(); dockPanel.Extender.DockPaneStripFactory = new VS2013BlueDockPaneStripFactory(); dockPanel.Extender.DockPaneSplitterControlFactory = new VS2013BlueDockPaneSplitterControlFactory(); dockPanel.Extender.DockWindowSplitterControlFactory = new VS2013BlueDockWindowSplitterControlFactory(); dockPanel.Extender.DockWindowFactory = new VS2013BlueDockWindowFactory(); dockPanel.Extender.PaneIndicatorFactory = new VS2013BluePaneIndicatorFactory(); dockPanel.Extender.PanelIndicatorFactory = new VS2013BluePanelIndicatorFactory(); dockPanel.Extender.DockOutlineFactory = new VS2013BlueDockOutlineFactory(); dockPanel.Skin = CreateVisualStudio2013Blue(); } private class VS2013BlueDockOutlineFactory : DockPanelExtender.IDockOutlineFactory { public DockOutlineBase CreateDockOutline() { return new VS2013BlueDockOutline(); } private class VS2013BlueDockOutline : DockOutlineBase { public VS2013BlueDockOutline() { m_dragForm = new DragForm(); SetDragForm(Rectangle.Empty); DragForm.BackColor = Color.FromArgb(0xff, 91, 173, 255); DragForm.Opacity = 0.5; DragForm.Show(false); } DragForm m_dragForm; private DragForm DragForm { get { return m_dragForm; } } protected override void OnShow() { CalculateRegion(); } protected override void OnClose() { DragForm.Close(); } private void CalculateRegion() { if (SameAsOldValue) return; if (!FloatWindowBounds.IsEmpty) SetOutline(FloatWindowBounds); else if (DockTo is DockPanel) SetOutline(DockTo as DockPanel, Dock, (ContentIndex != 0)); else if (DockTo is DockPane) SetOutline(DockTo as DockPane, Dock, ContentIndex); else SetOutline(); } private void SetOutline() { SetDragForm(Rectangle.Empty); } private void SetOutline(Rectangle floatWindowBounds) { SetDragForm(floatWindowBounds); } private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge) { Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); if (dock == DockStyle.Top) { int height = dockPanel.GetDockWindowSize(DockState.DockTop); rect = new Rectangle(rect.X, rect.Y, rect.Width, height); } else if (dock == DockStyle.Bottom) { int height = dockPanel.GetDockWindowSize(DockState.DockBottom); rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height); } else if (dock == DockStyle.Left) { int width = dockPanel.GetDockWindowSize(DockState.DockLeft); rect = new Rectangle(rect.X, rect.Y, width, rect.Height); } else if (dock == DockStyle.Right) { int width = dockPanel.GetDockWindowSize(DockState.DockRight); rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height); } else if (dock == DockStyle.Fill) { rect = dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); } SetDragForm(rect); } private void SetOutline(DockPane pane, DockStyle dock, int contentIndex) { if (dock != DockStyle.Fill) { Rectangle rect = pane.DisplayingRectangle; if (dock == DockStyle.Right) rect.X += rect.Width / 2; if (dock == DockStyle.Bottom) rect.Y += rect.Height / 2; if (dock == DockStyle.Left || dock == DockStyle.Right) rect.Width -= rect.Width / 2; if (dock == DockStyle.Top || dock == DockStyle.Bottom) rect.Height -= rect.Height / 2; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else if (contentIndex == -1) { Rectangle rect = pane.DisplayingRectangle; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else { using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex)) { RectangleF rectF = path.GetBounds(); Rectangle rect = new Rectangle((int)rectF.X, (int)rectF.Y, (int)rectF.Width, (int)rectF.Height); using (Matrix matrix = new Matrix(rect, new Point[] { new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height) })) { path.Transform(matrix); } Region region = new Region(path); SetDragForm(rect, region); } } } private void SetDragForm(Rectangle rect) { DragForm.Bounds = rect; if (rect == Rectangle.Empty) { if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = new Region(Rectangle.Empty); } else if (DragForm.Region != null) { DragForm.Region.Dispose(); DragForm.Region = null; } } private void SetDragForm(Rectangle rect, Region region) { DragForm.Bounds = rect; if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = region; } } } private class VS2013BluePanelIndicatorFactory : DockPanelExtender.IPanelIndicatorFactory { public DockPanel.IPanelIndicator CreatePanelIndicator(DockStyle style) { return new VS2013BluePanelIndicator(style); } private class VS2013BluePanelIndicator : PictureBox, DockPanel.IPanelIndicator { private static Image _imagePanelLeft = Resources.DockIndicator_PanelLeft; private static Image _imagePanelRight = Resources.DockIndicator_PanelRight; private static Image _imagePanelTop = Resources.DockIndicator_PanelTop; private static Image _imagePanelBottom = Resources.DockIndicator_PanelBottom; private static Image _imagePanelFill = Resources.DockIndicator_PanelFill; private static Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft; private static Image _imagePanelRightActive = Resources.DockIndicator_PanelRight; private static Image _imagePanelTopActive = Resources.DockIndicator_PanelTop; private static Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom; private static Image _imagePanelFillActive = Resources.DockIndicator_PanelFill; public VS2013BluePanelIndicator(DockStyle dockStyle) { m_dockStyle = dockStyle; SizeMode = PictureBoxSizeMode.AutoSize; Image = ImageInactive; } private DockStyle m_dockStyle; private DockStyle DockStyle { get { return m_dockStyle; } } private DockStyle m_status; public DockStyle Status { get { return m_status; } set { if (value != DockStyle && value != DockStyle.None) throw new InvalidEnumArgumentException(); if (m_status == value) return; m_status = value; IsActivated = (m_status != DockStyle.None); } } private Image ImageInactive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeft; else if (DockStyle == DockStyle.Right) return _imagePanelRight; else if (DockStyle == DockStyle.Top) return _imagePanelTop; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottom; else if (DockStyle == DockStyle.Fill) return _imagePanelFill; else return null; } } private Image ImageActive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeftActive; else if (DockStyle == DockStyle.Right) return _imagePanelRightActive; else if (DockStyle == DockStyle.Top) return _imagePanelTopActive; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottomActive; else if (DockStyle == DockStyle.Fill) return _imagePanelFillActive; else return null; } } private bool m_isActivated = false; private bool IsActivated { get { return m_isActivated; } set { m_isActivated = value; Image = IsActivated ? ImageActive : ImageInactive; } } public DockStyle HitTest(Point pt) { return this.Visible && ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None; } } } private class VS2013BluePaneIndicatorFactory : DockPanelExtender.IPaneIndicatorFactory { public DockPanel.IPaneIndicator CreatePaneIndicator() { return new VS2013BluePaneIndicator(); } private class VS2013BluePaneIndicator : PictureBox, DockPanel.IPaneIndicator { private static Bitmap _bitmapPaneDiamond = Resources.Dockindicator_PaneDiamond; private static Bitmap _bitmapPaneDiamondLeft = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondRight = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondTop = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondBottom = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondFill = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondHotSpot = Resources.Dockindicator_PaneDiamond_Hotspot; private static Bitmap _bitmapPaneDiamondHotSpotIndex = Resources.DockIndicator_PaneDiamond_HotspotIndex; private static DockPanel.HotSpotIndex[] _hotSpots = new[] { new DockPanel.HotSpotIndex(1, 0, DockStyle.Top), new DockPanel.HotSpotIndex(0, 1, DockStyle.Left), new DockPanel.HotSpotIndex(1, 1, DockStyle.Fill), new DockPanel.HotSpotIndex(2, 1, DockStyle.Right), new DockPanel.HotSpotIndex(1, 2, DockStyle.Bottom) }; private GraphicsPath _displayingGraphicsPath = DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond); public VS2013BluePaneIndicator() { SizeMode = PictureBoxSizeMode.AutoSize; Image = _bitmapPaneDiamond; Region = new Region(DisplayingGraphicsPath); } public GraphicsPath DisplayingGraphicsPath { get { return _displayingGraphicsPath; } } public DockStyle HitTest(Point pt) { if (!Visible) return DockStyle.None; pt = PointToClient(pt); if (!ClientRectangle.Contains(pt)) return DockStyle.None; for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++) { if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y)) return _hotSpots[i].DockStyle; } return DockStyle.None; } private DockStyle m_status = DockStyle.None; public DockStyle Status { get { return m_status; } set { m_status = value; if (m_status == DockStyle.None) Image = _bitmapPaneDiamond; else if (m_status == DockStyle.Left) Image = _bitmapPaneDiamondLeft; else if (m_status == DockStyle.Right) Image = _bitmapPaneDiamondRight; else if (m_status == DockStyle.Top) Image = _bitmapPaneDiamondTop; else if (m_status == DockStyle.Bottom) Image = _bitmapPaneDiamondBottom; else if (m_status == DockStyle.Fill) Image = _bitmapPaneDiamondFill; } } } } private class VS2013BlueAutoHideWindowFactory : DockPanelExtender.IAutoHideWindowFactory { public DockPanel.AutoHideWindowControl CreateAutoHideWindow(DockPanel panel) { return new VS2012LightAutoHideWindowControl(panel); } } private class VS2013BlueDockPaneSplitterControlFactory : DockPanelExtender.IDockPaneSplitterControlFactory { public DockPane.SplitterControlBase CreateSplitterControl(DockPane pane) { return new VS2013BlueSplitterControl(pane); } } private class VS2013BlueDockWindowSplitterControlFactory : DockPanelExtender.IDockWindowSplitterControlFactory { public SplitterBase CreateSplitterControl() { return new VS2013BlueDockWindowSplitterControl(); } } private class VS2013BlueDockPaneStripFactory : DockPanelExtender.IDockPaneStripFactory { public DockPaneStripBase CreateDockPaneStrip(DockPane pane) { return new VS2013BlueDockPaneStrip(pane); } } private class VS2013BlueAutoHideStripFactory : DockPanelExtender.IAutoHideStripFactory { public AutoHideStripBase CreateAutoHideStrip(DockPanel panel) { return new VS2012LightAutoHideStrip(panel); } } private class VS2013BlueDockPaneCaptionFactory : DockPanelExtender.IDockPaneCaptionFactory { public DockPaneCaptionBase CreateDockPaneCaption(DockPane pane) { return new VS2012LightDockPaneCaption(pane); } } private class VS2013BlueDockWindowFactory : DockPanelExtender.IDockWindowFactory { public DockWindow CreateDockWindow(DockPanel dockPanel, DockState dockState) { return new VS2012LightDockWindow(dockPanel, dockState); } } public static DockPanelSkin CreateVisualStudio2013Blue() { var border = Color.FromArgb(0xFF, 41, 57, 85); var specialyellow = Color.FromArgb(0xFF, 255, 242, 157); var hover = Color.FromArgb(0xFF, 155, 167, 183); var activeTab = specialyellow; var mouseHoverTab = Color.FromArgb(0xFF, 91, 113, 153); var inactiveTab = Color.FromArgb(0xFF, 54, 78, 111); var lostFocusTab = Color.FromArgb(0xFF, 77, 96, 130); var skin = new DockPanelSkin(); skin.AutoHideStripSkin.DockStripGradient.StartColor = hover; skin.AutoHideStripSkin.DockStripGradient.EndColor = inactiveTab; skin.AutoHideStripSkin.TabGradient.TextColor = Color.White; skin.AutoHideStripSkin.DockStripBackground.StartColor = border; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor = border; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor = border; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor = activeTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor = lostFocusTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor = Color.Black; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor = inactiveTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor = mouseHoverTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor = inactiveTab; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor = inactiveTab; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor = Color.Black; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor = border; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor = border; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor = specialyellow; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor = specialyellow; //skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor = Color.Black; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor = lostFocusTab; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor = lostFocusTab; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.HoverTabGradient.TextColor = Color.White; skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.StartColor = mouseHoverTab; skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.EndColor = mouseHoverTab; skin.DockPaneStripSkin.DocumentGradient.HoverTabGradient.TextColor = Color.White; return skin; } internal class VS2013BlueDockWindowSplitterControl : SplitterBase { private SolidBrush _brush; protected override int SplitterSize { get { return Measures.SplitterSize; } } protected override void StartDrag() { DockWindow window = Parent as DockWindow; if (window == null) return; window.DockPanel.BeginDrag(window, window.RectangleToScreen(Bounds)); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Rectangle rect = ClientRectangle; if (rect.Width <= 0 || rect.Height <= 0) return; DockWindow window = Parent as DockWindow; if (window == null) return; if (this._brush == null) { _brush = new SolidBrush(window.DockPanel.Skin.AutoHideStripSkin.DockStripBackground.StartColor); } switch (Dock) { case DockStyle.Right: case DockStyle.Left: { e.Graphics.FillRectangle(_brush, rect.X, rect.Y, Measures.SplitterSize, rect.Height); } break; case DockStyle.Bottom: case DockStyle.Top: { e.Graphics.FillRectangle(_brush, rect.X, rect.Y, rect.Width, Measures.SplitterSize); } 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.ComponentModel; using System.Diagnostics; using System.Drawing.Internal; using System.Runtime.InteropServices; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing { public sealed partial class Font { ///<summary> /// Creates the GDI+ native font object. ///</summary> private void CreateNativeFont() { Debug.Assert(_nativeFont == IntPtr.Zero, "nativeFont already initialized, this will generate a handle leak."); Debug.Assert(_fontFamily != null, "fontFamily not initialized."); // Note: GDI+ creates singleton font family objects (from the corresponding font file) and reference count them so // if creating the font object from an external FontFamily, this object's FontFamily will share the same native object. int status = Gdip.GdipCreateFont( new HandleRef(this, _fontFamily.NativeFamily), _fontSize, _fontStyle, _fontUnit, out _nativeFont); // Special case this common error message to give more information if (status == Gdip.FontStyleNotFound) { throw new ArgumentException(SR.Format(SR.GdiplusFontStyleNotFound, _fontFamily.Name, _fontStyle.ToString())); } else if (status != Gdip.Ok) { throw Gdip.StatusException(status); } } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class from the specified existing <see cref='Font'/> /// and <see cref='FontStyle'/>. /// </summary> public Font(Font prototype, FontStyle newStyle) { // Copy over the originalFontName because it won't get initialized _originalFontName = prototype.OriginalFontName; Initialize(prototype.FontFamily, prototype.Size, newStyle, prototype.Unit, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit) { Initialize(family, emSize, style, unit, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet) { Initialize(family, emSize, style, unit, gdiCharSet, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { Initialize(family, emSize, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet) { Initialize(familyName, emSize, style, unit, gdiCharSet, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0) { throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, nameof(emSize), emSize, 0, "System.Single.MaxValue"), nameof(emSize)); } Initialize(familyName, emSize, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style) { Initialize(family, emSize, style, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, GraphicsUnit unit) { Initialize(family, emSize, FontStyle.Regular, unit, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize) { Initialize(family, emSize, FontStyle.Regular, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit) { Initialize(familyName, emSize, style, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style) { Initialize(familyName, emSize, style, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, GraphicsUnit unit) { Initialize(familyName, emSize, FontStyle.Regular, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize) { Initialize(familyName, emSize, FontStyle.Regular, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Constructor to initialize fields from an existing native GDI+ object reference. Used by ToLogFont. /// </summary> private Font(IntPtr nativeFont, byte gdiCharSet, bool gdiVerticalFont) { Debug.Assert(_nativeFont == IntPtr.Zero, "GDI+ native font already initialized, this will generate a handle leak"); Debug.Assert(nativeFont != IntPtr.Zero, "nativeFont is null"); _nativeFont = nativeFont; Gdip.CheckStatus(Gdip.GdipGetFontUnit(new HandleRef(this, nativeFont), out GraphicsUnit unit)); Gdip.CheckStatus(Gdip.GdipGetFontSize(new HandleRef(this, nativeFont), out float size)); Gdip.CheckStatus(Gdip.GdipGetFontStyle(new HandleRef(this, nativeFont), out FontStyle style)); Gdip.CheckStatus(Gdip.GdipGetFamily(new HandleRef(this, nativeFont), out IntPtr nativeFamily)); SetFontFamily(new FontFamily(nativeFamily)); Initialize(_fontFamily, size, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes this object's fields. /// </summary> private void Initialize(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { _originalFontName = familyName; SetFontFamily(new FontFamily(StripVerticalName(familyName), createDefaultOnFail: true)); Initialize(_fontFamily, emSize, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes this object's fields. /// </summary> private void Initialize(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { if (family == null) { throw new ArgumentNullException(nameof(family)); } if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0) { throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, nameof(emSize), emSize, 0, "System.Single.MaxValue"), nameof(emSize)); } int status; _fontSize = emSize; _fontStyle = style; _fontUnit = unit; _gdiCharSet = gdiCharSet; _gdiVerticalFont = gdiVerticalFont; if (_fontFamily == null) { // GDI+ FontFamily is a singleton object. SetFontFamily(new FontFamily(family.NativeFamily)); } if (_nativeFont == IntPtr.Zero) { CreateNativeFont(); } // Get actual size. status = Gdip.GdipGetFontSize(new HandleRef(this, _nativeFont), out _fontSize); Gdip.CheckStatus(status); } /// <summary> /// Creates a <see cref='Font'/> from the specified Windows handle. /// </summary> public static Font FromHfont(IntPtr hfont) { var logFont = new SafeNativeMethods.LOGFONT(); SafeNativeMethods.GetObject(new HandleRef(null, hfont), ref logFont); using (ScreenDC dc = ScreenDC.Create()) { return FromLogFontInternal(ref logFont, dc); } } /// <summary> /// Creates a <see cref="Font"/> from the given LOGFONT using the screen device context. /// </summary> /// <param name="lf">A boxed LOGFONT.</param> /// <returns>The newly created <see cref="Font"/>.</returns> public static Font FromLogFont(object lf) { using (ScreenDC dc = ScreenDC.Create()) { return FromLogFont(lf, dc); } } internal static Font FromLogFont(ref SafeNativeMethods.LOGFONT logFont) { using (ScreenDC dc = ScreenDC.Create()) { return FromLogFont(logFont, dc); } } internal static Font FromLogFontInternal(ref SafeNativeMethods.LOGFONT logFont, IntPtr hdc) { int status = Gdip.GdipCreateFontFromLogfontW(hdc, ref logFont, out IntPtr font); // Special case this incredibly common error message to give more information if (status == Gdip.NotTrueTypeFont) { throw new ArgumentException(SR.GdiplusNotTrueTypeFont_NoName); } else if (status != Gdip.Ok) { throw Gdip.StatusException(status); } // GDI+ returns font = 0 even though the status is Ok. if (font == IntPtr.Zero) { throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont, logFont.ToString())); } bool gdiVerticalFont = logFont.lfFaceName[0] == '@'; return new Font(font, logFont.lfCharSet, gdiVerticalFont); } /// <summary> /// Creates a <see cref="Font"/> from the given LOGFONT using the given device context. /// </summary> /// <param name="lf">A boxed LOGFONT.</param> /// <param name="hdc">Handle to a device context (HDC).</param> /// <returns>The newly created <see cref="Font"/>.</returns> public static unsafe Font FromLogFont(object lf, IntPtr hdc) { if (lf == null) { throw new ArgumentNullException(nameof(lf)); } if (lf is SafeNativeMethods.LOGFONT logFont) { // A boxed LOGFONT, just use it to create the font return FromLogFontInternal(ref logFont, hdc); } Type type = lf.GetType(); int nativeSize = sizeof(SafeNativeMethods.LOGFONT); if (Marshal.SizeOf(type) != nativeSize) { // If we don't actually have an object that is LOGFONT in size, trying to pass // it to GDI+ is likely to cause an AV. throw new ArgumentException(); } // Now that we know the marshalled size is the same as LOGFONT, copy in the data logFont = new SafeNativeMethods.LOGFONT(); Marshal.StructureToPtr(lf, new IntPtr(&logFont), fDeleteOld: false); return FromLogFontInternal(ref logFont, hdc); } /// <summary> /// Creates a <see cref="Font"/> from the specified handle to a device context (HDC). /// </summary> /// <returns>The newly created <see cref="Font"/>.</returns> public static Font FromHdc(IntPtr hdc) { IntPtr font = IntPtr.Zero; int status = Gdip.GdipCreateFontFromDC(hdc, ref font); // Special case this incredibly common error message to give more information if (status == Gdip.NotTrueTypeFont) { throw new ArgumentException(SR.GdiplusNotTrueTypeFont_NoName); } else if (status != Gdip.Ok) { throw Gdip.StatusException(status); } return new Font(font, 0, false); } /// <summary> /// Creates an exact copy of this <see cref='Font'/>. /// </summary> public object Clone() { int status = Gdip.GdipCloneFont(new HandleRef(this, _nativeFont), out IntPtr clonedFont); Gdip.CheckStatus(status); return new Font(clonedFont, _gdiCharSet, _gdiVerticalFont); } private void SetFontFamily(FontFamily family) { _fontFamily = family; // GDI+ creates ref-counted singleton FontFamily objects based on the family name so all managed // objects with same family name share the underlying GDI+ native pointer. The unmanged object is // destroyed when its ref-count gets to zero. // // Make sure _fontFamily is not finalized so the underlying singleton object is kept alive. GC.SuppressFinalize(_fontFamily); } private static string StripVerticalName(string familyName) { if (familyName?.Length > 1 && familyName[0] == '@') { return familyName.Substring(1); } return familyName; } public void ToLogFont(object logFont) { using (ScreenDC dc = ScreenDC.Create()) using (Graphics graphics = Graphics.FromHdcInternal(dc)) { ToLogFont(logFont, graphics); } } /// <summary> /// Returns a handle to this <see cref='Font'/>. /// </summary> public IntPtr ToHfont() { using (ScreenDC dc = ScreenDC.Create()) using (Graphics graphics = Graphics.FromHdcInternal(dc)) { SafeNativeMethods.LOGFONT lf = ToLogFontInternal(graphics); IntPtr handle = IntUnsafeNativeMethods.CreateFontIndirect(ref lf); if (handle == IntPtr.Zero) { throw new Win32Exception(); } return handle; } } public float GetHeight() { using (ScreenDC dc = ScreenDC.Create()) using (Graphics graphics = Graphics.FromHdcInternal(dc)) { return GetHeight(graphics); } } /// <summary> /// Gets the size, in points, of this <see cref='Font'/>. /// </summary> [Browsable(false)] public float SizeInPoints { get { if (Unit == GraphicsUnit.Point) { return Size; } using (ScreenDC dc = ScreenDC.Create()) using (Graphics graphics = Graphics.FromHdcInternal(dc)) { float pixelsPerPoint = (float)(graphics.DpiY / 72.0); float lineSpacingInPixels = GetHeight(graphics); float emHeightInPixels = lineSpacingInPixels * FontFamily.GetEmHeight(Style) / FontFamily.GetLineSpacing(Style); return emHeightInPixels / pixelsPerPoint; } } } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System.Threading; using System.Collections.Generic; using System.Configuration.Provider; using System.Collections; using System.Linq; namespace System.Web { public partial class StaticSiteMapProviderEx { private List<SiteMapProvider> _childProviders; private Dictionary<SiteMapProvider, SiteMapNode> _childProviderRootNodes; //private ReaderWriterLockSlim _childProviderRwLock = new ReaderWriterLockSlim(); private SiteMapNode FindSiteMapNodeFromChildProvider(string rawUrl) { foreach (var provider in ChildProviders) { EnsureChildSiteMapProviderUpToDate(provider); var node = provider.FindSiteMapNode(rawUrl); if (node != null) return node; } return null; } protected bool HasChildProviders { get { return !EnumerableEx.IsNullOrEmpty(ChildProviders); } } private SiteMapNode FindSiteMapNodeFromChildProviderKey(string key) { foreach (var provider in ChildProviders) { EnsureChildSiteMapProviderUpToDate(provider); var node = provider.FindSiteMapNodeFromKey(key); if (node != null) return node; } return null; } public void AddProvider(string providerName, SiteMapNode parentNode) { AddProvider(providerName, parentNode, null); } public void AddProvider(string providerName, SiteMapNode parentNode, Action<SiteMapNode> rebaseAction) { if (parentNode == null) throw new ArgumentNullException("parentNode"); if (parentNode.Provider != this) throw new ArgumentException(string.Format("StaticSiteMapProviderEx_cannot_add_node", parentNode.ToString()), "parentNode"); var rootNode = GetNodeFromProvider(providerName, rebaseAction); AddNode(rootNode, parentNode); } private SiteMapNode GetNodeFromProvider(string providerName, Action<SiteMapNode> rebaseAction) { var providerFromName = GetProviderFromName(providerName); var rootNode = providerFromName.RootNode; if (rootNode == null) throw new InvalidOperationException(string.Format("StaticSiteMapProviderEx_invalid_GetRootNodeCore", providerFromName.Name)); if (!ChildProviderRootNodes.ContainsKey(providerFromName)) { ChildProviderRootNodes.Add(providerFromName, rootNode); _childProviders = null; providerFromName.ParentProvider = this; if (rebaseAction != null) rebaseAction(rootNode); } return rootNode; } protected override void RemoveNode(SiteMapNode node) { if (node == null) throw new ArgumentNullException("node"); var provider = node.Provider; if (provider != this) for (var parentProvider = provider.ParentProvider; parentProvider != this; parentProvider = parentProvider.ParentProvider) if (parentProvider == null) throw new InvalidOperationException(string.Format("StaticSiteMapProviderEx_cannot_remove_node", node.ToString(), Name, provider.Name)); if (node.Equals(provider.RootNode)) throw new InvalidOperationException("StaticSiteMapProviderEx_cannot_remove_root_node"); if (provider != this) _providerRemoveNode.Invoke(provider, new[] { node }); base.RemoveNode(node); } protected virtual void RemoveProvider(string providerName) { if (providerName == null) throw new ArgumentNullException("providerName"); lock (_providerLock) { var providerFromName = GetProviderFromName(providerName); var node = ChildProviderRootNodes[providerFromName]; if (node == null) throw new InvalidOperationException(string.Format("StaticSiteMapProviderEx_cannot_find_provider", providerFromName.Name, Name)); providerFromName.ParentProvider = null; ChildProviderRootNodes.Remove(providerFromName); _childProviders = null; base.RemoveNode(node); } } private List<SiteMapProvider> ChildProviders { get { if (_childProviders == null) lock (_providerLock) if (_childProviders == null) _childProviders = new List<SiteMapProvider>(ChildProviderRootNodes.Keys); return _childProviders; } } private Dictionary<SiteMapProvider, SiteMapNode> ChildProviderRootNodes { get { if (_childProviderRootNodes == null) lock (_providerLock) if (_childProviderRootNodes == null) _childProviderRootNodes = new Dictionary<SiteMapProvider, SiteMapNode>(); return _childProviderRootNodes; } } private void EnsureChildSiteMapProviderUpToDate(SiteMapProvider childProvider) { var node = ChildProviderRootNodes[childProvider]; if (node == null) return; var rootNode = childProvider.RootNode; if (rootNode == null) throw new InvalidOperationException(string.Format("XmlSiteMapProvider_invalid_sitemapnode_returned", childProvider.Name)); if (!node.Equals(rootNode)) lock (_providerLock) { node = ChildProviderRootNodes[childProvider]; if (node != null) { rootNode = childProvider.RootNode; if (rootNode == null) throw new InvalidOperationException(string.Format("XmlSiteMapProvider_invalid_sitemapnode_returned", childProvider.Name)); if (!node.Equals(rootNode)) { // double-lock reached if (_rootNode.Equals(node)) { RemoveNode(node); AddNode(rootNode); _rootNode = rootNode; } //var node3 = (SiteMapNode)base.ParentNodeTable[node]; //if (node3 != null) //{ // var nodes = (SiteMapNodeCollection)base.ChildNodeCollectionTable[node3]; // int index = nodes.IndexOf(node); // if (index != -1) // { // nodes.Remove(node); // nodes.Insert(index, rootNode); // } // else // nodes.Add(rootNode); // base.ParentNodeTable[rootNode] = node3; // base.ParentNodeTable.Remove(node); // RemoveNode(node); // AddNode(rootNode); //} //else //{ // var parentProvider = (ParentProvider as StaticSiteMapProviderEx); // if (parentProvider != null) // parentProvider.EnsureChildSiteMapProviderUpToDate(this); //} ChildProviderRootNodes[childProvider] = rootNode; _childProviders = null; } } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using RestCake.Metadata; using RestCake.Util; namespace RestCake.Clients { public class AmdClientWriter { private readonly TextWriter m_textWriter; public AmdClientWriter(TextWriter textWriter) { m_textWriter = textWriter; } public void WriteServiceClient(ServiceMetadata service, string baseUrl) { // Get the service client template, and setup the namespace, and the name of the js class string clientTemplate = ReflectionHelper.GetTemplateContents("Js.AmdClient.js"); clientTemplate = clientTemplate .Replace("$$Namespace", service.ServiceNamespace) .Replace("$$JsClassName", service.ServiceName + "Client"); // Go through each method in the service class, creating the js body for each one. StringBuilder sbServiceMethods = new StringBuilder(); foreach (MethodMetadata method in service.Methods) sbServiceMethods.AppendLine(getMethodBody(method)); // Now create special versions that can be called using just a form ID, where the form will be jquery serialized, and the args taken automatically foreach (MethodMetadata method in service.Methods) sbServiceMethods.AppendLine(getMethodBody_jqueryFormSerialize(method)); // Add the service method bodies (js) that we just created to the client template clientTemplate = clientTemplate.Replace("$$ServiceMethods", sbServiceMethods.ToString()); // Write out the client template m_textWriter.WriteLine("// AmdClient.js template"); m_textWriter.WriteLine(clientTemplate); } private static string getMethodBody_jqueryFormSerialize(MethodMetadata method) { string serviceMethodTemplate = ReflectionHelper.GetTemplateContents("Js.AmdServiceMethod-jqueryFormSerialize.txt"); string[] paramNames = method.GetParamNames(); string strParamNames = ""; if (paramNames.Length > 0) strParamNames = "\"" + String.Join("\",\"", paramNames) + "\""; IList<ParameterInfo> intParams = method.GetIntParams(); string strIntParams = ""; if (intParams.Count > 0) strIntParams = "\"" + String.Join("\",\"", intParams.Select(p => p.Name)) + "\""; IList<object> intParamDefaults = intParams.Select(prm => Activator.CreateInstance(prm.ParameterType) ?? "null").ToList(); string strIntParamDefaults = String.Join(",", intParamDefaults); IList<ParameterInfo> floatParams = method.GetFloatParams(); string strFloatParams = ""; if (floatParams.Count > 0) strFloatParams = "\"" + String.Join("\",\"", floatParams.Select(p => p.Name)) + "\""; IList<object> floatParamDefaults = floatParams.Select(prm => Activator.CreateInstance(prm.ParameterType) ?? "null").ToList(); string strFloatParamDefaults = String.Join(",", floatParamDefaults); string methodBody = serviceMethodTemplate .Replace("$$MethodName", method.Name) .Replace("$$jsonp", "") .Replace("$$ParamNames", strParamNames) .Replace("$$IntParams", strIntParams) .Replace("$$IntParamDefaults", strIntParamDefaults) .Replace("$$FloatParams", strFloatParams) .Replace("$$FloatParamDefaults", strFloatParamDefaults); // If it's GET, add an additional "_jsonp" method that can be called if (method.Verb == HttpVerb.Get) { string jsonpMethodBody = serviceMethodTemplate .Replace("$$MethodName", method.Name) .Replace("$$jsonp", "_jsonp") .Replace("$$ParamNames", strParamNames) .Replace("$$IntParams", strIntParams) .Replace("$$IntParamDefaults", strIntParamDefaults) .Replace("$$FloatParams", strFloatParams) .Replace("$$FloatParamDefaults", strFloatParamDefaults); methodBody += Environment.NewLine + jsonpMethodBody; } return methodBody; } private static string getMethodBody(MethodMetadata method) { string serviceMethodTemplate = ReflectionHelper.GetTemplateContents("Js.AmdServiceMethod.txt"); string dataArg = "null"; // The template works "as-is" with HTTP GET. For the other verbs (PUT, POST, DELETE), we have to modify the dataArg value. if (method.Verb != HttpVerb.Get) { string[] dataParams = method.GetDataParamNames(); // Set up the dataArg variable StringBuilder sbDataArg = new StringBuilder(); if (method.IsWrappedRequest) { // Start the wrapped json object sbDataArg.Append("{"); foreach (string param in dataParams) { sbDataArg.Append("\"").Append(param).Append("\": "); if (param.EndsWith("Json")) sbDataArg.Append("JSON.stringify(").Append(param.Substring(0, param.Length - "Json".Length)).Append("), "); else sbDataArg.Append(param).Append(", "); } // Get rid of the trailing ", " if (sbDataArg.Length > 1) sbDataArg.Remove(sbDataArg.Length - 2, 2); // End the json wrapped object sbDataArg.Append("}"); } else // Not wrapped { if (dataParams.Length > 1) throw new NotSupportedException("Error with service method " + method.Name + " in the " + method.Service.ServiceName + " service. Passing in multiple data arguments requires that the service have a wrapped request " + "(WebMessageBodyStyle.Wrapped or WebMessageBodyStyle.WrappedRequest)"); if (dataParams.Length == 0) { sbDataArg.Append("null"); } else { if (dataParams[0].EndsWith("Json")) sbDataArg.Append("JSON.stringify(").Append(dataParams[0].Substring(0, dataParams[0].Length - "Json".Length)). Append(")"); else sbDataArg.Append(dataParams[0]); } } dataArg = sbDataArg.ToString(); } string methodBody = serviceMethodTemplate .Replace("$$MethodName", method.Name) .Replace("$$jsonp", "") .Replace("$$isJsonp", "false") .Replace("$$MethodArgs", getArgsListAsString(method)) .Replace("$$DefaultErrorMessage", "Error calling " + method.Service.ServiceNamespace + "." + method.Name) .Replace("$$MethodUrl", getMethodUrl(method)) .Replace("$$HttpVerb", method.Verb.ToString("g").ToUpper()) .Replace("$$DataArg", dataArg) .Replace("$$IsWrappedResponse", method.IsWrappedResponse.ToString().ToLower()); if (method.Verb == HttpVerb.Get) { string jsonpMethodBody = serviceMethodTemplate .Replace("$$MethodName", method.Name) .Replace("$$jsonp", "_jsonp") .Replace("$$isJsonp", "true") .Replace("$$MethodArgs", getArgsListAsString(method)) .Replace("$$DefaultErrorMessage", "Error calling " + method.Service.ServiceNamespace + "." + method.Name) .Replace("$$MethodUrl", getMethodUrl(method)) .Replace("$$HttpVerb", method.Verb.ToString("g").ToUpper()) .Replace("$$DataArg", dataArg) .Replace("$$IsWrappedResponse", method.IsWrappedResponse.ToString().ToLower()); methodBody += Environment.NewLine + jsonpMethodBody; } return methodBody; } /// <summary> /// Returns a string like "arg1, arg2, arg3", etc (joins all params with a comma) /// TODO: Currently, any arg that ends with the string "Json" (such as personJson), the "Json" will be chopped off. /// This was for a specific feature (need to look into it and see if it's still used) /// </summary> /// <returns></returns> internal static string getArgsListAsString(MethodMetadata method) { // For args that end with "Json", we want to strip that off the arg name. // WCF doesn't seem to let us pass raw json in as a param. They want to use their own deserialization, which fails for many things. // We are using Json.NET, and so we pass in doubly quoted json strings, so the arg going into the service method is not an object, but a string. // But, we want our params named sanely. Regex rxNoJson = new Regex(@"Json$"); string argsList = String.Join(", ", method.GetParamNames().Select(p => rxNoJson.Replace(p, "")).ToArray()); if (argsList.Length > 0) argsList += ", "; return argsList; } private static string getMethodUrl(MethodMetadata method) { string methodUrl = "'" + method.UriTemplate + "'"; ParameterInfo[] urlParams = method.GetUrlParams(); // Query string params foreach (ParameterInfo param in urlParams) { string search = String.Format("{0}={{{0}}}", param.Name); string replace = String.Format("{0}=' + (({0} == null || {0} === 'undefined') ? '' : {1}) + '", param.Name, getParamUrlString(param)); methodUrl = methodUrl.Replace(search, replace); } // Get rid of useless empty string concats methodUrl = methodUrl.Replace(" + ''", ""); // Uri segment params foreach (var param in urlParams) methodUrl = methodUrl.Replace("{" + param.Name + "}", "' + " + getParamUrlString(param) + " + '"); // Get rid of weird [ + ''] and ['' + ] instances at the end or beginning (respecitvely) of the string Regex rxBeg = new Regex(@"^'' \+ "); Regex rxEnd = new Regex(@" \+ ''$"); methodUrl = rxBeg.Replace(methodUrl, ""); methodUrl = rxEnd.Replace(methodUrl, ""); return methodUrl; } private static string getParamUrlString(ParameterInfo param) { string value = param.Name; // Do we need to JSON.stringify() the arg? if ((!typeof(IEnumerable).IsAssignableFrom(param.ParameterType) || typeof(IDictionary).IsAssignableFrom(param.ParameterType)) // Not an IEnumerable or IS a Dictionary. && !typeof(string).IsAssignableFrom(param.ParameterType) && !param.ParameterType.IsPrimitive && !param.ParameterType.IsEnum) { value = "JSON.stringify(" + param.Name + ")"; } // True, RestCake on the server handles it when it's NOT that way, but it won't handle commas in the strings, so it's an easy point of failure. else if (param.ParameterType == typeof(string[]) || typeof(IList<string>).IsAssignableFrom(param.ParameterType)) { // For arrays or lists of strings (in a GET url, remember), use an empty string for null, [] for an empty array, and JSON.stringify() for a populated array. value = "(" + param.Name + " == null ? '' : (" + param.Name + ".length == 0 ? '[]' : JSON.stringify(" + param.Name + ")))"; } return value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Reflection.Emit { using System.Text; using System; using CultureInfo = System.Globalization.CultureInfo; using System.Diagnostics.SymbolStore; using System.Reflection; using System.Security; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; public sealed class MethodBuilder : MethodInfo { #region Private Data Members // Identity internal String m_strName; // The name of the method private MethodToken m_tkMethod; // The token of this method private ModuleBuilder m_module; internal TypeBuilder m_containingType; // IL private int[] m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups. private byte[] m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise. internal LocalSymInfo m_localSymInfo; // keep track debugging local information internal ILGenerator m_ilGenerator; // Null if not used. private byte[] m_ubBody; // The IL for the method private ExceptionHandler[] m_exceptions; // Exception handlers or null if there are none. private const int DefaultMaxStack = 16; private int m_maxStack = DefaultMaxStack; // Flags internal bool m_bIsBaked; private bool m_bIsGlobalMethod; private bool m_fInitLocals; // indicating if the method stack frame will be zero initialized or not. // Attributes private MethodAttributes m_iAttributes; private CallingConventions m_callingConvention; private MethodImplAttributes m_dwMethodImplFlags; // Parameters private SignatureHelper m_signature; internal Type[] m_parameterTypes; private ParameterBuilder m_retParam; private Type m_returnType; private Type[] m_returnTypeRequiredCustomModifiers; private Type[] m_returnTypeOptionalCustomModifiers; private Type[][] m_parameterTypeRequiredCustomModifiers; private Type[][] m_parameterTypeOptionalCustomModifiers; // Generics private GenericTypeParameterBuilder[] m_inst; private bool m_bIsGenMethDef; #endregion #region Constructor internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { Init(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, mod, type, bIsGlobalMethod); } private void Init(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); if (name[0] == '\0') throw new ArgumentException(SR.Argument_IllegalName, nameof(name)); if (mod == null) throw new ArgumentNullException(nameof(mod)); if (parameterTypes != null) { foreach (Type t in parameterTypes) { if (t == null) throw new ArgumentNullException(nameof(parameterTypes)); } } m_strName = name; m_module = mod; m_containingType = type; // //if (returnType == null) //{ // m_returnType = typeof(void); //} //else { m_returnType = returnType; } if ((attributes & MethodAttributes.Static) == 0) { // turn on the has this calling convention callingConvention = callingConvention | CallingConventions.HasThis; } else if ((attributes & MethodAttributes.Virtual) != 0) { // A method can't be both static and virtual throw new ArgumentException(SR.Arg_NoStaticVirtual); } if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName) { if ((type.Attributes & TypeAttributes.Interface) == TypeAttributes.Interface) { // methods on interface have to be abstract + virtual except special name methods such as type initializer if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) != (MethodAttributes.Abstract | MethodAttributes.Virtual) && (attributes & MethodAttributes.Static) == 0) throw new ArgumentException(SR.Argument_BadAttributeOnInterfaceMethod); } } m_callingConvention = callingConvention; if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length); } else { m_parameterTypes = null; } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; // m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention, // returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, // parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); m_iAttributes = attributes; m_bIsGlobalMethod = bIsGlobalMethod; m_bIsBaked = false; m_fInitLocals = true; m_localSymInfo = new LocalSymInfo(); m_ubBody = null; m_ilGenerator = null; // Default is managed IL. Manged IL has bit flag 0x0020 set off m_dwMethodImplFlags = MethodImplAttributes.IL; } #endregion #region Internal Members internal void CheckContext(params Type[][] typess) { m_module.CheckContext(typess); } internal void CheckContext(params Type[] types) { m_module.CheckContext(types); } internal void CreateMethodBodyHelper(ILGenerator il) { // Sets the IL of the method. An ILGenerator is passed as an argument and the method // queries this instance to get all of the information which it needs. if (il == null) { throw new ArgumentNullException(nameof(il)); } __ExceptionInfo[] excp; int counter = 0; int[] filterAddrs; int[] catchAddrs; int[] catchEndAddrs; Type[] catchClass; int[] type; int numCatch; int start, end; ModuleBuilder dynMod = (ModuleBuilder)m_module; m_containingType.ThrowIfCreated(); if (m_bIsBaked) { throw new InvalidOperationException(SR.InvalidOperation_MethodHasBody); } if (il.m_methodBuilder != this && il.m_methodBuilder != null) { // you don't need to call DefineBody when you get your ILGenerator // through MethodBuilder::GetILGenerator. // throw new InvalidOperationException(SR.InvalidOperation_BadILGeneratorUsage); } ThrowIfShouldNotHaveBody(); if (il.m_ScopeTree.m_iOpenScopeCount != 0) { // There are still unclosed local scope throw new InvalidOperationException(SR.InvalidOperation_OpenLocalVariableScope); } m_ubBody = il.BakeByteArray(); m_mdMethodFixups = il.GetTokenFixups(); //Okay, now the fun part. Calculate all of the exceptions. excp = il.GetExceptions(); int numExceptions = CalculateNumberOfExceptions(excp); if (numExceptions > 0) { m_exceptions = new ExceptionHandler[numExceptions]; for (int i = 0; i < excp.Length; i++) { filterAddrs = excp[i].GetFilterAddresses(); catchAddrs = excp[i].GetCatchAddresses(); catchEndAddrs = excp[i].GetCatchEndAddresses(); catchClass = excp[i].GetCatchClass(); numCatch = excp[i].GetNumberOfCatches(); start = excp[i].GetStartAddress(); end = excp[i].GetEndAddress(); type = excp[i].GetExceptionTypes(); for (int j = 0; j < numCatch; j++) { int tkExceptionClass = 0; if (catchClass[j] != null) { tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]).Token; } switch (type[j]) { case __ExceptionInfo.None: case __ExceptionInfo.Fault: case __ExceptionInfo.Filter: m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; case __ExceptionInfo.Finally: m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; } } } } m_bIsBaked = true; if (dynMod.GetSymWriter() != null) { // set the debugging information such as scope and line number // if it is in a debug module // SymbolToken tk = new SymbolToken(MetadataTokenInternal); ISymbolWriter symWriter = dynMod.GetSymWriter(); // call OpenMethod to make this method the current method symWriter.OpenMethod(tk); // call OpenScope because OpenMethod no longer implicitly creating // the top-levelsmethod scope // symWriter.OpenScope(0); if (m_symCustomAttrs != null) { foreach (SymCustomAttr symCustomAttr in m_symCustomAttrs) dynMod.GetSymWriter().SetSymAttribute( new SymbolToken(MetadataTokenInternal), symCustomAttr.m_name, symCustomAttr.m_data); } if (m_localSymInfo != null) m_localSymInfo.EmitLocalSymInfo(symWriter); il.m_ScopeTree.EmitScopeTree(symWriter); il.m_LineNumberInfo.EmitLineNumberInfo(symWriter); symWriter.CloseScope(il.ILOffset); symWriter.CloseMethod(); } } // This is only called from TypeBuilder.CreateType after the method has been created internal void ReleaseBakedStructures() { if (!m_bIsBaked) { // We don't need to do anything here if we didn't baked the method body return; } m_ubBody = null; m_localSymInfo = null; m_mdMethodFixups = null; m_localSignature = null; m_exceptions = null; } internal override Type[] GetParameterTypes() { if (m_parameterTypes == null) m_parameterTypes = Array.Empty<Type>(); return m_parameterTypes; } internal static Type GetMethodBaseReturnType(MethodBase method) { MethodInfo mi = null; ConstructorInfo ci = null; if ((mi = method as MethodInfo) != null) { return mi.ReturnType; } else if ((ci = method as ConstructorInfo) != null) { return ci.GetReturnType(); } else { Debug.Fail("We should never get here!"); return null; } } internal byte[] GetBody() { // Returns the il bytes of this method. // This il is not valid until somebody has called BakeByteArray return m_ubBody; } internal int[] GetTokenFixups() { return m_mdMethodFixups; } internal SignatureHelper GetMethodSignature() { if (m_parameterTypes == null) m_parameterTypes = Array.Empty<Type>(); m_signature = SignatureHelper.GetMethodSigHelper(m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0, m_returnType == null ? typeof(void) : m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers, m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers); return m_signature; } // Returns a buffer whose initial signatureLength bytes contain encoded local signature. internal byte[] GetLocalSignature(out int signatureLength) { if (m_localSignature != null) { signatureLength = m_localSignature.Length; return m_localSignature; } if (m_ilGenerator != null) { if (m_ilGenerator.m_localCount != 0) { // If user is using ILGenerator::DeclareLocal, then get local signaturefrom there. return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength); } } return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength); } internal int GetMaxStack() { if (m_ilGenerator != null) { return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount; } else { // this is the case when client provide an array of IL byte stream rather than going through ILGenerator. return m_maxStack; } } internal ExceptionHandler[] GetExceptionHandlers() { return m_exceptions; } internal int ExceptionHandlerCount { get { return m_exceptions != null ? m_exceptions.Length : 0; } } internal int CalculateNumberOfExceptions(__ExceptionInfo[] excp) { int num = 0; if (excp == null) { return 0; } for (int i = 0; i < excp.Length; i++) { num += excp[i].GetNumberOfCatches(); } return num; } internal bool IsTypeCreated() { return (m_containingType != null && m_containingType.IsCreated()); } internal TypeBuilder GetTypeBuilder() { return m_containingType; } internal ModuleBuilder GetModuleBuilder() { return m_module; } #endregion #region Object Overrides public override bool Equals(Object obj) { if (!(obj is MethodBuilder)) { return false; } if (!(this.m_strName.Equals(((MethodBuilder)obj).m_strName))) { return false; } if (m_iAttributes != (((MethodBuilder)obj).m_iAttributes)) { return false; } SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature(); if (thatSig.Equals(GetMethodSignature())) { return true; } return false; } public override int GetHashCode() { return this.m_strName.GetHashCode(); } public override String ToString() { StringBuilder sb = new StringBuilder(1000); sb.Append("Name: " + m_strName + " " + Environment.NewLine); sb.Append("Attributes: " + (int)m_iAttributes + Environment.NewLine); sb.Append("Method Signature: " + GetMethodSignature() + Environment.NewLine); sb.Append(Environment.NewLine); return sb.ToString(); } #endregion #region MemberInfo Overrides public override String Name { get { return m_strName; } } internal int MetadataTokenInternal { get { return GetToken().Token; } } public override Module Module { get { return m_containingType.Module; } } public override Type DeclaringType { get { if (m_containingType.m_isHiddenGlobalType == true) return null; return m_containingType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return null; } } public override Type ReflectedType { get { return DeclaringType; } } #endregion #region MethodBase Overrides public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_dwMethodImplFlags; } public override MethodAttributes Attributes { get { return m_iAttributes; } } public override CallingConventions CallingConvention { get { return m_callingConvention; } } public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } } public override bool IsSecurityCritical { get { return true; } } public override bool IsSecuritySafeCritical { get { return false; } } public override bool IsSecurityTransparent { get { return false; } } #endregion #region MethodInfo Overrides public override MethodInfo GetBaseDefinition() { return this; } public override Type ReturnType { get { return m_returnType; } } public override ParameterInfo[] GetParameters() { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new NotSupportedException(SR.InvalidOperation_TypeNotCreated); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes); return rmi.GetParameters(); } public override ParameterInfo ReturnParameter { get { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new InvalidOperationException(SR.InvalidOperation_TypeNotCreated); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes); return rmi.ReturnParameter; } } #endregion #region ICustomAttributeProvider Implementation public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } #endregion #region Generic Members public override bool IsGenericMethodDefinition { get { return m_bIsGenMethDef; } } public override bool ContainsGenericParameters { get { throw new NotSupportedException(); } } public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; } public override bool IsGenericMethod { get { return m_inst != null; } } public override Type[] GetGenericArguments() { return m_inst; } public override MethodInfo MakeGenericMethod(params Type[] typeArguments) { return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments); } public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { if (names == null) throw new ArgumentNullException(nameof(names)); if (names.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(names)); if (m_inst != null) throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet); for (int i = 0; i < names.Length; i++) if (names[i] == null) throw new ArgumentNullException(nameof(names)); if (m_tkMethod.Token != 0) throw new InvalidOperationException(SR.InvalidOperation_MethodBuilderBaked); m_bIsGenMethDef = true; m_inst = new GenericTypeParameterBuilder[names.Length]; for (int i = 0; i < names.Length; i++) m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this)); return m_inst; } internal void ThrowIfGeneric() { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException(); } #endregion #region Public Members public MethodToken GetToken() { // We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498 // we only "tokenize" a method when requested. But the order in which the methods are tokenized // didn't change: the same order the MethodBuilders are constructed. The recursion introduced // will overflow the stack when there are many methods on the same type (10000 in my experiment). // The change also introduced race conditions. Before the code change GetToken is called from // the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it // could be called more than once on the the same method introducing duplicate (invalid) tokens. // I don't fully understand this change. So I will keep the logic and only fix the recursion and // the race condition. if (m_tkMethod.Token != 0) { return m_tkMethod; } MethodBuilder currentMethod = null; MethodToken currentToken = new MethodToken(0); int i; // We need to lock here to prevent a method from being "tokenized" twice. // We don't need to synchronize this with Type.DefineMethod because it only appends newly // constructed MethodBuilders to the end of m_listMethods lock (m_containingType.m_listMethods) { if (m_tkMethod.Token != 0) { return m_tkMethod; } // If m_tkMethod is still 0 when we obtain the lock, m_lastTokenizedMethod must be smaller // than the index of the current method. for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; ++i) { currentMethod = m_containingType.m_listMethods[i]; currentToken = currentMethod.GetTokenNoLock(); if (currentMethod == this) break; } m_containingType.m_lastTokenizedMethod = i; } Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods"); Debug.Assert(currentToken.Token != 0, "The token should not be 0"); return currentToken; } private MethodToken GetTokenNoLock() { Debug.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized"); int sigLength; byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength); int token = TypeBuilder.DefineMethod(m_module.GetNativeHandle(), m_containingType.MetadataTokenInternal, m_strName, sigBytes, sigLength, Attributes); m_tkMethod = new MethodToken(token); if (m_inst != null) foreach (GenericTypeParameterBuilder tb in m_inst) if (!tb.m_type.IsCreated()) tb.m_type.CreateType(); TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), token, m_dwMethodImplFlags); return m_tkMethod; } public void SetParameters(params Type[] parameterTypes) { CheckContext(parameterTypes); SetSignature(null, null, null, parameterTypes, null, null); } public void SetReturnType(Type returnType) { CheckContext(returnType); SetSignature(returnType, null, null, null, null, null); } public void SetSignature( Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) { // We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked. // But we cannot because that would be a breaking change from V2. if (m_tkMethod.Token != 0) return; CheckContext(returnType); CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); CheckContext(parameterTypeRequiredCustomModifiers); CheckContext(parameterTypeOptionalCustomModifiers); ThrowIfGeneric(); if (returnType != null) { m_returnType = returnType; } if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length); } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; } public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName) { if (position < 0) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); ThrowIfGeneric(); m_containingType.ThrowIfCreated(); if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length)) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); attributes = attributes & ~ParameterAttributes.ReservedMask; return new ParameterBuilder(this, position, attributes, strParamName); } private List<SymCustomAttr> m_symCustomAttrs; private struct SymCustomAttr { public String m_name; public byte[] m_data; } public void SetImplementationFlags(MethodImplAttributes attributes) { ThrowIfGeneric(); m_containingType.ThrowIfCreated(); m_dwMethodImplFlags = attributes; m_canBeRuntimeImpl = true; TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), MetadataTokenInternal, attributes); } public ILGenerator GetILGenerator() { ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); if (m_ilGenerator == null) m_ilGenerator = new ILGenerator(this); return m_ilGenerator; } public ILGenerator GetILGenerator(int size) { ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); if (m_ilGenerator == null) m_ilGenerator = new ILGenerator(this, size); return m_ilGenerator; } private void ThrowIfShouldNotHaveBody() { if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL || (m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 || (m_iAttributes & MethodAttributes.PinvokeImpl) != 0 || m_isDllImport) { // cannot attach method body if methodimpl is marked not marked as managed IL // throw new InvalidOperationException(SR.InvalidOperation_ShouldNotHaveMethodBody); } } public bool InitLocals { // Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false. get { ThrowIfGeneric(); return m_fInitLocals; } set { ThrowIfGeneric(); m_fInitLocals = value; } } public Module GetModule() { return GetModuleBuilder(); } public String Signature { get { return GetMethodSignature().ToString(); } } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); ThrowIfGeneric(); TypeBuilder.DefineCustomAttribute(m_module, MetadataTokenInternal, ((ModuleBuilder)m_module).GetConstructorToken(con).Token, binaryAttribute, false, false); if (IsKnownCA(con)) ParseCA(con, binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) throw new ArgumentNullException(nameof(customBuilder)); ThrowIfGeneric(); customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataTokenInternal); if (IsKnownCA(customBuilder.m_con)) ParseCA(customBuilder.m_con, customBuilder.m_blob); } // this method should return true for any and every ca that requires more work // than just setting the ca private bool IsKnownCA(ConstructorInfo con) { Type caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) return true; else if (caType == typeof(DllImportAttribute)) return true; else return false; } private void ParseCA(ConstructorInfo con, byte[] blob) { Type caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) { // dig through the blob looking for the MethodImplAttributes flag // that must be in the MethodCodeType field // for now we simply set a flag that relaxes the check when saving and // allows this method to have no body when any kind of MethodImplAttribute is present m_canBeRuntimeImpl = true; } else if (caType == typeof(DllImportAttribute)) { m_canBeRuntimeImpl = true; m_isDllImport = true; } } internal bool m_canBeRuntimeImpl = false; internal bool m_isDllImport = false; #endregion } internal class LocalSymInfo { // This class tracks the local variable's debugging information // and namespace information with a given active lexical scope. #region Internal Data Members internal String[] m_strName; internal byte[][] m_ubSignature; internal int[] m_iLocalSlot; internal int[] m_iStartOffset; internal int[] m_iEndOffset; internal int m_iLocalSymCount; // how many entries in the arrays are occupied internal String[] m_namespace; internal int m_iNameSpaceCount; internal const int InitialSize = 16; #endregion #region Constructor internal LocalSymInfo() { // initialize data variables m_iLocalSymCount = 0; m_iNameSpaceCount = 0; } #endregion #region Private Members private void EnsureCapacityNamespace() { if (m_iNameSpaceCount == 0) { m_namespace = new String[InitialSize]; } else if (m_iNameSpaceCount == m_namespace.Length) { String[] strTemp = new String[checked(m_iNameSpaceCount * 2)]; Array.Copy(m_namespace, 0, strTemp, 0, m_iNameSpaceCount); m_namespace = strTemp; } } private void EnsureCapacity() { if (m_iLocalSymCount == 0) { // First time. Allocate the arrays. m_strName = new String[InitialSize]; m_ubSignature = new byte[InitialSize][]; m_iLocalSlot = new int[InitialSize]; m_iStartOffset = new int[InitialSize]; m_iEndOffset = new int[InitialSize]; } else if (m_iLocalSymCount == m_strName.Length) { // the arrays are full. Enlarge the arrays // why aren't we just using lists here? int newSize = checked(m_iLocalSymCount * 2); int[] temp = new int[newSize]; Array.Copy(m_iLocalSlot, 0, temp, 0, m_iLocalSymCount); m_iLocalSlot = temp; temp = new int[newSize]; Array.Copy(m_iStartOffset, 0, temp, 0, m_iLocalSymCount); m_iStartOffset = temp; temp = new int[newSize]; Array.Copy(m_iEndOffset, 0, temp, 0, m_iLocalSymCount); m_iEndOffset = temp; String[] strTemp = new String[newSize]; Array.Copy(m_strName, 0, strTemp, 0, m_iLocalSymCount); m_strName = strTemp; byte[][] ubTemp = new byte[newSize][]; Array.Copy(m_ubSignature, 0, ubTemp, 0, m_iLocalSymCount); m_ubSignature = ubTemp; } } #endregion #region Internal Members internal void AddLocalSymInfo(String strName, byte[] signature, int slot, int startOffset, int endOffset) { // make sure that arrays are large enough to hold addition info EnsureCapacity(); m_iStartOffset[m_iLocalSymCount] = startOffset; m_iEndOffset[m_iLocalSymCount] = endOffset; m_iLocalSlot[m_iLocalSymCount] = slot; m_strName[m_iLocalSymCount] = strName; m_ubSignature[m_iLocalSymCount] = signature; checked { m_iLocalSymCount++; } } internal void AddUsingNamespace(String strNamespace) { EnsureCapacityNamespace(); m_namespace[m_iNameSpaceCount] = strNamespace; checked { m_iNameSpaceCount++; } } internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter) { int i; for (i = 0; i < m_iLocalSymCount; i++) { symWriter.DefineLocalVariable( m_strName[i], FieldAttributes.PrivateScope, m_ubSignature[i], SymAddressKind.ILOffset, m_iLocalSlot[i], 0, // addr2 is not used yet 0, // addr3 is not used m_iStartOffset[i], m_iEndOffset[i]); } for (i = 0; i < m_iNameSpaceCount; i++) { symWriter.UsingNamespace(m_namespace[i]); } } #endregion } /// <summary> /// Describes exception handler in a method body. /// </summary> [StructLayout(LayoutKind.Sequential)] internal readonly struct ExceptionHandler : IEquatable<ExceptionHandler> { // Keep in sync with unmanged structure. internal readonly int m_exceptionClass; internal readonly int m_tryStartOffset; internal readonly int m_tryEndOffset; internal readonly int m_filterOffset; internal readonly int m_handlerStartOffset; internal readonly int m_handlerEndOffset; internal readonly ExceptionHandlingClauseOptions m_kind; #region Constructors internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset, int kind, int exceptionTypeToken) { Debug.Assert(tryStartOffset >= 0); Debug.Assert(tryEndOffset >= 0); Debug.Assert(filterOffset >= 0); Debug.Assert(handlerStartOffset >= 0); Debug.Assert(handlerEndOffset >= 0); Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind)); Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0); m_tryStartOffset = tryStartOffset; m_tryEndOffset = tryEndOffset; m_filterOffset = filterOffset; m_handlerStartOffset = handlerStartOffset; m_handlerEndOffset = handlerEndOffset; m_kind = (ExceptionHandlingClauseOptions)kind; m_exceptionClass = exceptionTypeToken; } private static bool IsValidKind(ExceptionHandlingClauseOptions kind) { switch (kind) { case ExceptionHandlingClauseOptions.Clause: case ExceptionHandlingClauseOptions.Filter: case ExceptionHandlingClauseOptions.Finally: case ExceptionHandlingClauseOptions.Fault: return true; default: return false; } } #endregion #region Equality public override int GetHashCode() { return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind; } public override bool Equals(Object obj) { return obj is ExceptionHandler && Equals((ExceptionHandler)obj); } public bool Equals(ExceptionHandler other) { return other.m_exceptionClass == m_exceptionClass && other.m_tryStartOffset == m_tryStartOffset && other.m_tryEndOffset == m_tryEndOffset && other.m_filterOffset == m_filterOffset && other.m_handlerStartOffset == m_handlerStartOffset && other.m_handlerEndOffset == m_handlerEndOffset && other.m_kind == m_kind; } public static bool operator ==(ExceptionHandler left, ExceptionHandler right) { return left.Equals(right); } public static bool operator !=(ExceptionHandler left, ExceptionHandler right) { return !left.Equals(right); } #endregion } }
using System; using System.Collections.Generic; using System.Web; using System.Text; using System.Text.RegularExpressions; using Desharp.Core; using System.Web.Script.Serialization; using Desharp.Completers; using System.Web.UI; namespace Desharp.Renderers { internal class Exceptions { internal const string SELF_FILENAME = "Exceptions.cs"; internal static List<string> RenderExceptions (Exception e, bool fileSystemLog = true, bool htmlOut = false, bool catched = true) { List<string> result = new List<string>(); Dictionary<string, ExceptionToRender> exceptions = StackTrace.CompleteInnerExceptions(e, catched); List<string[]> headers = new List<string[]>(); if (Dispatcher.EnvType == EnvType.Web) headers = HttpHeaders.CompletePossibleHttpHeaders(); int i = 0; foreach (var item in exceptions) { //if (item.Value.Exception.StackTrace == null) continue; // why ??!!?????!? exception has always a stacktrace hasn't it? RenderingCollection preparedResult = StackTrace.RenderStackTraceForException( item.Value, fileSystemLog, htmlOut, i ); preparedResult.Headers = headers; result.Add(Exceptions._renderStackRecordResult( preparedResult, fileSystemLog, htmlOut )); i++; } return result; } internal static string RenderCurrentApplicationPoint (string message = "", string exceptionType = "", bool fileSystemLog = true, bool htmlOut = false) { RenderingCollection preparedResult = StackTrace.CompleteStackTraceForCurrentApplicationPoint( message, exceptionType, fileSystemLog, htmlOut ); List<string[]> headers = new List<string[]>(); if (Dispatcher.EnvType == EnvType.Web) { headers = HttpHeaders.CompletePossibleHttpHeaders(); } preparedResult.Headers = headers; return Exceptions._renderStackRecordResult(preparedResult, fileSystemLog, htmlOut); } private static string _renderStackRecordResult(RenderingCollection preparedResult, bool fileSystemLog = true, bool htmlOut = false) { bool webEnv = Dispatcher.EnvType == EnvType.Web; string dateStr = String.Format("{0:yyyy-MM-dd HH:mm:ss:fff}", DateTime.Now); string errorFileStr = ""; string headersStr; string stackTraceStr; if (htmlOut) { if (webEnv && !fileSystemLog) { headersStr = Exceptions._renderDataTableRows(preparedResult.Headers, htmlOut, false); if (preparedResult.ErrorFileStackTrace.HasValue) { errorFileStr = ErrorFile.Render(preparedResult.ErrorFileStackTrace.Value, StackTraceFormat.Html); } stackTraceStr = Exceptions._renderStackTrace(preparedResult.AllStackTraces, htmlOut, StackTraceFormat.Html, fileSystemLog); return Exceptions._renderStackRecordResultHtmlResponse( preparedResult, errorFileStr, stackTraceStr, headersStr, dateStr ); } else { headersStr = Exceptions._renderDataTableRows(preparedResult.Headers, false, false); stackTraceStr = Exceptions._renderStackTrace(preparedResult.AllStackTraces, htmlOut, StackTraceFormat.Json, fileSystemLog); return Exceptions._renderStackRecordResultHtmlLog( preparedResult, stackTraceStr, headersStr, dateStr ); } } else { headersStr = Exceptions._renderDataTableRows(preparedResult.Headers, htmlOut, false); List<string> processAndThreadId = new List<string>() { "Process ID: " + Tools.GetProcessId().ToString() }; if (!webEnv && !fileSystemLog) { if (preparedResult.ErrorFileStackTrace.HasValue) { errorFileStr = ErrorFile.Render(preparedResult.ErrorFileStackTrace.Value, StackTraceFormat.Text); } stackTraceStr = Exceptions._renderStackTrace(preparedResult.AllStackTraces, htmlOut, StackTraceFormat.Text, fileSystemLog); processAndThreadId.Add("Thread ID : " + Tools.GetThreadId().ToString()); return Exceptions._renderStackRecordResultConsoleText( preparedResult, String.Join(Environment.NewLine + " ", processAndThreadId.ToArray()), errorFileStr, stackTraceStr, headersStr, dateStr ); } else { stackTraceStr = Exceptions._renderStackTrace(preparedResult.AllStackTraces, htmlOut, StackTraceFormat.Json, fileSystemLog); if (webEnv) processAndThreadId.Add("Request ID: " + Tools.GetRequestId().ToString()); processAndThreadId.Add("Thread ID: " + Tools.GetThreadId().ToString()); return Exceptions._renderStackRecordResultLoggerText( preparedResult, String.Join(" | ", processAndThreadId.ToArray()), errorFileStr, stackTraceStr, headersStr, dateStr ); } } } private static string _renderStackRecordResultHtmlResponse ( RenderingCollection preparedResult, string errorFileStr, string stackTraceStr, string headersStr, string dateStr ) { string linkValue = "https://www.google.com/search?sourceid=desharp&gws_rd=us&q=" + HttpUtility.UrlEncode(preparedResult.ExceptionMessage); string causedByMsg = preparedResult.CausedByMessage; if (causedByMsg.Length > 50) causedByMsg = causedByMsg.Substring(0, 50) + "..."; StringBuilder result = new StringBuilder(); result .Append(@"<div class=""exception"">") .Append(@"<div class=""head"">") .Append(@"<div class=""type"">" + preparedResult.ExceptionType) .Append(!String.IsNullOrEmpty(preparedResult.ExceptionHash) ? " (Hash Code: " + preparedResult.ExceptionHash + ")" : "") .Append("</div>") .Append(@"<a href=""" + linkValue + @""" target=""_blank"">") .Append(preparedResult.ExceptionMessage) .Append("</a>") .Append(@"<div class=""info"">") .Append("Catched: " + (preparedResult.Catched ? "yes" : "no")) .Append(preparedResult.CausedByHash.Length > 0 ? ", Caused By: " + preparedResult.CausedByType + " (Hash Code: " + preparedResult.CausedByHash + ", Message: " + causedByMsg + ")" : "") .Append("</div>") .Append("</div>") .Append(errorFileStr) .Append(stackTraceStr); if (preparedResult.Headers.Count > 0) result.Append(Exceptions._renderHtmlDataTable("HTTP Headers:", headersStr)); result.Append( Exceptions._renderHtmlDataTable( "Application Domain Assemblies:", Exceptions._renderDataTableRows(LoadedAssemblies.CompleteLoadedAssemblies(), true, true) ) ); result.Append(Exceptions._renderHtmlResponseFooterInfo()); result.Append("</div>"); return result.ToString(); } private static string _renderStackRecordResultHtmlLog ( RenderingCollection preparedResult, string stackTraceStr, string headersStr, string dateStr ) { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); bool valueRecording = preparedResult.ExceptionType == "Value"; string result = @"<div class=""record" + (valueRecording ? " value" : " exception") + @""">" + @"<div class=""control"">" + @"<div class=""date"">" + dateStr + "</div>"; if (valueRecording) { result += @"<div class=""process"">" + Tools.GetProcessId().ToString() + "</div>" + ((Dispatcher.EnvType == EnvType.Web) ? @"<div class=""request"">" + Tools.GetRequestId().ToString() + "</div>" : "") + @"<div class=""thread"">" + Tools.GetThreadId().ToString() + "</div>" + @"<div class=""desharp-dump"">" + preparedResult.ExceptionMessage + "</div>"; } else { result += @"<div class=""catched"">" + (preparedResult.Catched ? "yes" : "no") + "</div>" + @"<div class=""type"">" + preparedResult.ExceptionType + " (" + preparedResult.ExceptionHash + ")</div>" + @"<div class=""msg"">" + preparedResult.ExceptionMessage + "</div>"; } result += @"</div><div class=""json-data"">"; string dataStr = "{"; if (!valueRecording) { dataStr += "processId: " + Tools.GetProcessId().ToString(); if (Dispatcher.EnvType == EnvType.Web) dataStr += ",requestId:" + Tools.GetRequestId().ToString(); dataStr += ",threadId:" + Tools.GetThreadId().ToString(); } if (!valueRecording && preparedResult.CausedByType != null && preparedResult.CausedByType.Length > 0) { if (dataStr != "{") dataStr += ","; dataStr += "causedByType:" + jsonSerializer.Serialize(preparedResult.CausedByType) + ",causedByHash:" + jsonSerializer.Serialize(preparedResult.CausedByHash); } if (dataStr != "{") dataStr += ","; dataStr += "callstack:" + stackTraceStr; if (preparedResult.Headers.Count > 0) dataStr += ",headers:" + headersStr; dataStr += "}"; result += dataStr + "</div></div>"; return result; } private static string _renderStackRecordResultConsoleText ( RenderingCollection preparedResult, string threadOrRequestIdStr, string errorFileStr, string stackTraceStr, string headersStr, string dateStr ) { string result = preparedResult.ExceptionType + " (Hash Code: " + preparedResult.ExceptionHash + "):"; result += System.Environment.NewLine + " Message : " + preparedResult.ExceptionMessage; result += System.Environment.NewLine + " Time : " + dateStr; result += System.Environment.NewLine + " " + threadOrRequestIdStr; if (preparedResult.CausedByType != null && preparedResult.CausedByType.Length > 0) { result += System.Environment.NewLine + " Cuased By : " + preparedResult.CausedByType + " (Hash Code: " + preparedResult.CausedByHash + ")"; } if (errorFileStr.Length > 0) { string file = Tools.RelativeSourceFullPath(preparedResult.ErrorFileStackTrace.Value.File.ToString()); string line = preparedResult.ErrorFileStackTrace.Value.Line; result += System.Environment.NewLine + " File : " + file + ":" + line + System.Environment.NewLine + errorFileStr; } result += System.Environment.NewLine + " Callstack: " + stackTraceStr; return result; } private static string _renderStackRecordResultLoggerText ( RenderingCollection preparedResult, string threadOrRequestIdStr, string errorFileStr, string stackTraceStr, string headersStr, string dateStr ) { Regex r1 = new Regex(@"\r"); Regex r2 = new Regex(@"\n"); string message = r1.Replace(preparedResult.ExceptionMessage, ""); message = r2.Replace(message.Trim(), '\\' + "n"); string result = "Time: " + dateStr + " | " + threadOrRequestIdStr; if (preparedResult.ExceptionType == "Value") { result += " | Value: " + message; } else { result += " | Type: " + preparedResult.ExceptionType + " (Hash Code: " + preparedResult.ExceptionHash + ")" + " | Catched: " + (preparedResult.Catched ? "yes" : "no") + " | Message: " + message; if (preparedResult.CausedByType != null && preparedResult.CausedByType.Length > 0) result += " | Caused By: " + preparedResult.CausedByType + " (Hash Code: " + preparedResult.CausedByHash + ")"; } if (stackTraceStr.Length > 0) result += " | Callstack: " + stackTraceStr; if (headersStr.Length > 0) result += " | Request Headers: " + headersStr; return result; } private static string _renderDataTableRows (List<string[]> data, bool htmlOut = false, bool firstRowAsHead = false) { StringBuilder result = new StringBuilder(); if (data.Count == 0) return ""; if (htmlOut) { int index = 0; foreach (string[] rowData in data) { result.Append("<tr>"); for (int i = 0, l = rowData.Length; i < l; i += 1) { if (index == 0 && firstRowAsHead) { result.Append("<th>" + rowData[i] + "</th>"); } else if (data[0].Length == 2 && i == 0) { result.Append("<th>" + rowData[i] + "</th>"); } else { result.Append("<td>" + rowData[i] + "</td>"); } } result.Append("</tr>"); index++; } } else { if (data.Count > 0 && data[0].Length == 2) { Dictionary<string, string> dataDct = new Dictionary<string, string>(); foreach (string[] dataItem in data) dataDct.Add(dataItem[0], dataItem[1]); result.Append(new JavaScriptSerializer().Serialize(dataDct)); } else { result.Append(new JavaScriptSerializer().Serialize(data)); } } return result.ToString(); } private static string _renderHtmlDataTable (string title, string tableRows) { return @"<div class=""table""><b class=""title"">" + title + @"</b><div class=""data"" ><table>" + tableRows + "</table></div></div>"; } private static string _renderStackTrace (List<StackTraceItem> stackTrace, bool htmlOut, StackTraceFormat format, bool fileSystemLog = true) { List<string> result = new List<string>(); int counter = 0; int[] textLengths = new int[] { 0, 0}; if (format != StackTraceFormat.Html) { List<StackTraceItem> newStackTrace = new List<StackTraceItem>(); StackTraceItem newStackTraceItem; foreach (StackTraceItem stackTraceItem in stackTrace) { newStackTraceItem = new StackTraceItem(stackTraceItem); if (newStackTraceItem.Method.Length > textLengths[0]) textLengths[0] = newStackTraceItem.Method.Length; if (htmlOut && format == StackTraceFormat.Json && newStackTraceItem.File.ToString().Length > 0) { newStackTraceItem.File = new string[] { newStackTraceItem.File.ToString(), Tools.RelativeSourceFullPath(newStackTraceItem.File.ToString()) }; } else { newStackTraceItem.File = Tools.RelativeSourceFullPath(newStackTraceItem.File.ToString()); } if (newStackTraceItem.File.ToString().Length > textLengths[1]) textLengths[1] = newStackTraceItem.File.ToString().Length; newStackTrace.Add(newStackTraceItem); } stackTrace = newStackTrace; } foreach (StackTraceItem stackTraceItem in stackTrace) { result.Add( Exceptions._renderStackTraceLine(stackTraceItem, format, textLengths) ); counter++; } if (format == StackTraceFormat.Html) { string resultStr = @"<div class=""table callstack""><b class=""title"">Call Stack:</b>" + @"<div class=""calls""><div><table>" + String.Join("", result.ToArray()) + "</table></div></div>" + "</div>"; return resultStr; } else if (format == StackTraceFormat.Text) { return System.Environment.NewLine + " " + String.Join(System.Environment.NewLine + " ", result.ToArray()); } else if (format == StackTraceFormat.Json) { return "[" + String.Join(",", result.ToArray()) + "]"; } return ""; } private static string _renderStackTraceLine(StackTraceItem stackTraceItem, StackTraceFormat format, int[] textLengths) { string result = ""; string fileNameLink = ""; bool fileDefined = stackTraceItem.File.ToString().Length > 0 && stackTraceItem.Line.ToString().Length > 0; if (format == StackTraceFormat.Html) { if (fileDefined) { fileNameLink = @"<a href=""editor://open/?file=" + HttpUtility.UrlEncode(stackTraceItem.File.ToString()) + "&line=" + stackTraceItem.Line + "&editor=" + Tools.Editor + @""">" + Tools.RelativeSourceFullPath(stackTraceItem.File.ToString()) + "</a>"; } result = (fileNameLink.Length > 0 ? @"<tr class=""known""> " : "<tr>") + @"<td class=""file"">" + fileNameLink + "</td>" + @"<td class=""line"">" + stackTraceItem.Line + "</td>" + @"<td class=""method""><i>" + stackTraceItem.Method.Replace(".", "&#8203;.") + " </i></td>" + "</tr>"; } else if (format == StackTraceFormat.Text) { if (fileDefined) { result = stackTraceItem.Method + Tools.SpaceIndent(textLengths[0] - stackTraceItem.Method.Length, false) + " " + stackTraceItem.File + Tools.SpaceIndent(textLengths[1] - stackTraceItem.File.ToString().Length, false) + " " + stackTraceItem.Line; } else { result = stackTraceItem.Method + Tools.SpaceIndent(textLengths[0] - stackTraceItem.Method.Length, false) + " " + stackTraceItem.File; } } else if (format == StackTraceFormat.Json) { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); result = "{method:" + jsonSerializer.Serialize(stackTraceItem.Method); if (fileDefined) { result += ",file:" + jsonSerializer.Serialize(stackTraceItem.File); result += ",line:" + stackTraceItem.Line; } result += "}"; } return result; } private static string _renderHtmlResponseFooterInfo () { return @"<div class=""version"">" + "<b>.NET Framework Version:</b> " + Environment.Version.ToString() + "; " + "<b>ASP.NET Version:</b> " + typeof(Page).Assembly.GetName().Version.ToString() + "; " + "<b>Server Version:</b> " + HttpContext.Current.Request.ServerVariables["SERVER_SOFTWARE"] + "; " + "<b>Desharp Version:</b> " + Debug.Version.ToString() + "</div>"; } } }
namespace Tools.Tests { using System; using System.Collections.Generic; using Moq; using NUnit.Framework; using PokerTell.UnitTests; using PokerTell.UnitTests.Tools; using Tools.Interfaces; public class ThatItemsPagesManager { const int FirstItem = 0; const int SecondItem = 1; const int ThirdItem = 2; IItemsPagesManager<int> _manager; StubBuilder _stub; [SetUp] public void _Init() { _stub = new StubBuilder(); _manager = new ItemsPagesManager<int>(); } [Test] public void CanNavigateBackward_EmptyList_ReturnsFalse() { const uint itemsPerPage = 1; IList<int> allItems = new List<int>(); _manager .InitializeWith(itemsPerPage, allItems); Assert.That(_manager.CanNavigateBackward, Is.False); } [Test] public void CanNavigateBackward_OnePageCurrentPageIsFirstPage_ReturnsFalse() { const uint itemsPerPage = 1; IList<int> allItems = new List<int> { _stub.Some<int>() }; _manager .InitializeWith(itemsPerPage, allItems); Assert.That(_manager.CanNavigateBackward, Is.False); } [Test] public void CanNavigateBackward_TwoPagesCurrentPageIsFirstPage_ReturnsFalse() { const uint itemsPerPage = 1; IList<int> allItems = new List<int> { _stub.Some<int>(), _stub.Some<int>() }; _manager .InitializeWith(itemsPerPage, allItems); Assert.That(_manager.CanNavigateBackward, Is.False); } [Test] public void CanNavigateBackward_TwoPagesCurrentPageIsSecondPage_ReturnsTrue() { const uint itemsPerPage = 1; IList<int> allItems = new List<int> { _stub.Some<int>(), _stub.Some<int>() }; _manager .InitializeWith(itemsPerPage, allItems) .NavigateToPage(2); Assert.That(_manager.CanNavigateBackward, Is.True); } [Test] public void CanNavigateForward_OnePageCurrentPageIsLastPage_ReturnsFalse() { const uint itemsPerPage = 1; IList<int> allItems = new List<int> { _stub.Some<int>() }; _manager .InitializeWith(itemsPerPage, allItems); Assert.That(_manager.CanNavigateForward, Is.False); } [Test] public void CanNavigateForward_TwoPagesCurrentPageIsFirst_ReturnsTrue() { const uint itemsPerPage = 1; IList<int> allItems = new List<int> { _stub.Some<int>(), _stub.Some<int>() }; _manager .InitializeWith(itemsPerPage, allItems); Assert.That(_manager.CanNavigateForward, Is.True); } [Test] public void CanNavigateForward_TwoPagesCurrentPageIsSecond_ReturnsFalse() { const uint itemsPerPage = 1; IList<int> allItems = new List<int> { _stub.Some<int>(), _stub.Some<int>() }; _manager .InitializeWith(itemsPerPage, allItems) .NavigateToPage(2); Assert.That(_manager.CanNavigateForward, Is.False); } [Test] public void FilterItems_AllItemsMatchFilter_ShownItemsContainsAllItems() { IList<int> allItems = new List<int> { FirstItem, SecondItem }; _manager .InitializeWith((uint)_stub.Valid(For.NumberOfItems, 1), allItems) .FilterItems(f => true); Assert.That(_manager.AllShownItems, Is.EqualTo(allItems)); } [Test] public void FilterItems_CurrentPageIsSecondAllItemsMatchFilter_CurrentPageIsSetToFirstPage() { IList<int> allItems = new List<int> { FirstItem, SecondItem }; _manager .InitializeWith((uint)_stub.Valid(For.NumberOfItems, 1), allItems) .NavigateToPage(2) .FilterItems(f => true); Assert.That(_manager.CurrentPage, Is.EqualTo(1)); } [Test] public void FilterItems_CurrentPageIsSecondAllItemsMatchFilter_NavigatesToFirstPage() { IList<int> allItems = new List<int> { FirstItem, SecondItem }; var expectedItems = new List<int> { FirstItem }; _manager .InitializeWith((uint)_stub.Valid(For.NumberOfItems, 1), allItems) .NavigateToPage(2) .FilterItems(f => true); Assert.That(_manager.ItemsOnCurrentPage, Is.EqualTo(expectedItems)); } [Test] public void FilterItems_CurrentPageIsSecondNoItemMatchesFilter_CurrentPageIsSetToFirstPage() { IList<int> allItems = new List<int> { FirstItem, SecondItem }; _manager .InitializeWith((uint)_stub.Valid(For.NumberOfItems, 1), allItems) .NavigateToPage(2) .FilterItems(f => false); Assert.That(_manager.CurrentPage, Is.EqualTo(1)); } [Test] public void FilterItems_NoItemMatchesFilter_SetsNumberOfPagesToOne() { IList<int> allItems = new List<int> { FirstItem, SecondItem }; _manager .InitializeWith((uint)_stub.Valid(For.NumberOfItems, 1), allItems) .NavigateToPage(2) .FilterItems(f => false); Assert.That(_manager.CurrentPage, Is.EqualTo(1)); } [Test] public void FilterItems_NoItemMatchesFilter_ShownItemsIsEmpty() { IList<int> allItems = new List<int> { FirstItem, SecondItem }; _manager .InitializeWith((uint)_stub.Valid(For.NumberOfItems, 1), allItems) .FilterItems(f => false); Assert.That(_manager.AllShownItems.Count, Is.EqualTo(0)); } [Test] public void FilterItems_OneOfThreeItemMatchesFilter_ShownItemsContainsAllItemsThatMatchedFilter() { IList<int> allItems = new List<int> { FirstItem, SecondItem, ThirdItem }; _manager .InitializeWith((uint)_stub.Valid(For.NumberOfItems, 1), allItems) .FilterItems(f => f.Equals(SecondItem)); IList<int> expectedItems = new List<int> { SecondItem }; Assert.That(_manager.AllShownItems, Is.EqualTo(expectedItems)); } [Test] public void InitializeWith_EmptyList_CanNavigateForwardIsFalse() { const uint itemsPerPage = 1; IList<int> allItems = new List<int>(); _manager .InitializeWith(itemsPerPage, allItems); Assert.That(_manager.CanNavigateForward, Is.False); } [Test] public void InitializeWith_EmptyList_SetsNumberOfPagesToZero() { const uint itemsPerPage = 1; IList<int> allItems = new List<int>(); const int expectedNumberOfPages = 0; _manager .InitializeWith(itemsPerPage, allItems); Assert.That(_manager.NumberOfPages, Is.EqualTo(expectedNumberOfPages)); } [Test] public void InitializeWith_ItemsOnPageIsOneAndListHasOneItem_SetsNumberOfPagesToOne() { const uint itemsPerPage = 1; IList<int> allItems = new List<int> { _stub.Some<int>() }; const int expectedNumberOfPages = 1; _manager .InitializeWith(itemsPerPage, allItems); Assert.That(_manager.NumberOfPages, Is.EqualTo(expectedNumberOfPages)); } [Test] public void InitializeWith_ItemsOnPageIsOneAndListHasThreeItems_SetsNumberOfPagesToThree() { const uint itemsPerPage = 1; IList<int> allItems = new List<int> { _stub.Some<int>(), _stub.Some<int>(), _stub.Some<int>() }; const int expectedNumberOfPages = 3; _manager .InitializeWith(itemsPerPage, allItems); Assert.That(_manager.NumberOfPages, Is.EqualTo(expectedNumberOfPages)); } [Test] public void InitializeWith_ItemsOnPageIsTwoAndListHasThreeItems_SetsNumberOfPagesToTwo() { const uint itemsPerPage = 2; IList<int> allItems = new List<int> { _stub.Some<int>(), _stub.Some<int>(), _stub.Some<int>() }; const int expectedNumberOfPages = 2; _manager .InitializeWith(itemsPerPage, allItems); Assert.That(_manager.NumberOfPages, Is.EqualTo(expectedNumberOfPages)); } [Test] public void NavigateToFirstPage_ContainsOnePageAndShouldShowIsAlwaysTrue_NavigatesToToFirstPage() { const uint itemsPerPage = 1; IList<int> itemsOnFirstPage = new List<int> { FirstItem }; IList<int> allItems = new List<int> { FirstItem }; _manager .InitializeWith(itemsPerPage, allItems) .NavigateToPage(1); Assert.That(_manager.ItemsOnCurrentPage, Is.EqualTo(itemsOnFirstPage)); } [Test] public void NavigateToFirstPage_ListIsEmpty_SetsShownListToEmpty() { const uint itemsPerPage = 1; IList<int> allItems = new List<int>(); _manager .InitializeWith(itemsPerPage, allItems) .NavigateToPage(1); Assert.That(_manager.ItemsOnCurrentPage.Count, Is.EqualTo(0)); } [Test] public void NavigateToSecondPage_ContainsOnePage_NavigatesToFirstPage() { const uint itemsPerPage = 1; IList<int> itemsOnFirstPage = new List<int> { FirstItem }; IList<int> allItems = new List<int> { FirstItem }; _manager .InitializeWith(itemsPerPage, allItems) .NavigateToPage(2); Assert.That(_manager.ItemsOnCurrentPage, Is.EqualTo(itemsOnFirstPage)); } [Test] public void NavigateToSecondPage_ContainsTwoPages_NavigatesToSecondPage() { const uint itemsPerPage = 1; IList<int> itemsOnSecondPage = new List<int> { SecondItem }; IList<int> allItems = new List<int> { FirstItem, SecondItem }; _manager .InitializeWith(itemsPerPage, allItems) .NavigateToPage(2); Assert.That(_manager.ItemsOnCurrentPage, Is.EqualTo(itemsOnSecondPage)); } [Test] public void BinaryDeserialize_Serialized_RestoresItemsPerPage() { const uint itemsPerPage = 1; _manager .InitializeWith(itemsPerPage, new List<int>()); Assert.That(_manager.BinaryDeserializedInMemory().ItemsPerPage, Is.EqualTo(_manager.ItemsPerPage)); } [Test] public void BinaryDeserialize_Serialized_RestoresAllItems() { const uint someItemsPerPage = 1; IList<int> allItems = new List<int> { FirstItem, SecondItem }; _manager .InitializeWith(someItemsPerPage, allItems); Assert.That(_manager.BinaryDeserializedInMemory().AllItems, Is.EqualTo(_manager.AllItems)); } [Test] public void BinaryDeserialize_Serialized_RestoresAllShownItems() { const uint someItemsPerPage = 1; IList<int> allItems = new List<int> { FirstItem, SecondItem }; _manager .InitializeWith(someItemsPerPage, allItems); Assert.That(_manager.BinaryDeserializedInMemory().AllShownItems, Is.EqualTo(_manager.AllShownItems)); } [Test] public void BinaryDeserialize_Serialized_RestoresNumberOfPages() { const uint someItemsPerPage = 1; IList<int> allItems = new List<int> { FirstItem, SecondItem }; _manager .InitializeWith(someItemsPerPage, allItems); Assert.That(_manager.BinaryDeserializedInMemory().NumberOfPages, Is.EqualTo(_manager.NumberOfPages)); } [Test] public void BinaryDeserialize_Serialized_RestoresCurrentPage() { const uint someItemsPerPage = 1; IList<int> allItems = new List<int> { FirstItem, SecondItem }; _manager .InitializeWith(someItemsPerPage, allItems) .NavigateToPage(2); Assert.That(_manager.BinaryDeserializedInMemory().CurrentPage, Is.EqualTo(_manager.CurrentPage)); } [Test] public void BinaryDeserialize_Serialized_RestoresItemsOnCurrentPage() { const uint someItemsPerPage = 1; IList<int> allItems = new List<int> { FirstItem, SecondItem }; _manager .InitializeWith(someItemsPerPage, allItems) .NavigateToPage(2); Assert.That(_manager.BinaryDeserializedInMemory().ItemsOnCurrentPage, Is.EqualTo(_manager.ItemsOnCurrentPage)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ServiceModel.Description { using System.Collections.Generic; using System.Globalization; using System.Net; using System.Reflection; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.Threading; using Microsoft.Xml; using Microsoft.Xml.Schema; using WsdlNS = System.Web.Services.Description; // the description/metadata "mix-in" public class ServiceMetadataExtension { private const string BaseAddressPattern = "{%BaseAddress%}"; internal abstract class WriteFilter : XmlDictionaryWriter { internal XmlWriter Writer; public abstract WriteFilter CloneWriteFilter(); public override void Close() { this.Writer.Close(); } public override void Flush() { this.Writer.Flush(); } public override string LookupPrefix(string ns) { return this.Writer.LookupPrefix(ns); } public override void WriteBase64(byte[] buffer, int index, int count) { this.Writer.WriteBase64(buffer, index, count); } public override void WriteCData(string text) { this.Writer.WriteCData(text); } public override void WriteCharEntity(char ch) { this.Writer.WriteCharEntity(ch); } public override void WriteChars(char[] buffer, int index, int count) { this.Writer.WriteChars(buffer, index, count); } public override void WriteComment(string text) { this.Writer.WriteComment(text); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { this.Writer.WriteDocType(name, pubid, sysid, subset); } public override void WriteEndAttribute() { this.Writer.WriteEndAttribute(); } public override void WriteEndDocument() { this.Writer.WriteEndDocument(); } public override void WriteEndElement() { this.Writer.WriteEndElement(); } public override void WriteEntityRef(string name) { this.Writer.WriteEntityRef(name); } public override void WriteFullEndElement() { this.Writer.WriteFullEndElement(); } public override void WriteProcessingInstruction(string name, string text) { this.Writer.WriteProcessingInstruction(name, text); } public override void WriteRaw(string data) { this.Writer.WriteRaw(data); } public override void WriteRaw(char[] buffer, int index, int count) { this.Writer.WriteRaw(buffer, index, count); } public override void WriteStartAttribute(string prefix, string localName, string ns) { this.Writer.WriteStartAttribute(prefix, localName, ns); } public override void WriteStartDocument(bool standalone) { this.Writer.WriteStartDocument(standalone); } public override void WriteStartDocument() { this.Writer.WriteStartDocument(); } public override void WriteStartElement(string prefix, string localName, string ns) { this.Writer.WriteStartElement(prefix, localName, ns); } public override WriteState WriteState { get { return this.Writer.WriteState; } } public override void WriteString(string text) { this.Writer.WriteString(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { this.Writer.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteWhitespace(string ws) { this.Writer.WriteWhitespace(ws); } } private class LocationUpdatingWriter : WriteFilter { private readonly string _oldValue; private readonly string _newValue; // passing null for newValue filters any string with oldValue as a prefix rather than replacing internal LocationUpdatingWriter(string oldValue, string newValue) { _oldValue = oldValue; _newValue = newValue; } public override WriteFilter CloneWriteFilter() { return new LocationUpdatingWriter(_oldValue, _newValue); } public override void WriteString(string text) { if (_newValue != null) text = text.Replace(_oldValue, _newValue); else if (text.StartsWith(_oldValue, StringComparison.Ordinal)) text = String.Empty; base.WriteString(text); } } private class DynamicAddressUpdateWriter : WriteFilter { private readonly string _oldHostName; private readonly string _newHostName; private readonly string _newBaseAddress; private readonly bool _removeBaseAddress; private readonly string _requestScheme; private readonly int _requestPort; private readonly IDictionary<string, int> _updatePortsByScheme; internal DynamicAddressUpdateWriter(Uri listenUri, string requestHost, int requestPort, IDictionary<string, int> updatePortsByScheme, bool removeBaseAddress) : this(listenUri.Host, requestHost, removeBaseAddress, listenUri.Scheme, requestPort, updatePortsByScheme) { _newBaseAddress = UpdateUri(listenUri).ToString(); } private DynamicAddressUpdateWriter(string oldHostName, string newHostName, string newBaseAddress, bool removeBaseAddress, string requestScheme, int requestPort, IDictionary<string, int> updatePortsByScheme) : this(oldHostName, newHostName, removeBaseAddress, requestScheme, requestPort, updatePortsByScheme) { _newBaseAddress = newBaseAddress; } private DynamicAddressUpdateWriter(string oldHostName, string newHostName, bool removeBaseAddress, string requestScheme, int requestPort, IDictionary<string, int> updatePortsByScheme) { _oldHostName = oldHostName; _newHostName = newHostName; _removeBaseAddress = removeBaseAddress; _requestScheme = requestScheme; _requestPort = requestPort; _updatePortsByScheme = updatePortsByScheme; } public override WriteFilter CloneWriteFilter() { return new DynamicAddressUpdateWriter(_oldHostName, _newHostName, _newBaseAddress, _removeBaseAddress, _requestScheme, _requestPort, _updatePortsByScheme); } public override void WriteString(string text) { Uri uri; if (_removeBaseAddress && text.StartsWith(ServiceMetadataExtension.BaseAddressPattern, StringComparison.Ordinal)) { text = string.Empty; } else if (!_removeBaseAddress && text.Contains(ServiceMetadataExtension.BaseAddressPattern)) { text = text.Replace(ServiceMetadataExtension.BaseAddressPattern, _newBaseAddress); } else if (Uri.TryCreate(text, UriKind.Absolute, out uri)) { Uri newUri = UpdateUri(uri); if (newUri != null) { text = newUri.ToString(); } } base.WriteString(text); } public void UpdateUri(ref Uri uri, bool updateBaseAddressOnly = false) { Uri newUri = UpdateUri(uri, updateBaseAddressOnly); if (newUri != null) { uri = newUri; } } private Uri UpdateUri(Uri uri, bool updateBaseAddressOnly = false) { // Ordinal comparison okay: we're filtering for auto-generated URIs which will // always be based off the listenURI, so always match in case if (uri.Host != _oldHostName) { return null; } UriBuilder result = new UriBuilder(uri); result.Host = _newHostName; if (!updateBaseAddressOnly) { int port; if (uri.Scheme == _requestScheme) { port = _requestPort; } else if (!_updatePortsByScheme.TryGetValue(uri.Scheme, out port)) { return null; } result.Port = port; } return result.Uri; } } } }
using System; using MaterialComponents.MaterialAppBar; using MaterialComponents.MaterialFlexibleHeader; using UIKit; using Foundation; using CoreGraphics; using CoreFoundation; using CoreAnimation; using MaterialComponents; using MaterialComponents.MaterialAnimationTiming; namespace Pesto.Views { public delegate void DidSelectCellDelegate(PestoCardCollectionViewCell cell, Action completion); public class PestoViewController : MDCFlexibleHeaderContainerViewController, IUIViewControllerAnimatedTransitioning, IUIViewControllerTransitioningDelegate { MDCAppBar appBar; public PestoCollectionViewController collectionViewController; UIImageView zoomableView; UIView zoomableCardView; public static PestoViewController InitializeWithController() { var layout = new UICollectionViewFlowLayout(); layout.MinimumInteritemSpacing = 0f; var sectonInsect = 2f; layout.SectionInset = new UIEdgeInsets(sectonInsect, sectonInsect, sectonInsect, sectonInsect); var collectionVC = new PestoCollectionViewController((UICollectionViewLayout)layout); var result = new PestoViewController(collectionVC); result.collectionViewController = collectionVC; result.collectionViewController.ShadowDelegate = collectionVC.ShadowIntensityChangeBlock; result.collectionViewController.FlexHeaderContainerVC = result; result.collectionViewController.Delegate = result.DidSelectCell; result.appBar = new MDCAppBar(); result.AddChildViewController(result.appBar.HeaderViewController); result.appBar.HeaderViewController.HeaderView.BackgroundColor = UIColor.Clear; result.appBar.NavigationBar.TintColor = UIColor.White; UIImage icon = UIImage.FromBundle("Settings"); UIBarButtonItem menuButton = new UIBarButtonItem(icon, UIBarButtonItemStyle.Done, result.DidSelectSettings); result.NavigationItem.RightBarButtonItem = menuButton; return result; } protected PestoViewController(IntPtr handle) : base(handle) { // Note: this .ctor should not contain any initialization logic. } public PestoViewController() : base () { } [Export("initWithContentViewController:")] public PestoViewController(UIViewController controller) : base(controller) { Console.WriteLine("Initialise with Controller"); } public override void ViewDidLoad() { base.ViewDidLoad(); appBar.AddSubviewsToParent(); zoomableCardView = new UIView(CGRect.Empty); zoomableCardView.BackgroundColor = UIColor.White; View.AddSubview(zoomableCardView); zoomableView = new UIImageView(CGRect.Empty); zoomableView.BackgroundColor = UIColor.LightGray; zoomableView.ContentMode = UIViewContentMode.ScaleAspectFill; View.AddSubview(zoomableView); } public void DidSelectCell(PestoCardCollectionViewCell cell, Action completion) { Console.Write("Ooops! Sorry:)"); zoomableView.Frame = new CGRect(cell.Frame.X, cell.Frame.Y - collectionViewController.scrollOffsetY, cell.Frame.Size.Width, cell.Frame.Size.Height - 50f); zoomableCardView.Frame = new CGRect(cell.Frame.X, cell.Frame.Y - collectionViewController.scrollOffsetY, cell.Frame.Size.Width, cell.Frame.Size.Height); DispatchQueue.MainQueue.DispatchAsync(() => { zoomableView.Image = cell.image; UIView.AnimateNotify(PestoDetail.AnimationDuration, 0, UIViewAnimationOptions.CurveEaseOut, () => { var quantumEaseInOut = MDC_CAMediaTimingFunction.Mdc_functionWithType(MDCAnimationTimingFunction.EaseInOut); CATransaction.AnimationTimingFunction = quantumEaseInOut; var zoomFrame = new CGRect(0, 0, View.Bounds.Size.Width, 320f); zoomableView.Frame = zoomFrame; zoomableCardView.Frame = View.Bounds; }, new UICompletionHandler((bool finished) => { var detailVC = new PestoDetailViewController(); detailVC.imageView.Image = cell.image; detailVC.Title = cell.title; detailVC.descText = cell.descText; detailVC.iconImageName = cell.iconImageName; PresentViewController(detailVC, false, () => { this.zoomableView.Frame = CGRect.Empty; this.zoomableCardView.Frame = CGRect.Empty; completion(); }); })); }); } public IUIViewControllerAnimatedTransitioning GetAnimationControllerForPresentedController(UIViewController presented, UIViewController presenting, UIViewController source) { return null; } public IUIViewControllerAnimatedTransitioning GetAnimationControllerForDismissedController(UIViewController dismissed) { return this; } public void AnimateTransition(IUIViewControllerContextTransitioning transitionContext) { var fromController = transitionContext.GetViewControllerForKey( UITransitionContext.FromViewControllerKey); var toController = transitionContext.GetViewControllerForKey( UITransitionContext.ToViewControllerKey); if (fromController is PestoDetailViewController & toController is PestoViewController) { CGRect detailFrame = fromController.View.Frame; detailFrame.Y = this.View.Frame.Size.Height; UIView.AnimateNotify(TransitionDuration(transitionContext), 0.5f, UIViewAnimationOptions.CurveEaseIn, () => { fromController.View.Frame = detailFrame; }, new UICompletionHandler((bool finished) => { if (fromController.View != null) { fromController.View.RemoveFromSuperview(); } transitionContext.CompleteTransition(true); })); } } public double TransitionDuration(IUIViewControllerContextTransitioning transitionContext) { return 0.2; } public void DidSelectSettings(object sender, EventArgs args) { var settingsVC = new PestoSettingsViewController(); settingsVC.Title = "Settings"; var white = UIColor.White; var teal = new UIColor(0f, 0.67f, 0.55f, 1f); var rightBarButton = new UIBarButtonItem("Done", UIBarButtonItemStyle.Done, CloseViewController); rightBarButton.TintColor = white; settingsVC.NavigationItem.RightBarButtonItem = rightBarButton; var navVC = new UINavigationController(settingsVC); navVC.NavigationBar.BarTintColor = teal; navVC.NavigationBar.TitleTextAttributes = new UIStringAttributes() { ForegroundColor = white }; navVC.NavigationBar.Translucent = false; navVC.NavigationBarHidden = true; PresentViewController(navVC, true, null); } public void CloseViewController(object sender, EventArgs args) { DismissViewController(true, null); } } }
// // HMACRIPEMD160Test.cs - NUnit Test Cases for HMACRIPEMD160 // http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html // // Author: // Sebastien Pouliot (sebastien@ximian.com) // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // 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. // #if NET_2_0 using NUnit.Framework; using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace MonoTests.System.Security.Cryptography { [TestFixture] public class HMACRIPEMD160Test : Assertion { protected HMACRIPEMD160 hmac; // because most crypto stuff works with byte[] buffers static public void AssertEquals (string msg, byte[] array1, byte[] array2) { if ((array1 == null) && (array2 == null)) return; if (array1 == null) Fail (msg + " -> First array is NULL"); if (array2 == null) Fail (msg + " -> Second array is NULL"); bool a = (array1.Length == array2.Length); if (a) { for (int i = 0; i < array1.Length; i++) { if (array1 [i] != array2 [i]) { a = false; break; } } } if (array1.Length > 0) { msg += " -> Expected " + BitConverter.ToString (array1, 0); msg += " is different than " + BitConverter.ToString (array2, 0); } Assert (msg, a); } [SetUp] public void SetUp () { hmac = new HMACRIPEMD160 (); } static byte[] key1 = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x01, 0x23, 0x45, 0x67 }; // HMACRIPEMD160 (key1, "") = cf387677bfda8483e63b57e06c3b5ecd8b7fc055 [Test] public void HMACRIPEMD160_Key1_Test1 () { byte[] result = { 0xcf, 0x38, 0x76, 0x77, 0xbf, 0xda, 0x84, 0x83, 0xe6, 0x3b, 0x57, 0xe0, 0x6c, 0x3b, 0x5e, 0xcd, 0x8b, 0x7f, 0xc0, 0x55 }; byte[] input = new byte [0]; string testName = "HMACRIPEMD160 Key #1 Test #1"; hmac.Key = key1; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); // N/A RIPEMD160_e (testName, hmac, input, result); } // HMACRIPEMD160 ("a") = 0d351d71b78e36dbb7391c810a0d2b6240ddbafc [Test] public void HMACRIPEMD160_Key1_Test2 () { byte[] result = { 0x0d, 0x35, 0x1d, 0x71, 0xb7, 0x8e, 0x36, 0xdb, 0xb7, 0x39, 0x1c, 0x81, 0x0a, 0x0d, 0x2b, 0x62, 0x40, 0xdd, 0xba, 0xfc }; byte[] input = Encoding.Default.GetBytes ("a"); string testName = "HMACRIPEMD160 Key #1 Test #2"; hmac.Key = key1; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // HMACRIPEMD160 ("abc") = f7ef288cb1bbcc6160d76507e0a3bbf712fb67d6 [Test] public void HMACRIPEMD160_Key1_Test3 () { byte[] result = { 0xf7, 0xef, 0x28, 0x8c, 0xb1, 0xbb, 0xcc, 0x61, 0x60, 0xd7, 0x65, 0x07, 0xe0, 0xa3, 0xbb, 0xf7, 0x12, 0xfb, 0x67, 0xd6 }; byte[] input = Encoding.Default.GetBytes ("abc"); string testName = "HMACRIPEMD160 Key #1 Test #3"; hmac.Key = key1; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 ("message digest") = f83662cc8d339c227e600fcd636c57d2571b1c34 [Test] public void HMACRIPEMD160_Key1_Test4 () { byte[] result = { 0xf8, 0x36, 0x62, 0xcc, 0x8d, 0x33, 0x9c, 0x22, 0x7e, 0x60, 0x0f, 0xcd, 0x63, 0x6c, 0x57, 0xd2, 0x57, 0x1b, 0x1c, 0x34 }; byte[] input = Encoding.Default.GetBytes ("message digest"); string testName = "HMACRIPEMD160 Key #1 Test #4"; hmac.Key = key1; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 ("abcdefghijklmnopqrstuvwxyz") = 843d1c4eb880ac8ac0c9c95696507957d0155ddb [Test] public void HMACRIPEMD160_Key1_Test5 () { byte[] result = { 0x84, 0x3d, 0x1c, 0x4e, 0xb8, 0x80, 0xac, 0x8a, 0xc0, 0xc9, 0xc9, 0x56, 0x96, 0x50, 0x79, 0x57, 0xd0, 0x15, 0x5d, 0xdb }; byte[] input = Encoding.Default.GetBytes ("abcdefghijklmnopqrstuvwxyz"); string testName = "HMACRIPEMD160 Key #1 Test #5"; hmac.Key = key1; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = // 60f5ef198a2dd5745545c1f0c47aa3fb5776f881 [Test] public void HMACRIPEMD160_Key1_Test6 () { byte[] result = { 0x60, 0xf5, 0xef, 0x19, 0x8a, 0x2d, 0xd5, 0x74, 0x55, 0x45, 0xc1, 0xf0, 0xc4, 0x7a, 0xa3, 0xfb, 0x57, 0x76, 0xf8, 0x81 }; byte[] input = Encoding.Default.GetBytes ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); string testName = "HMACRIPEMD160 Key #1 Test #6"; hmac.Key = key1; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = // b0e20b6e3116640286ed3a87a5713079b21f5189 [Test] public void HMACRIPEMD160_Key1_Test7 () { byte[] result = { 0xe4, 0x9c, 0x13, 0x6a, 0x9e, 0x56, 0x27, 0xe0, 0x68, 0x1b, 0x80, 0x8a, 0x3b, 0x97, 0xe6, 0xa6, 0xe6, 0x61, 0xae, 0x79 }; byte[] input = Encoding.Default.GetBytes ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"); string testName = "HMACRIPEMD160 Key #1 Test #7"; hmac.Key = key1; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 ("123456789012345678901234567890123456789012345678901234567890123456 // 78901234567890") = 9b752e45573d4b39f4dbd3323cab82bf63326bfb [Test] public void HMACRIPEMD160_Key1_Test8 () { byte[] result = { 0x31, 0xbe, 0x3c, 0xc9, 0x8c, 0xee, 0x37, 0xb7, 0x9b, 0x06, 0x19, 0xe3, 0xe1, 0xc2, 0xbe, 0x4f, 0x1a, 0xa5, 0x6e, 0x6c }; byte[] input = Encoding.Default.GetBytes ("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); string testName = "HMACRIPEMD160 Key #1 Test #8"; hmac.Key = key1; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 (1000000 x 'a') = 52783243c1697bdbe16d37f97f68f08325dc1528 [Test] public void HMACRIPEMD160_Key1_Test9 () { byte[] result = { 0xc2, 0xaa, 0x88, 0xc6, 0x40, 0x56, 0x58, 0xdc, 0x22, 0x5e, 0x48, 0x54, 0x88, 0x37, 0x1f, 0xb2, 0x43, 0x3f, 0xa7, 0x35 }; byte[] input = new byte [1000000]; for (int i = 0; i < 1000000; i++) input[i] = 0x61; // a string testName = "HMACRIPEMD160 Key #1 Test #9"; hmac.Key = key1; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } static byte[] key2 = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x11, 0x22, 0x33 }; // HMACRIPEMD160 (key2, "") = fe69a66c7423eea9c8fa2eff8d9dafb4f17a62f5 [Test] public void HMACRIPEMD160_Key2_Test1 () { byte[] result = { 0xfe, 0x69, 0xa6, 0x6c, 0x74, 0x23, 0xee, 0xa9, 0xc8, 0xfa, 0x2e, 0xff, 0x8d, 0x9d, 0xaf, 0xb4, 0xf1, 0x7a, 0x62, 0xf5 }; byte[] input = new byte [0]; string testName = "HMACRIPEMD160 Key #2 Test #1"; hmac.Key = key2; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); // N/A RIPEMD160_e (testName, hmac, input, result); } // HMACRIPEMD160 ("a") = 85743e899bc82dbfa36faaa7a25b7cfd372432cd [Test] public void HMACRIPEMD160_Key2_Test2 () { byte[] result = { 0x85, 0x74, 0x3e, 0x89, 0x9b, 0xc8, 0x2d, 0xbf, 0xa3, 0x6f, 0xaa, 0xa7, 0xa2, 0x5b, 0x7c, 0xfd, 0x37, 0x24, 0x32, 0xcd }; byte[] input = Encoding.Default.GetBytes ("a"); string testName = "HMACRIPEMD160 Key #2 Test #2"; hmac.Key = key2; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // HMACRIPEMD160 ("abc") = 6e4afd501fa6b4a1823ca3b10bd9aa0ba97ba182 [Test] public void HMACRIPEMD160_Key2_Test3 () { byte[] result = { 0x6e, 0x4a, 0xfd, 0x50, 0x1f, 0xa6, 0xb4, 0xa1, 0x82, 0x3c, 0xa3, 0xb1, 0x0b, 0xd9, 0xaa, 0x0b, 0xa9, 0x7b, 0xa1, 0x82 }; byte[] input = Encoding.Default.GetBytes ("abc"); string testName = "HMACRIPEMD160 Key #2 Test #3"; hmac.Key = key2; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 ("message digest") = 2e066e624badb76a184c8f90fba053330e650e92 [Test] public void HMACRIPEMD160_Key2_Test4 () { byte[] result = { 0x2e, 0x06, 0x6e, 0x62, 0x4b, 0xad, 0xb7, 0x6a, 0x18, 0x4c, 0x8f, 0x90, 0xfb, 0xa0, 0x53, 0x33, 0x0e, 0x65, 0x0e, 0x92 }; byte[] input = Encoding.Default.GetBytes ("message digest"); string testName = "HMACRIPEMD160 Key #2 Test #4"; hmac.Key = key2; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 ("abcdefghijklmnopqrstuvwxyz") = 07e942aa4e3cd7c04dedc1d46e2e8cc4c741b3d9 [Test] public void HMACRIPEMD160_Key2_Test5 () { byte[] result = { 0x07, 0xe9, 0x42, 0xaa, 0x4e, 0x3c, 0xd7, 0xc0, 0x4d, 0xed, 0xc1, 0xd4, 0x6e, 0x2e, 0x8c, 0xc4, 0xc7, 0x41, 0xb3, 0xd9 }; byte[] input = Encoding.Default.GetBytes ("abcdefghijklmnopqrstuvwxyz"); string testName = "HMACRIPEMD160 Key #2 Test #5"; hmac.Key = key2; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = // b6582318ddcfb67a53a67d676b8ad869aded629a [Test] public void HMACRIPEMD160_Key2_Test6 () { byte[] result = { 0xb6, 0x58, 0x23, 0x18, 0xdd, 0xcf, 0xb6, 0x7a, 0x53, 0xa6, 0x7d, 0x67, 0x6b, 0x8a, 0xd8, 0x69, 0xad, 0xed, 0x62, 0x9a }; byte[] input = Encoding.Default.GetBytes ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); string testName = "HMACRIPEMD160 Key #2 Test #6"; hmac.Key = key2; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = // f1be3ee877703140d34f97ea1ab3a07c141333e2 [Test] public void HMACRIPEMD160_Key2_Test7 () { byte[] result = { 0xf1, 0xbe, 0x3e, 0xe8, 0x77, 0x70, 0x31, 0x40, 0xd3, 0x4f, 0x97, 0xea, 0x1a, 0xb3, 0xa0, 0x7c, 0x14, 0x13, 0x33, 0xe2 }; byte[] input = Encoding.Default.GetBytes ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"); string testName = "HMACRIPEMD160 Key #2 Test #7"; hmac.Key = key2; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 ("123456789012345678901234567890123456789012345678901234567890123456 // 78901234567890") = 85f164703e61a63131be7e45958e0794123904f9 [Test] public void HMACRIPEMD160_Key2_Test8 () { byte[] result = { 0x85, 0xf1, 0x64, 0x70, 0x3e, 0x61, 0xa6, 0x31, 0x31, 0xbe, 0x7e, 0x45, 0x95, 0x8e, 0x07, 0x94, 0x12, 0x39, 0x04, 0xf9 }; byte[] input = Encoding.Default.GetBytes ("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); string testName = "HMACRIPEMD160 Key #2 Test #8"; hmac.Key = key2; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } // RIPEMD160 (1000000 x 'a') = 82a504a002ba6e6c67f3cd67cedb66dc169bab7a [Test] public void HMACRIPEMD160_Key2_Test9 () { byte[] result = { 0x82, 0xa5, 0x04, 0xa0, 0x02, 0xba, 0x6e, 0x6c, 0x67, 0xf3, 0xcd, 0x67, 0xce, 0xdb, 0x66, 0xdc, 0x16, 0x9b, 0xab, 0x7a }; byte[] input = new byte [1000000]; for (int i = 0; i < 1000000; i++) input[i] = 0x61; // a string testName = "HMACRIPEMD160 Key #2 Test #9"; hmac.Key = key2; HMACRIPEMD160_a (testName, hmac, input, result); HMACRIPEMD160_b (testName, hmac, input, result); HMACRIPEMD160_c (testName, hmac, input, result); HMACRIPEMD160_d (testName, hmac, input, result); HMACRIPEMD160_e (testName, hmac, input, result); } public void HMACRIPEMD160_a (string testName, HMACRIPEMD160 hmac, byte[] input, byte[] result) { byte[] output = hmac.ComputeHash (input); AssertEquals (testName + ".a.1", result, output); AssertEquals (testName + ".a.2", result, hmac.Hash); // required or next operation will still return old hash hmac.Initialize (); } public void HMACRIPEMD160_b (string testName, HMACRIPEMD160 hmac, byte[] input, byte[] result) { byte[] output = hmac.ComputeHash (input, 0, input.Length); AssertEquals (testName + ".b.1", result, output); AssertEquals (testName + ".b.2", result, hmac.Hash); // required or next operation will still return old hash hmac.Initialize (); } public void HMACRIPEMD160_c (string testName, HMACRIPEMD160 hmac, byte[] input, byte[] result) { MemoryStream ms = new MemoryStream (input); byte[] output = hmac.ComputeHash (ms); AssertEquals (testName + ".c.1", result, output); AssertEquals (testName + ".c.2", result, hmac.Hash); // required or next operation will still return old hash hmac.Initialize (); } public void HMACRIPEMD160_d (string testName, HMACRIPEMD160 hmac, byte[] input, byte[] result) { hmac.TransformFinalBlock (input, 0, input.Length); AssertEquals (testName + ".d", result, hmac.Hash); // required or next operation will still return old hash hmac.Initialize (); } public void HMACRIPEMD160_e (string testName, HMACRIPEMD160 hmac, byte[] input, byte[] result) { byte[] copy = new byte [input.Length]; for (int i=0; i < input.Length - 1; i++) hmac.TransformBlock (input, i, 1, copy, i); hmac.TransformFinalBlock (input, input.Length - 1, 1); AssertEquals (testName + ".e", result, hmac.Hash); // required or next operation will still return old hash hmac.Initialize (); } // none of those values changes for any implementation of RIPEMD160 [Test] public virtual void StaticInfo () { string className = hmac.ToString (); AssertEquals (className + ".HashSize", 160, hmac.HashSize); AssertEquals (className + ".InputBlockSize", 1, hmac.InputBlockSize); AssertEquals (className + ".OutputBlockSize", 1, hmac.OutputBlockSize); } } } #endif
/*************************************************************************** * PlaylistSource.cs * * Copyright (C) 2005-2006 Novell, Inc. * Written by Aaron Bockover <aaron@abock.org> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * 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.Data; using System.Collections; using System.Collections.Generic; #if !win32 using Mono.Unix; #else using Banshee.Winforms; #endif using Banshee.Base; using Banshee.Database; namespace Banshee.Sources { public class PlaylistSource : AbstractPlaylistSource { private static List<PlaylistSource> playlists = new List<PlaylistSource>(); private DbParameter<int> playlist_id_param = new DbParameter<int>("playlist_id"); public static IEnumerable<PlaylistSource> Playlists { get { return playlists; } } public static int PlaylistCount { get { return playlists.Count; } } private Queue<TrackInfo> remove_queue = new Queue<TrackInfo>(); private Queue<TrackInfo> append_queue = new Queue<TrackInfo>(); public override int Id { get { return id; } protected set { id = value; playlist_id_param.Value = id; } } public PlaylistSource() : this(0) { } public PlaylistSource(string name) : base(name, 500) { } public PlaylistSource(int id) : base(Catalog.GetString("New Playlist"), 500) { Id = id; if (id < 0) { return; } else if (id == 0) { CreateNewPlaylist(); } else { if (Globals.Library.IsLoaded) { LoadFromDatabase(); } else { Globals.Library.Reloaded += OnLibraryReloaded; } } Globals.Library.TrackRemoved += OnLibraryTrackRemoved; playlists.Add(this); } private void OnLibraryReloaded(object o, EventArgs args) { LoadFromDatabase(); } private void CreateNewPlaylist() { Id = Globals.Library.Db.Execute(new DbCommand( @"INSERT INTO Playlists VALUES (NULL, :playlist_name, -1, 0)", "playlist_name", Name )); } private void LoadFromDatabase() { Name = (string)Globals.Library.Db.QuerySingle(new DbCommand( "SELECT Name FROM Playlists WHERE PlaylistID = :playlist_id", playlist_id_param)); // check to see if ViewOrder has ever been set, if not, perform // a default ordering as a compatibility update if (Convert.ToInt32(Globals.Library.Db.QuerySingle(new DbCommand( @"SELECT COUNT(*) FROM PlaylistEntries WHERE PlaylistID = :playlist_id AND ViewOrder > 0", playlist_id_param))) <= 0) { Console.WriteLine("Performing compatibility update on playlist '{0}'", Name); Globals.Library.Db.Execute(new DbCommand( @"UPDATE PlaylistEntries SET ViewOrder = (ROWID - (SELECT COUNT(*) FROM PlaylistEntries WHERE PlaylistID < :playlist_id)) WHERE PlaylistID = :playlist_id", playlist_id_param )); } IDataReader reader = Globals.Library.Db.Query(new DbCommand( @"SELECT TrackID FROM PlaylistEntries WHERE PlaylistID = :playlist_id ORDER BY ViewOrder", playlist_id_param )); lock (TracksMutex) { while (reader.Read()) { tracks.Add(Globals.Library.Tracks[Convert.ToInt32(reader[0])]); } } reader.Dispose(); } protected override bool UpdateName(string oldName, string newName) { bool updated = false; if (newName != null) { if (newName.Length > 256) { newName = newName.Substring(0, 256); } if (oldName.Equals(newName)) { return false; } if (PlaylistUtil.PlaylistExists(newName)) { LogCore.Instance.PushWarning( Catalog.GetString("Cannot Rename Playlist"), Catalog.GetString("A playlist with this name already exists. Please choose another name.")); return false; } DbCommand command = new DbCommand( @"UPDATE Playlists SET Name = :playlist_name WHERE PlaylistID = :playlist_id", "playlist_name", newName, playlist_id_param ); try { Globals.Library.Db.Execute(command); Name = newName; updated =true; } catch (Exception) { updated =false; } } return updated; } public override void AddTrack(TrackInfo track) { if (track is LibraryTrackInfo) { lock (TracksMutex) { tracks.Add(track); append_queue.Enqueue(track); } OnUpdated(); } } public override void RemoveTrack(TrackInfo track) { lock (TracksMutex) { tracks.Remove(track); remove_queue.Enqueue(track); } } public override void SourceDrop(Source source) { if (source == this || !(source is PlaylistSource)) { return; } foreach (TrackInfo track in source.Tracks) { AddTrack(track); } } public override bool Unmap() { if (base.Unmap()) { Globals.Library.Db.Execute(new DbCommand( @"DELETE FROM PlaylistEntries WHERE PlaylistID = :playlist_id", playlist_id_param )); Globals.Library.Db.Execute(new DbCommand( @"DELETE FROM Playlists WHERE PlaylistID = :playlist_id", playlist_id_param )); append_queue.Clear(); remove_queue.Clear(); playlists.Remove(this); return true; } return false; } public override void Commit() { if (remove_queue.Count > 0) { lock (TracksMutex) { while (remove_queue.Count > 0) { TrackInfo track = remove_queue.Dequeue(); Globals.Library.Db.Execute(new DbCommand( @"DELETE FROM PlaylistEntries WHERE PlaylistID = :playlist_id AND TrackID = :track_id", "track_id", track.TrackId, playlist_id_param )); OnTrackRemoved(track); } } } if (append_queue.Count > 0) { lock (TracksMutex) { while (append_queue.Count > 0) { TrackInfo track = append_queue.Dequeue(); Globals.Library.Db.Execute(new DbCommand( @"INSERT INTO PlaylistEntries VALUES (NULL, :playlist_id, :track_id, ( SELECT CASE WHEN MAX(ViewOrder) THEN MAX(ViewOrder) + 1 ELSE 1 END FROM PlaylistEntries WHERE PlaylistID = :playlist_id) )", "track_id", track.TrackId, playlist_id_param )); OnTrackAdded(track); } } } } public override void Reorder(TrackInfo track, int position) { lock (TracksMutex) { int sql_position = 1; if (position > 0) { TrackInfo sibling = tracks[position]; if (sibling == track || sibling == null) { return; } sql_position = Convert.ToInt32(Globals.Library.Db.QuerySingle(new DbCommand( @"SELECT ViewOrder FROM PlaylistEntries WHERE PlaylistID = :playlist_id AND TrackID = :track_id LIMIT 1", "track_id", sibling.TrackId, playlist_id_param) )); } else if (tracks[position] == track) { return; } Globals.Library.Db.Execute(new DbCommand( @"UPDATE PlaylistEntries SET ViewOrder = ViewOrder + 1 WHERE PlaylistID = :playlist_id AND ViewOrder >= :sql_position", "sql_position", sql_position, playlist_id_param )); Globals.Library.Db.Execute(new DbCommand( @"UPDATE PlaylistEntries SET ViewOrder = :sql_position WHERE PlaylistID = :playlist_id AND TrackID = :track_id", "sql_position", sql_position, "track_id", track.TrackId, playlist_id_param )); tracks.Remove(track); tracks.Insert(position, track); } } private void OnLibraryTrackRemoved(object o, LibraryTrackRemovedArgs args) { if (args.Track != null) { if (tracks.Contains(args.Track)) { RemoveTrack(args.Track); if (Count == 0) { Unmap(); } else { Commit(); } } return; } else if (args.Tracks == null) { return; } int removed_count = 0; lock (TracksMutex) { foreach (TrackInfo track in args.Tracks) { if (tracks.Contains(track)) { tracks.Remove(track); remove_queue.Enqueue(track); removed_count++; } } } if (removed_count > 0) { if (Count == 0) { Unmap(); } else { Commit(); } } } public override int SortColumn { get { try { return Convert.ToInt32(Globals.Library.Db.QuerySingle(new DbCommand( @"SELECT SortColumn FROM Playlists WHERE PlaylistID = :playlist_id", playlist_id_param))); } catch { return base.SortColumn; } } set { try { Globals.Library.Db.Execute(new DbCommand( @"UPDATE Playlists SET SortColumn = :sort_column WHERE PlaylistID = :playlist_id", "sort_column", value, playlist_id_param)); } catch { base.SortColumn = value; } } } public override System.Windows.Forms.SortOrder SortType { get { try { return (System.Windows.Forms.SortOrder)Convert.ToInt32(Globals.Library.Db.QuerySingle(new DbCommand( @"SELECT SortType FROM Playlists WHERE PlaylistID = :playlist_id", playlist_id_param))); } catch { return base.SortType; } } set { try { Globals.Library.Db.Execute(new DbCommand( @"UPDATE Playlists SET SortType = :sort_type WHERE PlaylistID = :playlist_id", "sort_type", value, playlist_id_param)); } catch { base.SortType = value; } } } #if !win32 public override Gtk.SortType SortType { get { try { return (Gtk.SortType)Convert.ToInt32(Globals.Library.Db.QuerySingle(new DbCommand( @"SELECT SortType FROM Playlists WHERE PlaylistID = :playlist_id", playlist_id_param))); } catch { return base.SortType; } } set { try { Globals.Library.Db.Execute(new DbCommand( @"UPDATE Playlists SET SortType = :sort_type WHERE PlaylistID = :playlist_id", "sort_type", value, playlist_id_param)); } catch { base.SortType = value; } } } #endif public static class PlaylistUtil { public static ICollection LoadSources() { ArrayList sources = new ArrayList(); IDataReader reader = Globals.Library.Db.Query(@" SELECT PlaylistID FROM Playlists" ); while (reader.Read()) { PlaylistSource playlist = new PlaylistSource(Convert.ToInt32(reader[0])); sources.Add(playlist); } reader.Dispose(); return sources; } internal static int GetPlaylistID(string name) { try { return Convert.ToInt32(Globals.Library.Db.QuerySingle(new DbCommand( @"SELECT PlaylistID FROM Playlists WHERE Name = :name LIMIT 1", "name", name ))); } catch (Exception) { return 0; } } internal static bool PlaylistExists(string name) { return GetPlaylistID(name) > 0; } public static string UniqueName { get { return NamingUtil.PostfixDuplicate(Catalog.GetString("New Playlist"), PlaylistExists); } } public static string GoodUniqueName(IEnumerable tracks) { return NamingUtil.PostfixDuplicate(NamingUtil.GenerateTrackCollectionName( tracks, Catalog.GetString("New Playlist")), PlaylistExists); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Web.Mvc.Html; using System.Web.Routing; using HyperSlackers.Bootstrap; using System.Diagnostics.Contracts; using HyperSlackers.Bootstrap.Core; using HyperSlackers.Bootstrap.Extensions; namespace HyperSlackers.Bootstrap.Controls { public class ActionLinkControl<TModel> : ControlBase<ActionLinkControl<TModel>, TModel> { internal readonly AjaxHelper<TModel> ajax; // TODO: ajaxable control base? internal readonly ActionResult result; internal readonly Task<ActionResult> taskResult; internal readonly AjaxOptions ajaxOptions; internal readonly ActionType actionTypePassed; internal string linkText; internal string routeName; internal readonly string actionName; internal readonly string controllerName; internal string protocol; internal string hostName; internal string fragment; // TODO: internal bool disabled; internal bool isDropDownToggle; internal RouteValueDictionary routeValues = new RouteValueDictionary(); internal Icon iconPrepend; internal Icon iconAppend; internal bool wrapTagControllerAware; internal bool wrapTagControllerAndActionAware; internal string title; internal Tooltip tooltip; internal Badge badge; internal ActionLinkControl(HtmlHelper<TModel> html, string linkText, ActionResult result) : base(html) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(result != null, "result"); this.linkText = linkText; this.result = result; actionTypePassed = ActionType.HtmlActionResult; } internal ActionLinkControl(HtmlHelper<TModel> html, string linkText, Task<ActionResult> taskResult) : base(html) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(taskResult != null, "taskResult"); this.linkText = linkText; this.taskResult = taskResult; actionTypePassed = ActionType.HtmlTaskResult; } internal ActionLinkControl(HtmlHelper<TModel> html, string linkText, string actionName) : base(html) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!actionName.IsNullOrWhiteSpace()); this.linkText = linkText; this.actionName = actionName; actionTypePassed = ActionType.HtmlRegular; } internal ActionLinkControl(HtmlHelper<TModel> html, string linkText, string actionName, string controllerName) : base(html) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!actionName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!controllerName.IsNullOrWhiteSpace()); this.linkText = linkText; this.actionName = actionName; this.controllerName = controllerName; actionTypePassed = ActionType.HtmlRegular; } internal ActionLinkControl(AjaxHelper<TModel> ajax, string linkText, ActionResult result, AjaxOptions ajaxOptions) : base(new HtmlHelper<TModel>(ajax.ViewContext, ajax.ViewDataContainer, ajax.RouteCollection)) { Contract.Requires<ArgumentNullException>(ajax != null, "ajax"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(result != null, "result"); Contract.Requires<ArgumentNullException>(ajaxOptions != null, "ajaxOptions"); this.ajax = ajax; this.linkText = linkText; this.result = result; this.ajaxOptions = ajaxOptions; actionTypePassed = ActionType.AjaxActionResult; } internal ActionLinkControl(AjaxHelper<TModel> ajax, string linkText, Task<ActionResult> taskResult, AjaxOptions ajaxOptions) : base(new HtmlHelper<TModel>(ajax.ViewContext, ajax.ViewDataContainer, ajax.RouteCollection)) { Contract.Requires<ArgumentNullException>(ajax != null, "ajax"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(taskResult != null, "taskResult"); Contract.Requires<ArgumentNullException>(ajaxOptions != null, "ajaxOptions"); this.ajax = ajax; this.linkText = linkText; this.taskResult = taskResult; this.ajaxOptions = ajaxOptions; actionTypePassed = ActionType.AjaxTaskResult; } internal ActionLinkControl(AjaxHelper<TModel> ajax, string linkText, string actionName, AjaxOptions ajaxOptions) : base(new HtmlHelper<TModel>(ajax.ViewContext, ajax.ViewDataContainer, ajax.RouteCollection)) { Contract.Requires<ArgumentNullException>(ajax != null, "ajax"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!actionName.IsNullOrEmpty()); Contract.Requires<ArgumentNullException>(ajaxOptions != null, "ajaxOptions"); this.ajax = ajax; this.linkText = linkText; this.actionName = actionName; this.ajaxOptions = ajaxOptions; actionTypePassed = ActionType.AjaxRegular; } internal ActionLinkControl(AjaxHelper<TModel> ajax, string linkText, string actionName, string controllerName, AjaxOptions ajaxOptions) : base(new HtmlHelper<TModel>(ajax.ViewContext, ajax.ViewDataContainer, ajax.RouteCollection)) { Contract.Requires<ArgumentNullException>(ajax != null, "ajax"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!actionName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!controllerName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(ajaxOptions != null, "ajaxOptions"); this.ajax = ajax; this.linkText = linkText; this.actionName = actionName; this.controllerName = controllerName; this.ajaxOptions = ajaxOptions; actionTypePassed = ActionType.AjaxRegular; } public ActionLinkControl<TModel> AppendIcon(GlyphIcon icon) { Contract.Requires<ArgumentNullException>(icon != null, "icon"); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); iconAppend = icon; return this; } public ActionLinkControl<TModel> AppendIcon(GlyphIconType icon, bool isWhite = false) { Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); iconAppend = new GlyphIcon(icon, isWhite); return this; } public ActionLinkControl<TModel> AppendIcon(FontAwesomeIcon icon) { Contract.Requires<ArgumentNullException>(icon != null, "icon"); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); iconAppend = icon; return this; } public ActionLinkControl<TModel> AppendIcon(FontAwesomeIconType icon, bool isWhite = false) { Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); iconAppend = new FontAwesomeIcon(icon, isWhite); return this; } public ActionLinkControl<TModel> AppendIcon(string cssClass) { Contract.Requires<ArgumentException>(!cssClass.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); iconAppend = new GlyphIcon(cssClass); return this; } //public ActionLinkControl<TModel> Disabled(bool isDisabled = true) //{ // Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); // this.disabled = isDisabled; // return this; //} public ActionLinkControl<TModel> DropDownToggle() { Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); isDropDownToggle = true; return this; } public ActionLinkControl<TModel> Fragment(string fragment) { Contract.Requires<ArgumentException>(!fragment.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); this.fragment = fragment; return this; } public ActionLinkControl<TModel> HostName(string hostName) { Contract.Requires<ArgumentException>(!hostName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); this.hostName = hostName; return this; } public ActionLinkControl<TModel> PrependIcon(GlyphIcon icon) { Contract.Requires<ArgumentNullException>(icon != null, "icon"); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); iconPrepend = icon; return this; } public ActionLinkControl<TModel> PrependIcon(GlyphIconType icon, bool isWhite = false) { Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); iconPrepend = new GlyphIcon(icon, isWhite); return this; } public ActionLinkControl<TModel> PrependIcon(FontAwesomeIcon icon) { Contract.Requires<ArgumentNullException>(icon != null, "icon"); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); iconPrepend = icon; return this; } public ActionLinkControl<TModel> PrependIcon(FontAwesomeIconType icon, bool isWhite = false) { Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); iconPrepend = new FontAwesomeIcon(icon, isWhite); return this; } public ActionLinkControl<TModel> PrependIcon(string cssClass) { Contract.Requires<ArgumentException>(!cssClass.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); iconPrepend = new GlyphIcon(cssClass); return this; } public ActionLinkControl<TModel> Protocol(string protocol) { Contract.Requires<ArgumentException>(!protocol.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); this.protocol = protocol; return this; } public ActionLinkControl<TModel> RouteName(string routeName) { Contract.Requires<ArgumentException>(!routeName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); this.routeName = routeName; return this; } public ActionLinkControl<TModel> RouteValues(object routeValues) { Contract.Requires<ArgumentNullException>(routeValues != null, "routeValues"); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); this.routeValues.AddOrReplaceHtmlAttributes(routeValues.ToDictionary()); return this; } public ActionLinkControl<TModel> RouteValues(RouteValueDictionary routeValues) { Contract.Requires<ArgumentNullException>(routeValues != null, "routeValues"); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); this.routeValues.AddOrReplaceHtmlAttributes(routeValues); return this; } public ActionLinkControl<TModel> Title(string title) { Contract.Requires<ArgumentException>(!title.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); this.title = title; return this; } public ActionLinkControl<TModel> Tooltip(Tooltip tooltip) { Contract.Requires<ArgumentNullException>(tooltip != null, "tooltip"); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); this.tooltip = tooltip; return this; } public ActionLinkControl<TModel> Tooltip(string text) { Contract.Requires<ArgumentException>(!text.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); tooltip = new Tooltip(text); return this; } public ActionLinkControl<TModel> Tooltip(IHtmlString html) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); tooltip = new Tooltip(html); return this; } internal ActionLinkControl<TModel> WrapTagControllerAndActionAware(bool aware) { Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); wrapTagControllerAndActionAware = aware; return this; } internal ActionLinkControl<TModel> WrapTagControllerAware(bool aware) { Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); wrapTagControllerAware = aware; return this; } internal ActionLinkControl<TModel> AlertLink() { Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); ControlClass("alert-link"); return this; } public ActionLinkControl<TModel> Badge(string text) { Contract.Requires<ArgumentException>(!text.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkControl<TModel>>() != null); badge = new Controls.Badge(text); return this; } protected override string Render() { Contract.Ensures(!Contract.Result<string>().IsNullOrWhiteSpace()); IDictionary<string, object> attributes = controlHtmlAttributes.FormatHtmlAttributes(); if (tooltip != null) { attributes.AddOrReplaceHtmlAttributes(tooltip.ToDictionary()); } if (!id.IsNullOrWhiteSpace()) { attributes.AddOrReplaceHtmlAttribute("id", id); } if (isDropDownToggle) { attributes.AddIfNotExistsCssClass("dropdown-toggle"); attributes.Add("data-toggle", "dropdown"); } //if (this.disabled) //{ // attributes.AddClass("disabled"); // attributes.Add("onclick", "return false"); //} if (!title.IsNullOrWhiteSpace()) { attributes.AddOrReplaceHtmlAttribute("title", title); } string replaceMe = Guid.NewGuid().ToString(); string linkText = replaceMe; string prepend = string.Empty; string append = string.Empty; if (iconPrepend != null || iconAppend != null) { if (iconPrepend != null) { prepend = iconPrepend.ToHtmlString() + " "; } if (iconAppend != null) { append = " " + iconAppend.ToHtmlString(); } } string linkHtml = string.Empty; string controllerName = ""; string actionName = ""; string areaName = ""; switch (actionTypePassed) { case ActionType.HtmlRegular: { if (routeValues == null || !routeValues.ContainsKey("area")) { areaName = (html.ViewContext.RouteData.DataTokens.ContainsKey("area") ? html.ViewContext.RouteData.DataTokens["area"].ToString() : string.Empty); } else { areaName = routeValues["area"].ToString(); } controllerName = (this.controllerName.IsNullOrWhiteSpace() ? html.ViewContext.RouteData.GetRequiredString("controller") : this.controllerName); actionName = this.actionName; linkHtml = html.ActionLink(replaceMe, this.actionName, this.controllerName, protocol, hostName, fragment, routeValues, attributes).ToHtmlString(); break; } case ActionType.HtmlActionResult: { areaName = (result.GetRouteValueDictionary().ContainsKey("area") ? result.GetRouteValueDictionary()["area"].ToString() : string.Empty); controllerName = result.GetRouteValueDictionary()["controller"].ToString(); actionName = result.GetRouteValueDictionary()["action"].ToString(); linkHtml = html.ActionLink(replaceMe, result, attributes, protocol, hostName, fragment).ToHtmlString(); break; } case ActionType.HtmlTaskResult: { areaName = (taskResult.Result.GetRouteValueDictionary().ContainsKey("area") ? taskResult.Result.GetRouteValueDictionary()["area"].ToString() : string.Empty); controllerName = taskResult.Result.GetRouteValueDictionary()["controller"].ToString(); actionName = taskResult.Result.GetRouteValueDictionary()["action"].ToString(); linkHtml = html.ActionLink(replaceMe, taskResult, attributes, protocol, hostName, fragment).ToHtmlString(); break; } case ActionType.AjaxRegular: { if (routeValues == null || !routeValues.ContainsKey("area")) { areaName = (ajax.ViewContext.RouteData.DataTokens.ContainsKey("area") ? ajax.ViewContext.RouteData.DataTokens["area"].ToString() : string.Empty); } else { areaName = routeValues["area"].ToString(); } controllerName = (this.controllerName.IsNullOrWhiteSpace() ? ajax.ViewContext.RouteData.GetRequiredString("controller") : this.controllerName); actionName = this.actionName; linkHtml = ajax.ActionLink(replaceMe, this.actionName, this.controllerName, protocol, hostName, fragment, routeValues, ajaxOptions, attributes).ToHtmlString(); break; } case ActionType.AjaxActionResult: { areaName = (result.GetRouteValueDictionary().ContainsKey("area") ? result.GetRouteValueDictionary()["area"].ToString() : string.Empty); controllerName = result.GetRouteValueDictionary()["controller"].ToString(); actionName = result.GetRouteValueDictionary()["action"].ToString(); linkHtml = ajax.ActionLink(replaceMe, result, ajaxOptions, attributes).ToHtmlString(); break; } case ActionType.AjaxTaskResult: { areaName = (taskResult.Result.GetRouteValueDictionary().ContainsKey("area") ? taskResult.Result.GetRouteValueDictionary()["area"].ToString() : string.Empty); controllerName = taskResult.Result.GetRouteValueDictionary()["controller"].ToString(); actionName = taskResult.Result.GetRouteValueDictionary()["action"].ToString(); linkHtml = ajax.ActionLink(replaceMe, taskResult, ajaxOptions, attributes).ToHtmlString(); break; } } linkHtml = linkHtml.Replace(replaceMe, prepend + this.linkText + (badge == null ? "" : " {0}".FormatWith(badge.ToHtmlString())) + append); if (wrapper != null) { string actionRequiredString = string.Empty; string controllerRequiredString = string.Empty; string areaRequiredString = string.Empty; switch (actionTypePassed) { case ActionType.HtmlRegular: case ActionType.HtmlActionResult: case ActionType.HtmlTaskResult: { actionRequiredString = html.ViewContext.RouteData.GetRequiredString("action"); controllerRequiredString = html.ViewContext.RouteData.GetRequiredString("controller"); areaRequiredString = (html.ViewContext.RouteData.DataTokens.ContainsKey("area") ? html.ViewContext.RouteData.DataTokens["area"].ToString() : string.Empty); break; } case ActionType.AjaxRegular: case ActionType.AjaxActionResult: case ActionType.AjaxTaskResult: { actionRequiredString = ajax.ViewContext.RouteData.GetRequiredString("action"); controllerRequiredString = ajax.ViewContext.RouteData.GetRequiredString("controller"); areaRequiredString = (ajax.ViewContext.RouteData.DataTokens.ContainsKey("area") ? ajax.ViewContext.RouteData.DataTokens["area"].ToString() : string.Empty); break; } } Contract.Assume(controllerName != null); Contract.Assume(controllerRequiredString != null); Contract.Assume(actionRequiredString != null); Contract.Assume(actionName != null); Contract.Assert(areaRequiredString != null); if (wrapTagControllerAware && areaRequiredString.ToLower() == areaName.ToLower() && controllerRequiredString.ToLower() == controllerName.ToLower()) { wrapper.Active(); } if (wrapTagControllerAndActionAware && areaRequiredString.ToLower() == areaName.ToLower() && controllerRequiredString.ToLower() == controllerName.ToLower() && actionRequiredString.ToLower() == actionName.ToLower()) { wrapper.Active(); } linkHtml = WrapperTagFromatString().FormatWith(linkHtml); } return MvcHtmlString.Create(linkHtml).ToString(); } } }
//////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2015 Tim Stair // // 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.ComponentModel; using System.IO; using System.Windows.Forms; namespace Support.UI { /// <summary> /// Handles Form "dirty/clean" states in relation to file loading / saving. Acts as /// an abstract class, but is not. (forms & abstraction break the IDE in MSVS2003) /// Be sure to override SaveFormData and OpenFormData /// </summary> //public abstract class AbstractDirtyForm public class AbstractDirtyForm : Form { private string m_sCurrentDirectory = string.Empty; protected string m_sBaseTitle = string.Empty; protected string m_sLoadedFile = string.Empty; protected string m_sFileOpenFilter = string.Empty; public string LoadedFile => m_sLoadedFile; protected bool Dirty { get; private set; } /// <summary> /// This method should have an override that performs the save of the data to the file. /// </summary> /// <param name="sFileName">The file to save the data to</param> /// <returns>true on success, false otherwise</returns> protected virtual bool SaveFormData(string sFileName) { MessageBox.Show(this, "DEV Error: Please override AbstractDirtyForm.SaveFormData"); return false; } /// <summary> /// This method should have an override that performs the load of the data from the file. /// </summary> /// <param name="sFileName">The file to load the data from</param> /// <returns>true on success, false otherwise</returns> protected virtual bool OpenFormData(string sFileName) { MessageBox.Show(this, "DEV Error: Please override AbstractDirtyForm.OpenFormData"); return false; } /// <summary> /// Gets the current directory associated with the form /// </summary> /// <returns>Current directory for the form, defaults to the current environment</returns> private string GetDialogDirectory() { if (Directory.Exists(m_sCurrentDirectory)) return m_sCurrentDirectory; return Environment.CurrentDirectory; } /// <summary> /// Marks this form as dirty (needing save) /// </summary> public void MarkDirty() { if(!Dirty) { if(!Text.EndsWith("*")) Text += " *"; Dirty = true; } } /// <summary> /// Marks this form as clean (save not needed) /// </summary> public void MarkClean() { if (Dirty) { Text = Text.Replace("*", "").Trim(); Dirty = false; } } /// <summary> /// Initializes a simple new file /// </summary> protected void InitNew() { m_sLoadedFile = string.Empty; Text = m_sBaseTitle; MarkClean(); } /// <summary> /// Initializes the Open process via the OpenFileDialog /// </summary> protected void InitOpen() { var ofn = new OpenFileDialog { InitialDirectory = GetDialogDirectory(), Filter = 0 == m_sFileOpenFilter.Length ? "All files (*.*)|*.*" : m_sFileOpenFilter }; if(DialogResult.OK == ofn.ShowDialog(this)) { var sPath = Path.GetDirectoryName(ofn.FileName); if (null != sPath) { if (Directory.Exists(sPath)) { m_sCurrentDirectory = sPath; if (OpenFormData(ofn.FileName)) { SetLoadedFile(ofn.FileName); return; } } } MessageBox.Show(this, "Error opening [" + ofn.FileName + "] Wrong file type?", "File Open Error"); } } /// <summary> /// Initializes the open process with the file specified. /// </summary> /// <param name="sFileName">The file to open the data from</param> /// <returns>true on success, false otherwise</returns> protected bool InitOpen(string sFileName) { if(OpenFormData(sFileName)) { SetLoadedFile(sFileName); return true; } return false; } /// <summary> /// Sets the currently loaded file and marks the state as clean /// </summary> /// <param name="sFileName"></param> protected void SetLoadedFile(string sFileName) { m_sLoadedFile = sFileName; Text = m_sBaseTitle + " [" + m_sLoadedFile + "]"; MarkClean(); } /// <summary> /// Event to associate with the OnClose event of the form /// </summary> /// <param name="eArg"></param> protected void SaveOnClose(CancelEventArgs eArg) { SaveOnEvent(eArg, true); } protected void SaveOnEvent(CancelEventArgs eArg, bool bAllowCancel) { if (Dirty) { switch (MessageBox.Show(this, "Would you like to save any changes?", "Save", (bAllowCancel ? MessageBoxButtons.YesNoCancel : MessageBoxButtons.YesNo), MessageBoxIcon.Question)) { case DialogResult.Yes: InitSave(false); break; case DialogResult.No: MarkClean(); break; case DialogResult.Cancel: eArg.Cancel = true; break; } } } /// <summary> /// Initializes the Save / Save As dialog /// </summary> /// <param name="bForceSaveAs"></param> protected void InitSave(bool bForceSaveAs) { if (string.IsNullOrEmpty(m_sLoadedFile) || bForceSaveAs) { var sfn = new SaveFileDialog { InitialDirectory = GetDialogDirectory(), OverwritePrompt = true, Filter = 0 == m_sFileOpenFilter.Length ? "All files (*.*)|*.*" : m_sFileOpenFilter }; if (DialogResult.OK == sfn.ShowDialog(this)) { var sPath = Path.GetDirectoryName(sfn.FileName); if (null != sPath) { if (Directory.Exists(sPath)) { m_sCurrentDirectory = sPath; SetLoadedFile(sfn.FileName); } } } else { return; } } if (!SaveFormData(m_sLoadedFile)) { MessageBox.Show(this, "Error saving to file: " + m_sLoadedFile, "File Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MarkClean(); } } } }
using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Index { /* * 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 Analyzer = Lucene.Net.Analysis.Analyzer; using BooleanQuery = Lucene.Net.Search.BooleanQuery; using BytesRef = Lucene.Net.Util.BytesRef; using Codec = Lucene.Net.Codecs.Codec; using Directory = Lucene.Net.Store.Directory; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using Document = Documents.Document; using Field = Field; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using Lucene3xCodec = Lucene.Net.Codecs.Lucene3x.Lucene3xCodec; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using Occur = Lucene.Net.Search.Occur; using TermQuery = Lucene.Net.Search.TermQuery; using TestUtil = Lucene.Net.Util.TestUtil; using TokenStream = Lucene.Net.Analysis.TokenStream; using TopDocs = Lucene.Net.Search.TopDocs; [TestFixture] public class TestIndexableField : LuceneTestCase { private class MyField : IIndexableField { private readonly TestIndexableField outerInstance; internal readonly int counter; internal readonly IIndexableFieldType fieldType; public MyField() { fieldType = new IndexableFieldTypeAnonymousClass(this); } private class IndexableFieldTypeAnonymousClass : IIndexableFieldType { private MyField outerInstance; public IndexableFieldTypeAnonymousClass(MyField outerInstance) { this.outerInstance = outerInstance; } public bool IsIndexed => (outerInstance.counter % 10) != 3; public bool IsStored => (outerInstance.counter & 1) == 0 || (outerInstance.counter % 10) == 3; public bool IsTokenized => true; public bool StoreTermVectors => IsIndexed && outerInstance.counter % 2 == 1 && outerInstance.counter % 10 != 9; public bool StoreTermVectorOffsets => StoreTermVectors && outerInstance.counter % 10 != 9; public bool StoreTermVectorPositions => StoreTermVectors && outerInstance.counter % 10 != 9; public bool StoreTermVectorPayloads { get { #pragma warning disable 612, 618 if (Codec.Default is Lucene3xCodec) #pragma warning restore 612, 618 { return false; // 3.x doesnt support } else { return StoreTermVectors && outerInstance.counter % 10 != 9; } } } public bool OmitNorms => false; public IndexOptions IndexOptions => Index.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; public DocValuesType DocValueType => DocValuesType.NONE; } public MyField(TestIndexableField outerInstance, int counter) : this() { this.outerInstance = outerInstance; this.counter = counter; } public string Name => "f" + counter; public float Boost => 1.0f + (float)Random.NextDouble(); public BytesRef GetBinaryValue() { if ((counter % 10) == 3) { var bytes = new byte[10]; for (int idx = 0; idx < bytes.Length; idx++) { bytes[idx] = (byte)(counter + idx); } return new BytesRef(bytes, 0, bytes.Length); } else { return null; } } public string GetStringValue() { int fieldID = counter % 10; if (fieldID != 3 && fieldID != 7) { return "text " + counter; } else { return null; } } // LUCENENET specific - created overload so we can format an underlying numeric type using specified provider public virtual string GetStringValue(IFormatProvider provider) { return GetStringValue(); } // LUCENENET specific - created overload so we can format an underlying numeric type using specified format public virtual string GetStringValue(string format) { return GetStringValue(); } // LUCENENET specific - created overload so we can format an underlying numeric type using specified format and provider public virtual string GetStringValue(string format, IFormatProvider provider) { return GetStringValue(); } public TextReader GetReaderValue() { if (counter % 10 == 7) { return new StringReader("text " + counter); } else { return null; } } public object GetNumericValue() { return null; } // LUCENENET specific - Since we have no numeric reference types in .NET, this method was added to check // the numeric type of the inner field without boxing/unboxing. public virtual NumericFieldType NumericType => NumericFieldType.NONE; // LUCENENET specific - created overload for Byte, since we have no Number class in .NET public virtual byte? GetByteValue() { return null; } // LUCENENET specific - created overload for Short, since we have no Number class in .NET public virtual short? GetInt16Value() { return null; } // LUCENENET specific - created overload for Int32, since we have no Number class in .NET public virtual int? GetInt32Value() { return null; } // LUCENENET specific - created overload for Int64, since we have no Number class in .NET public virtual long? GetInt64Value() { return null; } // LUCENENET specific - created overload for Single, since we have no Number class in .NET public virtual float? GetSingleValue() { return null; } // LUCENENET specific - created overload for Double, since we have no Number class in .NET public virtual double? GetDoubleValue() { return null; } public IIndexableFieldType IndexableFieldType => fieldType; public TokenStream GetTokenStream(Analyzer analyzer) { return GetReaderValue() != null ? analyzer.GetTokenStream(Name, GetReaderValue()) : analyzer.GetTokenStream(Name, new StringReader(GetStringValue())); } } // Silly test showing how to index documents w/o using Lucene's core // Document nor Field class [Test] public virtual void TestArbitraryFields() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); int NUM_DOCS = AtLeast(27); if (Verbose) { Console.WriteLine("TEST: " + NUM_DOCS + " docs"); } int[] fieldsPerDoc = new int[NUM_DOCS]; int baseCount = 0; for (int docCount = 0; docCount < NUM_DOCS; docCount++) { int fieldCount = TestUtil.NextInt32(Random, 1, 17); fieldsPerDoc[docCount] = fieldCount - 1; int finalDocCount = docCount; if (Verbose) { Console.WriteLine("TEST: " + fieldCount + " fields in doc " + docCount); } int finalBaseCount = baseCount; baseCount += fieldCount - 1; w.AddDocument(new IterableAnonymousClass(this, fieldCount, finalDocCount, finalBaseCount)); } IndexReader r = w.GetReader(); w.Dispose(); IndexSearcher s = NewSearcher(r); int counter = 0; for (int id = 0; id < NUM_DOCS; id++) { if (Verbose) { Console.WriteLine("TEST: verify doc id=" + id + " (" + fieldsPerDoc[id] + " fields) counter=" + counter); } TopDocs hits = s.Search(new TermQuery(new Term("id", "" + id)), 1); Assert.AreEqual(1, hits.TotalHits); int docID = hits.ScoreDocs[0].Doc; Document doc = s.Doc(docID); int endCounter = counter + fieldsPerDoc[id]; while (counter < endCounter) { string name = "f" + counter; int fieldID = counter % 10; bool stored = (counter & 1) == 0 || fieldID == 3; bool binary = fieldID == 3; bool indexed = fieldID != 3; string stringValue; if (fieldID != 3 && fieldID != 9) { stringValue = "text " + counter; } else { stringValue = null; } // stored: if (stored) { IIndexableField f = doc.GetField(name); Assert.IsNotNull(f, "doc " + id + " doesn't have field f" + counter); if (binary) { Assert.IsNotNull(f, "doc " + id + " doesn't have field f" + counter); BytesRef b = f.GetBinaryValue(); Assert.IsNotNull(b); Assert.AreEqual(10, b.Length); for (int idx = 0; idx < 10; idx++) { Assert.AreEqual((byte)(idx + counter), b.Bytes[b.Offset + idx]); } } else { if (Debugging.AssertsEnabled) Debugging.Assert(stringValue != null); Assert.AreEqual(stringValue, f.GetStringValue()); } } if (indexed) { bool tv = counter % 2 == 1 && fieldID != 9; if (tv) { Terms tfv = r.GetTermVectors(docID).GetTerms(name); Assert.IsNotNull(tfv); TermsEnum termsEnum = tfv.GetEnumerator(); Assert.IsTrue(termsEnum.MoveNext()); Assert.AreEqual(new BytesRef("" + counter), termsEnum.Term); Assert.AreEqual(1, termsEnum.TotalTermFreq); DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); Assert.AreEqual(1, dpEnum.Freq); Assert.AreEqual(1, dpEnum.NextPosition()); Assert.IsTrue(termsEnum.MoveNext()); Assert.AreEqual(new BytesRef("text"), termsEnum.Term); Assert.AreEqual(1, termsEnum.TotalTermFreq); dpEnum = termsEnum.DocsAndPositions(null, dpEnum); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); Assert.AreEqual(1, dpEnum.Freq); Assert.AreEqual(0, dpEnum.NextPosition()); Assert.IsFalse(termsEnum.MoveNext()); // TODO: offsets } else { Fields vectors = r.GetTermVectors(docID); Assert.IsTrue(vectors == null || vectors.GetTerms(name) == null); } BooleanQuery bq = new BooleanQuery(); bq.Add(new TermQuery(new Term("id", "" + id)), Occur.MUST); bq.Add(new TermQuery(new Term(name, "text")), Occur.MUST); TopDocs hits2 = s.Search(bq, 1); Assert.AreEqual(1, hits2.TotalHits); Assert.AreEqual(docID, hits2.ScoreDocs[0].Doc); bq = new BooleanQuery(); bq.Add(new TermQuery(new Term("id", "" + id)), Occur.MUST); bq.Add(new TermQuery(new Term(name, "" + counter)), Occur.MUST); TopDocs hits3 = s.Search(bq, 1); Assert.AreEqual(1, hits3.TotalHits); Assert.AreEqual(docID, hits3.ScoreDocs[0].Doc); } counter++; } } r.Dispose(); dir.Dispose(); } private class IterableAnonymousClass : IEnumerable<IIndexableField> { private readonly TestIndexableField outerInstance; private int fieldCount; private int finalDocCount; private int finalBaseCount; public IterableAnonymousClass(TestIndexableField outerInstance, int fieldCount, int finalDocCount, int finalBaseCount) { this.outerInstance = outerInstance; this.fieldCount = fieldCount; this.finalDocCount = finalDocCount; this.finalBaseCount = finalBaseCount; } public virtual IEnumerator<IIndexableField> GetEnumerator() { return new IteratorAnonymousClass(this, outerInstance); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } private class IteratorAnonymousClass : IEnumerator<IIndexableField> { private readonly IterableAnonymousClass outerInstance; private readonly TestIndexableField outerTextIndexableField; public IteratorAnonymousClass(IterableAnonymousClass outerInstance, TestIndexableField outerTextIndexableField) { this.outerInstance = outerInstance; this.outerTextIndexableField = outerTextIndexableField; } internal int fieldUpto; private IIndexableField current; public bool MoveNext() { if (fieldUpto >= outerInstance.fieldCount) { return false; } if (Debugging.AssertsEnabled) Debugging.Assert(fieldUpto < outerInstance.fieldCount); if (fieldUpto == 0) { fieldUpto = 1; current = NewStringField("id", "" + outerInstance.finalDocCount, Field.Store.YES); } else { current = new MyField(outerTextIndexableField, outerInstance.finalBaseCount + (fieldUpto++ - 1)); } return true; } public IIndexableField Current => current; object System.Collections.IEnumerator.Current => Current; public void Dispose() { } public void Reset() { throw new NotImplementedException(); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using OpenCL.Net; namespace Project1 { public class Computations { public struct clState { public Context cl_context; //cl_context OpenCL. context; public Kernel cl_kernel; public CommandQueue cl_command_queue; public Program cl_program; public Mem outputBuffer; public uint4 CLBuffer0; public uint4 padbuffer8; public IntPtr padbufsize; // size_t padbufsize; public IntPtr cldata; // void * cldata; public bool hasBitAlign; public bool hasOpenCL11plus; public bool hasOpenCL12plus; public bool goffset; public uint16 vwidth; // uint16 vwidth; public IntPtr max_work_size; public IntPtr wsize; } public struct dev_blk_ctx { public OpenCL.Net.uint16 ctx_a; public uint16 ctx_b; public uint16 ctx_c; public uint16 ctx_d; public uint16 ctx_e; uint16 ctx_f; uint16 ctx_g; uint16 ctx_h; public uint16 cty_a; uint16 cty_b; uint16 cty_c; uint16 cty_d; public uint16 cty_e; uint16 cty_f; uint16 cty_g; uint16 cty_h; public uint16 merkle; uint16 ntime; uint16 nbits; uint16 nonce; public uint16 fW0; uint16 fW1; uint16 fW2; uint16 fW3; uint16 fW15; public uint16 fW01r; uint16 fcty_e; uint16 fcty_e2; public uint16 W16; uint16 W17; uint16 W2; public uint16 PreVal4; uint16 T1; public uint16 C1addK5; uint16 D1A; uint16 W2A; uint16 W17_2; public uint16 PreVal4addT1; uint16 T1substate0; public uint16 PreVal4_2; public uint16 PreVal0; public uint16 PreW18; public uint16 PreW19; public uint16 PreW31; public uint16 PreW32; public work work; /* For diakgcn */ public uint16 B1addK6, PreVal0addK7, W16addK16, W17addK17; public uint16 zeroA, zeroB; public uint16 oneA, twoA, threeA, fourA, fiveA, sixA, sevenA; } public struct work { public int longnonce; public OpenCL.Net.uchar16 midstate; public OpenCL.Net.uint4 midstate0; public OpenCL.Net.uint4 midstate16; public int device_target; public IntPtr data; } private Context _context; private Device _device; private void CheckErr(ErrorCode err, string name) { if (err != ErrorCode.Success) { Console.WriteLine("ERROR: " + name + " (" + err.ToString() + ")"); } } private void ContextNotify(string errInfo, byte[] data, IntPtr cb, IntPtr userData) { Console.WriteLine("OpenCL Notification: " + errInfo); } public void Setup() { ErrorCode error; Platform[] platforms = Cl.GetPlatformIDs(out error); List<Device> devicesList = new List<Device>(); CheckErr(error, "Cl.GetPlatformIDs"); foreach (Platform platform in platforms) { //ToDO:Log Platform Device Name; // status = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(pbuff), pbuff, NULL); // status = clGetPlatformInfo(platform, CL_PLATFORM_VERSION, sizeof(pbuff), pbuff, NULL); // status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices); //ToDO: Saved the compiled version so it can be built the next time as a binary: //ToDO: Enable certain cards, fan control, scheduling string platformName = Cl.GetPlatformInfo(platform, PlatformInfo.Name, out error).ToString(); Console.WriteLine("Platform: " + platformName); CheckErr(error, "Cl.GetPlatformInfo"); //We will be looking only for GPU devices foreach (OpenCL.Net.Device device in Cl.GetDeviceIDs(platform, DeviceType.Gpu, out error)) { CheckErr(error, "Cl.GetDeviceIDs"); Console.WriteLine("Device: " + device.ToString()); devicesList.Add(device); } } if (devicesList.Count <= 0) { Console.WriteLine("No devices found."); return; } _device = devicesList[0]; if (Cl.GetDeviceInfo(_device, OpenCL.Net.DeviceInfo.ImageSupport, out error).CastTo<OpenCL.Net.Bool>() == OpenCL.Net.Bool.False) { Console.WriteLine("No image support."); return; } _context = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify, IntPtr.Zero, out error); //Second parameter is amount of devices CheckErr(error, "Cl.CreateContext"); } public void ImagingTest(string inputImagePath, string outputImagePath) { ErrorCode error; //Load and compile kernel source code. string programPath = System.Environment.CurrentDirectory + "/../../imagingtest.cl"; //The path to the source file may vary if (!System.IO.File.Exists(programPath)) { Console.WriteLine("Program doesn't exist at path " + programPath); return; } string programSource = System.IO.File.ReadAllText(programPath); using (Program program = Cl.CreateProgramWithSource(_context, 1, new[] { programSource }, null, out error)) { CheckErr(error, "Cl.CreateProgramWithSource"); //Compile kernel source error = Cl.BuildProgram(program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero); CheckErr(error, "Cl.BuildProgram"); //Check for any compilation errors if (Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Status, out error).CastTo<BuildStatus>() != BuildStatus.Success && 1==0) { CheckErr(error, "Cl.GetProgramBuildInfo"); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Log, out error)); return; } //Create the required kernel (entry function) Kernel kernel = Cl.CreateKernel(program, "imagingTest", out error); CheckErr(error, "Cl.CreateKernel"); int intPtrSize = 0; intPtrSize = Marshal.SizeOf(typeof(IntPtr)); //Image's RGBA data converted to an unmanaged[] array byte[] inputByteArray; //OpenCL memory buffer that will keep our image's byte[] data. Mem inputImage2DBuffer; OpenCL.Net.ImageFormat clImageFormat = new OpenCL.Net.ImageFormat(ChannelOrder.RGBA, ChannelType.Unsigned_Int8); int inputImgWidth, inputImgHeight; int inputImgBytesSize; int inputImgStride; //Try loading the input image using (FileStream imageFileStream = new FileStream(inputImagePath, FileMode.Open)) { System.Drawing.Image inputImage = System.Drawing.Image.FromStream(imageFileStream); if (inputImage == null) { Console.WriteLine("Unable to load input image"); return; } inputImgWidth = inputImage.Width; inputImgHeight = inputImage.Height; System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(inputImage); //Get raw pixel data of the bitmap //The format should match the format of clImageFormat BitmapData bitmapData = bmpImage.LockBits(new Rectangle(0, 0, bmpImage.Width, bmpImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);//inputImage.PixelFormat); inputImgStride = bitmapData.Stride; inputImgBytesSize = bitmapData.Stride * bitmapData.Height; //Copy the raw bitmap data to an unmanaged byte[] array inputByteArray = new byte[inputImgBytesSize]; Marshal.Copy(bitmapData.Scan0, inputByteArray, 0, inputImgBytesSize); //Allocate OpenCL image memory buffer inputImage2DBuffer = (OpenCL.Net.Mem)OpenCL.Net.Cl.CreateImage2D(_context, OpenCL.Net.MemFlags.CopyHostPtr | OpenCL.Net.MemFlags.ReadOnly, clImageFormat, (IntPtr)bitmapData.Width, (IntPtr)bitmapData.Height, (IntPtr)0, inputByteArray, out error); CheckErr(error, "Cl.CreateImage2D input"); } //Unmanaged output image's raw RGBA byte[] array byte[] outputByteArray = new byte[inputImgBytesSize]; //Allocate OpenCL image memory buffer OpenCL.Net.Mem outputImage2DBuffer = (OpenCL.Net.Mem)OpenCL.Net.Cl.CreateImage2D(_context, OpenCL.Net.MemFlags.CopyHostPtr | OpenCL.Net.MemFlags.WriteOnly, clImageFormat, (IntPtr)inputImgWidth, (IntPtr)inputImgHeight, (IntPtr)0, outputByteArray, out error); CheckErr(error, "Cl.CreateImage2D output"); //Pass the memory buffers to our kernel function error = Cl.SetKernelArg(kernel, 0, (IntPtr)intPtrSize, inputImage2DBuffer); error |= Cl.SetKernelArg(kernel, 1, (IntPtr)intPtrSize, outputImage2DBuffer); CheckErr(error, "Cl.SetKernelArg"); //Create a command queue, where all of the commands for execution will be added CommandQueue cmdQueue = Cl.CreateCommandQueue(_context, _device, (CommandQueueProperties)0, out error); CheckErr(error, "Cl.CreateCommandQueue"); OpenCL.Net.Event clevent; //Copy input image from the host to the GPU. IntPtr[] originPtr = new IntPtr[] { (IntPtr)0, (IntPtr)0, (IntPtr)0 }; //x, y, z IntPtr[] regionPtr = new IntPtr[] { (IntPtr)inputImgWidth, (IntPtr)inputImgHeight, (IntPtr)1 }; //x, y, z IntPtr[] workGroupSizePtr = new IntPtr[] { (IntPtr)inputImgWidth, (IntPtr)inputImgHeight, (IntPtr)1 }; error = Cl.EnqueueWriteImage(cmdQueue, inputImage2DBuffer, OpenCL.Net.Bool.True, originPtr, regionPtr, (IntPtr)0, (IntPtr)0, inputByteArray, 0, null, out clevent); CheckErr(error, "Cl.EnqueueWriteImage"); //Execute our kernel (OpenCL code) // CommandQueue q = new OpenCL.Net.CommandQueue(); //enqueue nd range kernel // error = cmdQueue.EnqueueKernel(cmdQueue, kernel, 2, null, workGroupSizePtr, null, 0, null, out clevent); // OpenCL.Net.Cl.EnqueueNDRangeKernel( OpenCL.Net.Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 2, null, workGroupSizePtr, null, 0, null, out clevent); CheckErr(error, "Cl.EnqueueNDRangeKernel"); //Wait for completion of all calculations on the GPU. error = Cl.Finish(cmdQueue); CheckErr(error, "Cl.Finish"); //Read the processed image from GPU to raw RGBA data byte[] array error = Cl.EnqueueReadImage(cmdQueue, outputImage2DBuffer, OpenCL.Net.Bool.True, originPtr, regionPtr, (IntPtr)0, (IntPtr)0, outputByteArray, 0, null, out clevent); CheckErr(error, "Cl.clEnqueueReadImage"); //Clean up memory Cl.ReleaseKernel(kernel); Cl.ReleaseCommandQueue(cmdQueue); Cl.ReleaseMemObject(inputImage2DBuffer); Cl.ReleaseMemObject(outputImage2DBuffer); //Get a pointer to our unmanaged output byte[] array GCHandle pinnedOutputArray = GCHandle.Alloc(outputByteArray, GCHandleType.Pinned); IntPtr outputBmpPointer = pinnedOutputArray.AddrOfPinnedObject(); //Create a new bitmap with processed data and save it to a file. Bitmap outputBitmap = new Bitmap(inputImgWidth, inputImgHeight, inputImgStride, PixelFormat.Format32bppArgb, outputBmpPointer); outputBitmap.Save(outputImagePath, System.Drawing.Imaging.ImageFormat.Png); pinnedOutputArray.Free(); } } public void ScryptTest() { ErrorCode error; //Load and compile kernel source code. string programPath = System.Environment.CurrentDirectory + "/../../scrypt.cl"; //Cl if (!System.IO.File.Exists(programPath)) { Console.WriteLine("Program doesn't exist at path " + programPath); return; } string programSource = System.IO.File.ReadAllText(programPath); IntPtr[] sz = new IntPtr[programSource.Length*2]; Program program =Cl.CreateProgramWithSource(_context, 1, new[] { programSource }, null, out error); if (1==1) { CheckErr(error, "Cl.CreateProgramWithSource"); // status = clBuildProgram(clState->program, 1, &devices[gpu], ""-D LOOKUP_GAP=%d -D CONCURRENT_THREADS=%d -D WORKSIZE=%d", NULL, NULL); //Compile kernel source error = Cl.BuildProgram(program, 1, new[] { _device },"-D LOOKUP_GAP=1 -D CONCURRENT_THREADS=1 -D WORKSIZE=1", null, IntPtr.Zero); CheckErr(error, "Cl.BuildProgram"); //Check for any compilation errors if (Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Status, out error).CastTo<BuildStatus>() != BuildStatus.Success && 1 == 0) { CheckErr(error, "Cl.GetProgramBuildInfo"); Console.WriteLine("Cl.GetProgramBuildInfo != Success"); Console.WriteLine(Cl.GetProgramBuildInfo(program, _device, ProgramBuildInfo.Log, out error)); return; } //Create the required kernel (entry function) [search] Kernel kernel = Cl.CreateKernel(program, "search", out error); CheckErr(error, "Cl.CreateKernel"); int intPtrSize = 0; intPtrSize = Marshal.SizeOf(typeof(IntPtr)); //Image's RGBA data converted to an unmanaged[] array byte[] inputByteArray; //OpenCL memory buffer that will keep our image's byte[] data. Mem inputImage2DBuffer; //Create a command queue, where all of the commands for execution will be added CommandQueue cmdQueue = Cl.CreateCommandQueue(_context, _device, (CommandQueueProperties)0, out error); CheckErr(error, "Cl.CreateCommandQueue"); clState _clState = new clState(); _clState.cl_command_queue = cmdQueue; _clState.cl_kernel = kernel; _clState.cl_context = _context; IntPtr buffersize = new IntPtr(1024); IntPtr blank_res = new IntPtr(1024); Object thrdataRes = new Object(); //int buffersize = 1024; OpenCL.Net.Event clevent; // status |= clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0, buffersize, blank_res, 0, NULL, NULL); dev_blk_ctx blk = new dev_blk_ctx(); ErrorCode err = queue_scrypt_kernel(_clState,blk); ErrorCode status = Cl.EnqueueWriteBuffer(_clState.cl_command_queue, _clState.outputBuffer, OpenCL.Net.Bool.True, new IntPtr(0), buffersize, blank_res, 0, null, out clevent); IntPtr[] globalThreads = new IntPtr[0]; IntPtr[] localThreads = new IntPtr[0]; //uint16 workdim = new uint16(1); uint workdim = 1; status = Cl.EnqueueNDRangeKernel(_clState.cl_command_queue,_clState.cl_kernel, workdim, null, globalThreads, localThreads, 0, null, out clevent); CheckErr(error, "Cl.EnqueueNDRangeKernel"); IntPtr offset = new IntPtr(0); status = Cl.EnqueueReadBuffer(_clState.cl_command_queue,_clState.outputBuffer,OpenCL.Net.Bool.False,offset,buffersize,thrdataRes, 0,null, out clevent); //Wait for completion of all calculations on the GPU. error = Cl.Finish(_clState.cl_command_queue); CheckErr(error, "Cl.Finish"); //Clean up memory Cl.ReleaseKernel(_clState.cl_kernel); Cl.ReleaseCommandQueue(_clState.cl_command_queue); } } ErrorCode queue_scrypt_kernel(clState _clState, dev_blk_ctx blk) { //Scantime blk.work.midstate0 = new uint4(0); blk.work.midstate16 = new uint4(1); // unsigned char *midstate = blk->work->midstate; int num = 0; uint16 le_target; le_target = new uint16(Convert.ToUInt16(blk.work.device_target + 28)); _clState.cldata = blk.work.data; _clState.CLBuffer0 = new uint4(0); _clState.outputBuffer = new Mem(); _clState.padbuffer8 = new uint4(0); OpenCL.Net.Event clevent; OpenCL.Net.ImageFormat clImageFormat = new OpenCL.Net.ImageFormat(ChannelOrder.RGBA, ChannelType.Unsigned_Int8); ErrorCode err1; byte[] inputByteArray = new byte[1024]; //buffer0 = (OpenCL.Net.Mem)OpenCL.Net.Cl.CreateImage2D(_clState.cl_context, OpenCL.Net.MemFlags.CopyHostPtr | OpenCL.Net.MemFlags.ReadOnly, clImageFormat, (IntPtr)1024, (IntPtr)1, (IntPtr)0, inputByteArray, out err1); // buffer0 = (OpenCL.Net.Mem)inputByteArray; // byte[] byteSrcImage2DData = new byte[srcIMGBytesSize]; Mem buffer0 = (Mem)OpenCL.Net.Cl.CreateBuffer(_clState.cl_context, MemFlags.ReadWrite, 1024,out err1); ErrorCode status =Cl.EnqueueWriteBuffer(_clState.cl_command_queue, buffer0, OpenCL.Net.Bool.True, (IntPtr)0, (IntPtr)1024, _clState.cldata, 0, null,out clevent); // // status = OpenCL.Net.Cl.SetKernelArg(_clState.Kernel, num++, sizeof(var), (void *)&var) // CL_SET_VARG(args, var) status |= clSetKernelArg(*kernel, num++, args * sizeof(uint), (void *)var) int intPtrSize = 0; intPtrSize = Marshal.SizeOf(typeof(IntPtr)); OpenCL.Net.Cl.SetKernelArg(_clState.cl_kernel, 0,(IntPtr)intPtrSize, _clState.CLBuffer0); OpenCL.Net.Cl.SetKernelArg(_clState.cl_kernel, 1, _clState.outputBuffer); OpenCL.Net.Cl.SetKernelArg(_clState.cl_kernel, 2, _clState.padbuffer8); OpenCL.Net.Cl.SetKernelArg(_clState.cl_kernel, 3, blk.work.midstate0); OpenCL.Net.Cl.SetKernelArg(_clState.cl_kernel, 4, blk.work.midstate16); // CL_SET_VARG(4, &midstate[0]); // CL_SET_VARG(4, &midstate[16]); OpenCL.Net.Cl.SetKernelArg(_clState.cl_kernel, 5,le_target); //error = Cl.SetKernelArg(kernel, 0, (IntPtr)intPtrSize, inputImage2DBuffer); CheckErr(status, "Cl.SetKernelArg"); return status; } } }
/// Credit drobina, w34edrtfg, playemgames /// Sourced from - http://forum.unity3d.com/threads/sprite-icons-with-text-e-g-emoticons.265927/ using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using UnityEngine.Events; using UnityEngine.EventSystems; namespace UnityEngine.UI.Extensions { // Image according to the label inside the name attribute to load, read from the Resources directory. The size of the image is controlled by the size property. // Use: Add Icon name and sprite to the icons list [AddComponentMenu("UI/Extensions/TextPic")] [ExecuteInEditMode] // Needed for culling images that are not used // public class TextPic : Text, IPointerClickHandler, IPointerExitHandler, IPointerEnterHandler, ISelectHandler { /// <summary> /// Image Pool /// </summary> private readonly List<Image> m_ImagesPool = new List<Image>(); private readonly List<GameObject> culled_ImagesPool = new List<GameObject>(); private bool clearImages = false; private Object thisLock = new Object(); /// <summary> /// Vertex Index /// </summary> private readonly List<int> m_ImagesVertexIndex = new List<int>(); /// <summary> /// Regular expression to replace /// </summary> private static readonly Regex s_Regex = new Regex(@"<quad name=(.+?) size=(\d*\.?\d+%?) width=(\d*\.?\d+%?) />", RegexOptions.Singleline); private string fixedString; [SerializeField] [Tooltip("Allow click events to be received by parents, (default) blocks")] private bool m_ClickParents; // Update the quad images when true private bool updateQuad = false; public bool AllowClickParents { get { return m_ClickParents; } set { m_ClickParents = value; } } public override void SetVerticesDirty() { base.SetVerticesDirty(); // Update the quad images updateQuad = true; } #if UNITY_EDITOR protected override void OnValidate() { base.OnValidate(); // Update the quad images updateQuad = true; for (int i = 0; i < inspectorIconList.Length; i++) { if (inspectorIconList[i].scale == Vector2.zero) { inspectorIconList[i].scale = Vector2.one; } } } #endif /// <summary> /// After parsing the final text /// </summary> private string m_OutputText; [System.Serializable] public struct IconName { public string name; public Sprite sprite; public Vector2 offset; public Vector2 scale; } public IconName[] inspectorIconList; [Tooltip("Global scaling factor for all images")] public float ImageScalingFactor = 1; // Write the name or hex value of the hyperlink color public string hyperlinkColor = "blue"; // Offset image by x, y [SerializeField] public Vector2 imageOffset = Vector2.zero; private Button button; private List<Vector2> positions = new List<Vector2>(); /** * Little hack to support multiple hrefs with same name */ private string previousText = ""; public bool isCreating_m_HrefInfos = true; new void Start() { button = GetComponent<Button>(); ResetIconList(); } public void ResetIconList() { Reset_m_HrefInfos (); base.Start(); } protected void UpdateQuadImage() { #if UNITY_EDITOR if (UnityEditor.PrefabUtility.GetPrefabType(this) == UnityEditor.PrefabType.Prefab) { return; } #endif m_OutputText = GetOutputText(); MatchCollection matches = s_Regex.Matches(m_OutputText); if (matches != null && matches.Count > 0) { for (int i = 0; i < matches.Count; i++) { m_ImagesPool.RemoveAll(image => image == null); if (m_ImagesPool.Count == 0) { GetComponentsInChildren<Image>(true, m_ImagesPool); } if (matches.Count > m_ImagesPool.Count) { var resources = new DefaultControls.Resources(); var go = DefaultControls.CreateImage(resources); go.layer = gameObject.layer; var rt = go.transform as RectTransform; if (rt) { rt.SetParent(rectTransform); rt.anchoredPosition3D = Vector3.zero; rt.localRotation = Quaternion.identity; rt.localScale = Vector3.one; } m_ImagesPool.Add(go.GetComponent<Image>()); } var spriteName = matches[i].Groups[1].Value; var img = m_ImagesPool[i]; Vector2 imgoffset = Vector2.zero; if (img.sprite == null || img.sprite.name != spriteName) { if (inspectorIconList != null && inspectorIconList.Length > 0) { foreach (IconName icon in inspectorIconList) { if (icon.name == spriteName) { img.sprite = icon.sprite; img.preserveAspect = true; img.rectTransform.sizeDelta = new Vector2(fontSize * ImageScalingFactor * icon.scale.x, fontSize * ImageScalingFactor * icon.scale.y); imgoffset = icon.offset; break; } } } } img.enabled = true; if (positions.Count > 0 && i < positions.Count) { img.rectTransform.anchoredPosition = positions[i] += imgoffset; } } } else { // If there are no matches, remove the images from the pool for (int i = 0; i < m_ImagesPool.Count; i++) { if (m_ImagesPool[i]) { if (!culled_ImagesPool.Contains(m_ImagesPool[i].gameObject)) { culled_ImagesPool.Add(m_ImagesPool[i].gameObject); m_ImagesPool.Remove(m_ImagesPool[i]); } } } } // Remove any images that are not being used for (var i = matches.Count; i < m_ImagesPool.Count; i++) { if (m_ImagesPool[i]) { if (!culled_ImagesPool.Contains(m_ImagesPool[i].gameObject)) { culled_ImagesPool.Add(m_ImagesPool[i].gameObject); m_ImagesPool.Remove(m_ImagesPool[i]); } } } // Clear the images when it is safe to do so if (culled_ImagesPool.Count > 0) { clearImages = true; } } protected override void OnPopulateMesh(VertexHelper toFill) { var orignText = m_Text; m_Text = GetOutputText(); base.OnPopulateMesh(toFill); m_Text = orignText; positions.Clear(); UIVertex vert = new UIVertex(); for (var i = 0; i < m_ImagesVertexIndex.Count; i++) { var endIndex = m_ImagesVertexIndex[i]; if (endIndex < toFill.currentVertCount) { toFill.PopulateUIVertex(ref vert, endIndex); positions.Add(new Vector2((vert.position.x + fontSize / 2), (vert.position.y + fontSize / 2)) + imageOffset); // Erase the lower left corner of the black specks toFill.PopulateUIVertex(ref vert, endIndex - 3); var pos = vert.position; for (int j = endIndex, m = endIndex - 3; j > m; j--) { toFill.PopulateUIVertex(ref vert, endIndex); vert.position = pos; toFill.SetUIVertex(vert, j); } } } // Hyperlinks surround processing box foreach (var hrefInfo in m_HrefInfos) { hrefInfo.boxes.Clear(); if (hrefInfo.startIndex >= toFill.currentVertCount) { continue; } // Hyperlink inside the text is added to surround the vertex index coordinate frame toFill.PopulateUIVertex(ref vert, hrefInfo.startIndex); var pos = vert.position; var bounds = new Bounds(pos, Vector3.zero); for (int i = hrefInfo.startIndex, m = hrefInfo.endIndex; i < m; i++) { if (i >= toFill.currentVertCount) { break; } toFill.PopulateUIVertex(ref vert, i); pos = vert.position; // Wrap re-add surround frame if (pos.x < bounds.min.x) { hrefInfo.boxes.Add(new Rect(bounds.min, bounds.size)); bounds = new Bounds(pos, Vector3.zero); } else { bounds.Encapsulate(pos); // Extended enclosed box } } hrefInfo.boxes.Add(new Rect(bounds.min, bounds.size)); } // Update the quad images updateQuad = true; } /// <summary> /// Hyperlink List /// </summary> private readonly List<HrefInfo> m_HrefInfos = new List<HrefInfo>(); /// <summary> /// Text Builder /// </summary> private static readonly StringBuilder s_TextBuilder = new StringBuilder(); /// <summary> /// Hyperlink Regular Expression /// </summary> private static readonly Regex s_HrefRegex = new Regex(@"<a href=([^>\n\s]+)>(.*?)(</a>)", RegexOptions.Singleline); [Serializable] public class HrefClickEvent : UnityEvent<string> { } [SerializeField] private HrefClickEvent m_OnHrefClick = new HrefClickEvent(); /// <summary> /// Hyperlink Click Event /// </summary> public HrefClickEvent onHrefClick { get { return m_OnHrefClick; } set { m_OnHrefClick = value; } } /// <summary> /// Finally, the output text hyperlinks get parsed /// </summary> /// <returns></returns> protected string GetOutputText() { s_TextBuilder.Length = 0; var indexText = 0; fixedString = this.text; if (inspectorIconList != null && inspectorIconList.Length > 0) { foreach (IconName icon in inspectorIconList) { if (!string.IsNullOrEmpty(icon.name)) { fixedString = fixedString.Replace(icon.name, "<quad name=" + icon.name + " size=" + fontSize + " width=1 />"); } } } int count = 0; foreach (Match match in s_HrefRegex.Matches(fixedString)) { s_TextBuilder.Append(fixedString.Substring(indexText, match.Index - indexText)); s_TextBuilder.Append("<color=" + hyperlinkColor + ">"); // Hyperlink color var group = match.Groups[1]; if (isCreating_m_HrefInfos) { var hrefInfo = new HrefInfo { startIndex = s_TextBuilder.Length * 4, // Hyperlinks in text starting vertex indices endIndex = (s_TextBuilder.Length + match.Groups[2].Length - 1) * 4 + 3, name = group.Value }; m_HrefInfos.Add(hrefInfo); } else { if(m_HrefInfos.Count > 0) { m_HrefInfos[count].startIndex = s_TextBuilder.Length * 4; // Hyperlinks in text starting vertex indices; m_HrefInfos[count].endIndex = (s_TextBuilder.Length + match.Groups[2].Length - 1) * 4 + 3; count++; } } s_TextBuilder.Append(match.Groups[2].Value); s_TextBuilder.Append("</color>"); indexText = match.Index + match.Length; } // we should create array only once or if there is any change in the text if (isCreating_m_HrefInfos) isCreating_m_HrefInfos = false; s_TextBuilder.Append(fixedString.Substring(indexText, fixedString.Length - indexText)); m_OutputText = s_TextBuilder.ToString(); m_ImagesVertexIndex.Clear(); MatchCollection matches = s_Regex.Matches(m_OutputText); if (matches != null && matches.Count > 0) { foreach (Match match in matches) { var picIndex = match.Index; var endIndex = picIndex * 4 + 3; m_ImagesVertexIndex.Add(endIndex); } } return m_OutputText; } /// <summary> /// Click event is detected whether to click a hyperlink text /// </summary> /// <param name="eventData"></param> public void OnPointerClick(PointerEventData eventData) { Vector2 lp; RectTransformUtility.ScreenPointToLocalPointInRectangle( rectTransform, eventData.position, eventData.pressEventCamera, out lp); foreach (var hrefInfo in m_HrefInfos) { var boxes = hrefInfo.boxes; for (var i = 0; i < boxes.Count; ++i) { if (boxes[i].Contains(lp)) { m_OnHrefClick.Invoke(hrefInfo.name); return; } } } } public void OnPointerEnter(PointerEventData eventData) { if (m_ImagesPool.Count >= 1) { foreach (Image img in m_ImagesPool) { if (button != null && button.isActiveAndEnabled) { img.color = button.colors.highlightedColor; } } } } public void OnPointerExit(PointerEventData eventData) { if (m_ImagesPool.Count >= 1) { foreach (Image img in m_ImagesPool) { if (button != null && button.isActiveAndEnabled) { img.color = button.colors.normalColor; } else { img.color = color; } } } } public void OnSelect(BaseEventData eventData) { if (m_ImagesPool.Count >= 1) { foreach (Image img in m_ImagesPool) { if (button != null && button.isActiveAndEnabled) { img.color = button.colors.highlightedColor; } } } } public void OnDeselect(BaseEventData eventData) { if (m_ImagesPool.Count >= 1) { foreach (Image img in m_ImagesPool) { if (button != null && button.isActiveAndEnabled) { img.color = button.colors.normalColor; } } } } /// <summary> /// Hyperlinks Info /// </summary> private class HrefInfo { public int startIndex; public int endIndex; public string name; public readonly List<Rect> boxes = new List<Rect>(); } void LateUpdate() { // Reset the hrefs if text is changed if( previousText != text) { Reset_m_HrefInfos (); // Update the quad on text change updateQuad = true; } // Need to lock to remove images properly lock (thisLock) { // Can only update the images when it is not in a rebuild, this prevents the error if (updateQuad) { UpdateQuadImage(); updateQuad = false; } // Destroy any images that are not in use if (clearImages) { for (int i = 0; i < culled_ImagesPool.Count; i++) { DestroyImmediate(culled_ImagesPool[i]); } culled_ImagesPool.Clear(); clearImages = false; } } } // Reseting m_HrefInfos array if there is any change in text void Reset_m_HrefInfos () { previousText = text; m_HrefInfos.Clear(); isCreating_m_HrefInfos = true; } protected override void OnEnable() { base.OnEnable(); // Enable images on TextPic disable if (m_ImagesPool.Count >= 1) { for (int i = 0; i < m_ImagesPool.Count; i++) { if(m_ImagesPool[i] != null) { m_ImagesPool[i].enabled = true; } } } // Update the quads on re-enable updateQuad = true; } protected override void OnDisable() { base.OnDisable(); // Disable images on TextPic disable if (m_ImagesPool.Count >= 1) { for (int i = 0; i < m_ImagesPool.Count; i++) { if(m_ImagesPool[i] != null) { m_ImagesPool[i].enabled = false; } } } } } }
using System; using System.Runtime.InteropServices; using System.IO; #if OPENGL #if MONOMAC using MonoMac.OpenGL; #elif WINDOWS || LINUX using OpenTK.Graphics.OpenGL; #elif GLES using System.Text; using OpenTK.Graphics.ES20; using ShaderType = OpenTK.Graphics.ES20.All; using ShaderParameter = OpenTK.Graphics.ES20.All; using TextureUnit = OpenTK.Graphics.ES20.All; using TextureTarget = OpenTK.Graphics.ES20.All; #endif #elif DIRECTX using SharpDX; using SharpDX.Direct3D; using SharpDX.Direct3D11; using SharpDX.DXGI; #elif PSM enum ShaderType //FIXME: Major Hack { VertexShader, FragmentShader } #endif namespace Microsoft.Xna.Framework.Graphics { internal enum SamplerType { Sampler2D = 0, SamplerCube = 1, SamplerVolume = 2, Sampler1D = 3, } // TODO: We should convert the sampler info below // into the start of a Shader reflection API. internal struct SamplerInfo { public SamplerType type; public int textureSlot; public int samplerSlot; public string name; public SamplerState state; // TODO: This should be moved to EffectPass. public int parameter; } internal class Shader : GraphicsResource { #if OPENGL // The shader handle. private int _shaderHandle = -1; // We keep this around for recompiling on context lost and debugging. private readonly string _glslCode; private struct Attribute { public VertexElementUsage usage; public int index; public string name; public short format; public int location; } private Attribute[] _attributes; #elif DIRECTX private VertexShader _vertexShader; private PixelShader _pixelShader; private byte[] _shaderBytecode; public byte[] Bytecode { get; private set; } internal VertexShader VertexShader { get { if (_vertexShader == null) CreateVertexShader(); return _vertexShader; } } internal PixelShader PixelShader { get { if (_pixelShader == null) CreatePixelShader(); return _pixelShader; } } #endif /// <summary> /// A hash value which can be used to compare shaders. /// </summary> internal int HashKey { get; private set; } public SamplerInfo[] Samplers { get; private set; } public int[] CBuffers { get; private set; } public ShaderStage Stage { get; private set; } internal Shader(GraphicsDevice device, BinaryReader reader) { GraphicsDevice = device; var isVertexShader = reader.ReadBoolean(); Stage = isVertexShader ? ShaderStage.Vertex : ShaderStage.Pixel; var shaderLength = reader.ReadInt32(); var shaderBytecode = reader.ReadBytes(shaderLength); var samplerCount = (int)reader.ReadByte(); Samplers = new SamplerInfo[samplerCount]; for (var s = 0; s < samplerCount; s++) { Samplers[s].type = (SamplerType)reader.ReadByte(); Samplers[s].textureSlot = reader.ReadByte(); Samplers[s].samplerSlot = reader.ReadByte(); if (reader.ReadBoolean()) { Samplers[s].state = new SamplerState(); Samplers[s].state.AddressU = (TextureAddressMode)reader.ReadByte(); Samplers[s].state.AddressV = (TextureAddressMode)reader.ReadByte(); Samplers[s].state.AddressW = (TextureAddressMode)reader.ReadByte(); Samplers[s].state.Filter = (TextureFilter)reader.ReadByte(); Samplers[s].state.MaxAnisotropy = reader.ReadInt32(); Samplers[s].state.MaxMipLevel = reader.ReadInt32(); Samplers[s].state.MipMapLevelOfDetailBias = reader.ReadSingle(); } #if OPENGL Samplers[s].name = reader.ReadString(); #endif Samplers[s].parameter = reader.ReadByte(); } var cbufferCount = (int)reader.ReadByte(); CBuffers = new int[cbufferCount]; for (var c = 0; c < cbufferCount; c++) CBuffers[c] = reader.ReadByte(); #if DIRECTX _shaderBytecode = shaderBytecode; // We need the bytecode later for allocating the // input layout from the vertex declaration. Bytecode = shaderBytecode; HashKey = MonoGame.Utilities.Hash.ComputeHash(Bytecode); if (isVertexShader) CreateVertexShader(); else CreatePixelShader(); #endif // DIRECTX #if OPENGL _glslCode = System.Text.Encoding.ASCII.GetString(shaderBytecode); HashKey = MonoGame.Utilities.Hash.ComputeHash(shaderBytecode); var attributeCount = (int)reader.ReadByte(); _attributes = new Attribute[attributeCount]; for (var a = 0; a < attributeCount; a++) { _attributes[a].name = reader.ReadString(); _attributes[a].usage = (VertexElementUsage)reader.ReadByte(); _attributes[a].index = reader.ReadByte(); _attributes[a].format = reader.ReadInt16(); } #endif // OPENGL } #if OPENGL internal int GetShaderHandle() { // If the shader has already been created then return it. if (_shaderHandle != -1) return _shaderHandle; // _shaderHandle = GL.CreateShader(Stage == ShaderStage.Vertex ? ShaderType.VertexShader : ShaderType.FragmentShader); GraphicsExtensions.CheckGLError(); #if GLES GL.ShaderSource(_shaderHandle, 1, new string[] { _glslCode }, (int[])null); #else GL.ShaderSource(_shaderHandle, _glslCode); #endif GraphicsExtensions.CheckGLError(); GL.CompileShader(_shaderHandle); GraphicsExtensions.CheckGLError(); var compiled = 0; #if GLES GL.GetShader(_shaderHandle, ShaderParameter.CompileStatus, ref compiled); #else GL.GetShader(_shaderHandle, ShaderParameter.CompileStatus, out compiled); #endif GraphicsExtensions.CheckGLError(); if (compiled == (int)All.False) { #if GLES string log = ""; int length = 0; GL.GetShader(_shaderHandle, ShaderParameter.InfoLogLength, ref length); GraphicsExtensions.CheckGLError(); if (length > 0) { var logBuilder = new StringBuilder(length); GL.GetShaderInfoLog(_shaderHandle, length, ref length, logBuilder); GraphicsExtensions.CheckGLError(); log = logBuilder.ToString(); } #else var log = GL.GetShaderInfoLog(_shaderHandle); #endif Console.WriteLine(log); if (GL.IsShader(_shaderHandle)) { GL.DeleteShader(_shaderHandle); GraphicsExtensions.CheckGLError(); } _shaderHandle = -1; throw new InvalidOperationException("Shader Compilation Failed"); } return _shaderHandle; } internal void GetVertexAttributeLocations(int program) { for (int i = 0; i < _attributes.Length; ++i) { _attributes[i].location = GL.GetAttribLocation(program, _attributes[i].name); GraphicsExtensions.CheckGLError(); } } internal int GetAttribLocation(VertexElementUsage usage, int index) { for (int i = 0; i < _attributes.Length; ++i) { if ((_attributes[i].usage == usage) && (_attributes[i].index == index)) return _attributes[i].location; } return -1; } internal void ApplySamplerTextureUnits(int program) { // Assign the texture unit index to the sampler uniforms. foreach (var sampler in Samplers) { var loc = GL.GetUniformLocation(program, sampler.name); GraphicsExtensions.CheckGLError(); if (loc != -1) { GL.Uniform1(loc, sampler.textureSlot); GraphicsExtensions.CheckGLError(); } } } #endif // OPENGL internal protected override void GraphicsDeviceResetting() { #if OPENGL if (_shaderHandle != -1) { if (GL.IsShader(_shaderHandle)) { GL.DeleteShader(_shaderHandle); GraphicsExtensions.CheckGLError(); } _shaderHandle = -1; } #endif #if DIRECTX SharpDX.Utilities.Dispose(ref _vertexShader); SharpDX.Utilities.Dispose(ref _pixelShader); #endif } protected override void Dispose(bool disposing) { if (!IsDisposed) { #if OPENGL GraphicsDevice.AddDisposeAction(() => { if (_shaderHandle != -1) { if (GL.IsShader(_shaderHandle)) { GL.DeleteShader(_shaderHandle); GraphicsExtensions.CheckGLError(); } _shaderHandle = -1; } }); #endif #if DIRECTX GraphicsDeviceResetting(); #endif } base.Dispose(disposing); } #if DIRECTX private void CreatePixelShader() { System.Diagnostics.Debug.Assert(Stage == ShaderStage.Pixel); _pixelShader = new PixelShader(GraphicsDevice._d3dDevice, _shaderBytecode); } private void CreateVertexShader() { System.Diagnostics.Debug.Assert(Stage == ShaderStage.Vertex); _vertexShader = new VertexShader(GraphicsDevice._d3dDevice, _shaderBytecode, null); } #endif } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using eidss.gis.Serializers; using SharpMap.Layers; using SharpMap.Data.Providers; using ICSharpCode.SharpZipLib.Zip; using System.Xml; using SharpMap; using GdalRasterLayer = GIS_V4.Layers.GdalRasterLayer; namespace eidss.gis.Utils { //TODO[enikulin]: Need code review! Change zip lib! Vector and raster layer from SharpMap or GIS_V4? public static class MapPacker { static MapPacker() { if (ZipConstants.DefaultCodePage == 1) ZipConstants.DefaultCodePage = 437; //Bug in ZipLib } private const string FileTagName = "Filename"; private const string MapNameTagName = "MapName"; /// <summary> /// Packaging map /// </summary> /// <param name="map">Map for packaging</param> /// <param name="mapName">Name of the map</param> /// <param name="packetOutputPath">Output file path</param> public static void PackMap(Map map, string mapName, string packetOutputPath) { string mapFilePath = null; try { ZipFile zipFile = ZipFile.Create(packetOutputPath); //maping full name -> short name in arch var filenames = new Dictionary<string, string>(); //add layers data to arc; foreach (ILayer layer in map.Layers) { string fileName = null; //if shp file get its fileName var vectorLayer = layer as VectorLayer; if (vectorLayer != null) { var prov = vectorLayer.DataSource as ShapeFile; if (prov != null) fileName = prov.Filename; } //if raster get its filename var rastLayer = layer as GdalRasterLayer; if (rastLayer != null) fileName = rastLayer.Filename; //add to arc if (fileName != null) { //search FullPath (if already exist - continue) if (filenames.ContainsKey(fileName)) continue; //file already added to arch string shortName = Path.GetFileName(fileName); //search shortName in dictionary (if exist, rename it) if (filenames.ContainsValue(shortName)) shortName = Path.GetFileNameWithoutExtension(shortName) + Guid.NewGuid() + Path.GetExtension(shortName); //add to dictionary filenames.Add(fileName, shortName); zipFile.BeginUpdate(); CompressFileWithAdditional(fileName, Path.GetFileNameWithoutExtension(shortName), zipFile); zipFile.CommitUpdate(); } } //add map file to arc string mapFileName = mapName + ".map"; mapFilePath = Path.GetTempPath() + Guid.NewGuid() + ".map"; //+ mapName //save as temporary file EidssMapSerializer.Instance.SerializeAsFile(map, mapFilePath); PrePackParseMapFile(mapFilePath, filenames, mapName); //pack map file zipFile.BeginUpdate(); zipFile.Add(mapFilePath, mapFileName); zipFile.CommitUpdate(); //close zip file zipFile.Close(); //delete temporary map file File.Delete(mapFilePath); } catch (Exception) { //if(File.Exists(packetOutputPath)) // File.Delete(packetOutputPath); //if (File.Exists(mapFilePath)) // File.Delete(mapFilePath); throw; } } public delegate bool GetNewMapName(ref string mapName); /// <summary> /// Unpackaging map /// </summary> /// <param name="packPath">Path to pack file</param> /// <param name="mapOutputFolder">Output folder for unpacking map</param> /// <param name="newMapNameDelegate">Delegeate for request new mapName</param> public static void UnpackMap(string packPath, string mapOutputFolder, GetNewMapName newMapNameDelegate) { string newMapDir = Path.Combine(mapOutputFolder, "Map_"+Guid.NewGuid()); string mapFilePath=null; string newMapFilePath = null; try { Directory.CreateDirectory(newMapDir); //extract map var fastZip = new FastZip(); fastZip.ExtractZip(packPath, newMapDir, null); //copy map file and set new file path string[] mapFiles = Directory.GetFiles(newMapDir, "*.map"); if (mapFiles.Length != 1) throw new ApplicationException(string.Format("MapPack has {0} map files!", mapFiles.Length)); mapFilePath = mapFiles[0]; newMapFilePath = Path.Combine(mapOutputFolder, Path.GetFileName(mapFilePath)); //system map directory already contains map with such name if (File.Exists(newMapFilePath)) { if (!newMapNameDelegate(ref newMapFilePath)) { Directory.Delete(newMapDir, true); return; } } File.Copy(mapFilePath, newMapFilePath, true); File.Delete(mapFilePath); PostUnpackParseMapFile(newMapFilePath, newMapDir); } catch (Exception) { if(Directory.Exists(newMapDir)) Directory.Delete(newMapDir, true); if(File.Exists(newMapFilePath)) File.Delete(newMapFilePath); if (File.Exists(mapFilePath)) File.Delete(mapFilePath); throw; } } //TODO[enikulin]: make private public static void CompressFileWithAdditional(string filePath, string entryName, ZipFile zipFile) { var file = new FileInfo(filePath); var files = file.Directory.GetFiles(Path.GetFileNameWithoutExtension(filePath) + ".*"); foreach (FileInfo fileInfo in files) { zipFile.Add(fileInfo.FullName, entryName + Path.GetExtension(fileInfo.FullName)); } } public static void PrePackParseMapFile(string mapFilePath, Dictionary<string , string> fileNamesDict, string mapName) { var xmlDoc=new XmlDocument(); xmlDoc.Load(mapFilePath); var filenameNodes = xmlDoc.GetElementsByTagName(FileTagName); //remake paths foreach (XmlNode fileNode in filenameNodes) { fileNode.InnerText = fileNamesDict.ContainsKey(fileNode.InnerText) ? fileNamesDict[fileNode.InnerText] : Path.GetFileName(fileNode.InnerText); } //rename map var mapnameNode = xmlDoc.GetElementsByTagName(MapNameTagName); if (mapnameNode.Count != 1) Debug.WriteLine("Map file is broken!"); else mapnameNode[0].InnerText = mapName; xmlDoc.Save(mapFilePath); } public static void PostUnpackParseMapFile(string mapFilePath, string dataPath) { var xmlDoc = new XmlDocument(); xmlDoc.Load(mapFilePath); var filenames = xmlDoc.GetElementsByTagName(FileTagName); foreach (XmlNode fileNode in filenames) { fileNode.InnerText = Path.Combine(dataPath, fileNode.InnerText); } xmlDoc.Save(mapFilePath); } } }
// // Slider.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright 2009 Aaron Bockover // // 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 Cairo; using Hyena.Gui; using Hyena.Gui.Theming; namespace Hyena.Gui.Canvas { public class Slider : CanvasItem { private uint value_changed_inhibit_ref = 0; public event EventHandler<EventArgs> ValueChanged; public event EventHandler<EventArgs> PendingValueChanged; public Slider () { Margin = new Thickness (3); MarginStyle = new ShadowMarginStyle { ShadowSize = 3, ShadowOpacity = 0.25 }; } protected virtual void OnValueChanged () { if (value_changed_inhibit_ref != 0) { return; } var handler = ValueChanged; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnPendingValueChanged () { var handler = PendingValueChanged; if (handler != null) { handler (this, EventArgs.Empty); } } public void InhibitValueChangeEvent () { value_changed_inhibit_ref++; } public void UninhibitValueChangeEvent () { value_changed_inhibit_ref--; } private void SetPendingValueFromX (double x) { IsValueUpdatePending = true; PendingValue = Math.Max (0, Math.Min ((x - ThrobberSize / 2) / RenderSize.Width, 1)); } public override bool ButtonEvent (Point cursor, bool pressed, uint button) { if (pressed && button == 1) { GrabPointer (); SetPendingValueFromX (cursor.X); return true; } else if (!pressed && IsPointerGrabbed) { ReleasePointer (); Value = PendingValue; IsValueUpdatePending = false; return true; } return false; } public override bool CursorMotionEvent (Point cursor) { if (IsPointerGrabbed) { SetPendingValueFromX (cursor.X); return true; } return false; } //private double last_invalidate_value = -1; /*private void Invalidate () { double current_value = (IsValueUpdatePending ? PendingValue : Value); // FIXME: Something is wrong with the updating below causing an // invalid region when IsValueUpdatePending is true, so when // that is the case for now, we trigger a full invalidation if (last_invalidate_value < 0 || IsValueUpdatePending) { last_invalidate_value = current_value; InvalidateRender (); return; } double max = Math.Max (last_invalidate_value, current_value) * RenderSize.Width; double min = Math.Min (last_invalidate_value, current_value) * RenderSize.Width; Rect region = new Rect ( InvalidationRect.X + min, InvalidationRect.Y, (max - min) + 2 * ThrobberSize, InvalidationRect.Height ); last_invalidate_value = current_value; InvalidateRender (region); }*/ /*protected override Rect InvalidationRect { get { return new Rect ( -Margin.Left - ThrobberSize / 2, -Margin.Top, Allocation.Width + ThrobberSize, Allocation.Height); } }*/ protected override void ClippedRender (Cairo.Context cr) { double throbber_r = ThrobberSize / 2.0; double throbber_x = Math.Round (RenderSize.Width * (IsValueUpdatePending ? PendingValue : Value)); double throbber_y = (Allocation.Height - ThrobberSize) / 2.0 - Margin.Top + throbber_r; double bar_w = RenderSize.Width * Value; Theme.Widget.StyleContext.Save (); Theme.Widget.StyleContext.AddClass ("entry"); Theme.Widget.StyleContext.RenderBackground (cr, 0, 0, RenderSize.Width, RenderSize.Height); var color = CairoExtensions.GdkRGBAToCairoColor (Theme.Widget.StyleContext.GetColor (Gtk.StateFlags.Active)); Theme.Widget.StyleContext.Restore (); // TODO get Dark color Color fill_color = CairoExtensions.ColorShade (color, 0.4); Color light_fill_color = CairoExtensions.ColorShade (color, 0.3); fill_color.A = 1.0; light_fill_color.A = 1.0; using (var fill = new LinearGradient (0, 0, 0, RenderSize.Height)) { fill.AddColorStop (0, light_fill_color); fill.AddColorStop (0.5, fill_color); fill.AddColorStop (1, light_fill_color); cr.Rectangle (0, 0, bar_w, RenderSize.Height); cr.SetSource (fill); cr.Fill (); cr.SetSourceColor (fill_color); cr.Arc (throbber_x, throbber_y, throbber_r, 0, Math.PI * 2); cr.Fill (); } } public override Size Measure (Size available) { Height = BarSize; return DesiredSize = new Size (base.Measure (available).Width, Height + Margin.Top + Margin.Bottom); } private double bar_size = 3; public virtual double BarSize { get { return bar_size; } set { bar_size = value; } } private double throbber_size = 7; public virtual double ThrobberSize { get { return throbber_size; } set { throbber_size = value; } } private double value; public virtual double Value { get { return this.value; } set { if (value < 0.0 || value > 1.0) { throw new ArgumentOutOfRangeException ("Value", "Must be between 0.0 and 1.0 inclusive"); } else if (this.value == value) { return; } this.value = value; Invalidate (); OnValueChanged (); } } private bool is_value_update_pending; public virtual bool IsValueUpdatePending { get { return is_value_update_pending; } set { is_value_update_pending = value; } } private double pending_value; public virtual double PendingValue { get { return pending_value; } set { if (value < 0.0 || value > 1.0) { throw new ArgumentOutOfRangeException ("Value", "Must be between 0.0 and 1.0 inclusive"); } else if (pending_value == value) { return; } pending_value = value; Invalidate (); OnPendingValueChanged (); } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: Viewport3D.cs // // Description: Viewport3D element is a UIElement that contains a 3D // scene and a camera that defines the scene's projection into the 2D // rectangle of the control. // // History: // 11/17/2003 : danwo - created. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using System; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Media; using System.Windows.Media.Media3D; using System.Windows.Markup; using System.Windows.Threading; namespace System.Windows.Controls { /// <summary> /// The Viewport3D provides the Camera and layout bounds /// required to project the Visual3Ds into 2D. The Viewport3D /// is the bridge between 2D visuals and 3D. /// </summary> [ContentProperty("Children")] [Localizability(LocalizationCategory.NeverLocalize)] public class Viewport3D : FrameworkElement, IAddChild { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors static Viewport3D() { // Viewport3Ds do not really have a "Desired Bounds" since the // camera frustum is scaled to the width of the viewport rect. // As a result, layout never imposes a clip on Viewport3D. // // This makes it very easy to render Visual3Ds outside of the // layout bounds. Most framework users find this surprising. // As a result, we clip Viewport3Ds to bounds by default. ClipToBoundsProperty.OverrideMetadata(typeof(Viewport3D), new PropertyMetadata(BooleanBoxes.TrueBox)); } /// <summary> /// Viewport3D Constructor /// </summary> public Viewport3D() { _viewport3DVisual = new Viewport3DVisual(); // The value for the Camera property and the Children property on Viewport3D // will also be the value for these properties on the Viewport3DVisual we // create as an internal Visual child. This then will cause these values to // be shared, which will break property inheritance, dynamic resource references // and databinding. To prevent this, we mark the internal // Viewport3DVisual.CanBeInheritanceContext to be false, allowing Camera and // Children to only pick up value context from the Viewport3D (this). _viewport3DVisual.CanBeInheritanceContext = false; this.AddVisualChild(_viewport3DVisual); // NTRAID#Longhorn-1219113-7/11/2005-[....] XamlSerializer does not support RO DPs // // The XamlSerializer currently only serializes locally set properties. To // work around this we intentionally promote our ReadOnly Children // property to locally set. // SetValue(ChildrenPropertyKey, _viewport3DVisual.Children); _viewport3DVisual.SetInheritanceContextForChildren(this); } #endregion //------------------------------------------------------ // // Public properties // //------------------------------------------------------ #region Properties /// <summary> /// The DependencyProperty for the Camera property. /// </summary> public static readonly DependencyProperty CameraProperty = Viewport3DVisual.CameraProperty.AddOwner( typeof(Viewport3D), new FrameworkPropertyMetadata( FreezableOperations.GetAsFrozen(new PerspectiveCamera()), new PropertyChangedCallback(OnCameraChanged))); private static void OnCameraChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Viewport3D owner = (Viewport3D) d; if (!e.IsASubPropertyChange) { owner._viewport3DVisual.Camera = (Camera) e.NewValue; } } /// <summary> /// Camera for viewing scene. If no camera is specified, then a default will be provided. /// </summary> public Camera Camera { get { return (Camera) GetValue(CameraProperty); } set { SetValue(CameraProperty, value); } } private static readonly DependencyPropertyKey ChildrenPropertyKey = DependencyProperty.RegisterReadOnly( "Children", typeof(Visual3DCollection), typeof(Viewport3D), new FrameworkPropertyMetadata((object) null)); /// <summary> /// The 3D children of the Viewport3D /// </summary> public static readonly DependencyProperty ChildrenProperty = ChildrenPropertyKey.DependencyProperty; /// <summary> /// The 3D children of this Viewport3D. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public Visual3DCollection Children { get { return (Visual3DCollection) GetValue(ChildrenProperty); } } #endregion //------------------------------------------------------ // // Protected methods // //------------------------------------------------------ #region Protected methods /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override AutomationPeer OnCreateAutomationPeer() { return new Viewport3DAutomationPeer(this); } /// <summary> /// Viewport3D arranges its children to fill whatever it is given. /// </summary> /// <param name="finalSize">Size that Viewport3D will assume.</param> protected override Size ArrangeOverride(Size finalSize) { Rect newBounds = new Rect(new Point(), finalSize); _viewport3DVisual.Viewport = newBounds; return finalSize; } /// <summary> /// Derived class must implement to support Visual children. The method must return /// the child at the specified index. Index must be between 0 and GetVisualChildrenCount-1. /// /// By default a Visual does not have any children. /// /// Remark: /// During this virtual call it is not valid to modify the Visual tree. /// </summary> protected override Visual GetVisualChild(int index) { //added in the constructor so 1 children always exist switch(index) { case 0: return _viewport3DVisual; default: throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } } /// <summary> /// Derived classes override this property to enable the Visual code to enumerate /// the Visual children. Derived classes need to return the number of children /// from this method. /// /// By default a Visual does not have any children. /// /// Remark: During this virtual method the Visual tree must not be modified. /// </summary> protected override int VisualChildrenCount { //children are added in the constructor get { return 1; } } #endregion Protected methods //------------------------------------------------------ // // Private fields // //------------------------------------------------------ #region Private Fields private readonly Viewport3DVisual _viewport3DVisual; #endregion Private Fields //------------------------------------------------------ // // IAddChild implementation // //------------------------------------------------------ void IAddChild.AddChild(Object value) { if (value == null) { throw new ArgumentNullException("value"); } Visual3D visual3D = value as Visual3D; if (visual3D == null) { throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(Visual3D)), "value"); } Children.Add(visual3D); } void IAddChild.AddText(string text) { // The only text we accept is whitespace, which we ignore. XamlSerializerUtil.ThrowIfNonWhiteSpaceInAddText(text, this); } } }
using System; using System.Collections.Generic; namespace MaLamaLama.Util{ public class SkipList<T>{ private static int DefaultHeight=(int)(Math.Log(1000000))+1; private int size; private int height; private int[] heightList; private int heightPointer; private int heightPointerMax; private int circularEdge=-1; // TODO: gotta figure out this protection level thing and fix this from public! public SkipListElement<T> firstElement; public SkipList(int expected_size){ this.height=(int)(Math.Log(expected_size))+1; Init(); } public SkipList(){ this.height=DefaultHeight; Init(); } private void Init(){ // Setup dummy element for the start of the list firstElement=new SkipListElement<T>(height,-1,default(T)); // Generate the correct distribution of heights for the given list height List<int> tmp=new List<int>(); for(int i=0;i<height;i++){ for(int x=0;x<Math.Pow(2,i);x++){ tmp.Add((height-1)-i); heightPointer++; } } // Randomize heights and move them to an array heightPointerMax=heightPointer; heightPointer=0; heightList=new int[heightPointerMax]; // TODO: Is there really no shuffle/randomize library call in .net? Random rnd=new Random(); int n=tmp.Count; while(n>1){ n--; int k=rnd.Next(n+1); int v=tmp[k]; tmp[k]=tmp[n]; tmp[n]=v; } for(int i=0;i<tmp.Count;i++){ heightList[i]=tmp[i]; } } private int GetHeight(int index,T element){ // correct index if(index>=circularEdge)index=index % circularEdge; // **** Power of two populated lookup table heightPointer++; if(heightPointer>=heightPointerMax)heightPointer=0; return heightList[heightPointer]; } public void Clear(){ // Setup new dummy element for the start of the list firstElement=new SkipListElement<T>(height,-1); } public void SetCircular(int s){ circularEdge=s; } // TODO: This should be turned into a count property.. how? public int Size(){ return size; } // TODO: Should this be a property too? public bool IsEmpty(){ return size==0; } public void Add(int index, T value){ // correct index if(circularEdge>-1 && index>=circularEdge)index=index % circularEdge; // Setup new element for addition int newHeight=GetHeight(index,value); SkipListElement<T> element=new SkipListElement<T>(height,index,value); // Look for an existing element with the same index. // Start at the dummy element that holds no value SkipListElement<T> current = firstElement; // Go through each level from the top for(int i=height-1;i>=0;i--){ // Keep going sideways at the current level until the pointer to the next has a too high index while(current.pointers[i]!=null){ if (current.pointers[i].index==index){ // This element has the same index, add the value and return current.pointers[i].Add(value); return; } if(current.pointers[i].index>index){ // At this point, current holds the largest index at this level that is smaller than our desired index // so it's time to go down a step break; } // Go sideways at this level current=current.pointers[i]; } } // This index of the new element was not currently found in the list current=firstElement; // Go through each level from the top for(int i=height-1;i>=0;i--){ // Keep going sideways at the current level until the pointer to the next has a too high index while(current.pointers[i]!=null){ if(current.pointers[i].index>index){ // At this point, current holds the largest index at this level that is smaller than our desired index // so it's time to go down a step break; } // Go sideways at this level current=current.pointers[i]; } // We are at the last element in the current level that is smaller than or our index, if this level is // lower or equal to our desired level, this pointer should point to us and we should point to it's // previous target if(i<=newHeight){ element.pointers[i]=current.pointers[i]; current.pointers[i]=element; } } size++; } public T Set(int index, T value){ // correct index if(circularEdge>-1 && index>=circularEdge)index=index % circularEdge; // Setup new element for addition int newHeight=GetHeight(index,value); SkipListElement<T> element=new SkipListElement<T>(height,index,value); // Look for an existing element with the same index. // Start at the dummy element that holds no value SkipListElement<T> current = firstElement; // Go through each level from the top for(int i=height-1;i>=0;i--){ // Keep going sideways at the current level until the pointer to the next has a too high index while(current.pointers[i]!=null){ if (current.pointers[i].index==index){ // This element has the same index, replace the value and return the old T old=current.pointers[i].list[0]; current.pointers[i].Replace(value); return old; } if(current.pointers[i].index>index){ // At this point, current holds the largest index at this level that is smaller than our desired index // so it's time to go down a step break; } // Go sideways at this level current=current.pointers[i]; } } // This index of the new element was not currently found in the list current=firstElement; // Go through each level from the top for(int i=height-1;i>=0;i--){ // Keep going sideways at the current level until the pointer to the next has a too high index while(current.pointers[i]!=null){ if(current.pointers[i].index>index){ // At this point, current holds the largest index at this level that is smaller than our desired index // so it's time to go down a step break; } // Go sideways at this level current=current.pointers[i]; } // We are at the last element in the current level that is smaller than or our index, if this level is // lower or equal to our desired level, this pointer should point to us and we should point to it's // previous target if(i<=newHeight){ element.pointers[i]=current.pointers[i]; current.pointers[i]=element; } } size++; return default(T); } public T Remove(int index){ // correct index if(circularEdge>-1 && index>=circularEdge)index=index % circularEdge; T value=default(T); // Start at the dummy element that holds no value SkipListElement<T> current = firstElement; // Go through each level from the top for(int i=height-1;i>=0;i--){ // Keep going sideways at the current level until the pointer to the next has a too high index while(current.pointers[i]!=null){ // If the next element has the right index if(current.pointers[i].index==index){ // Store the first value for return at the end value=current.pointers[i].list[0]; // Set the current elements pointer to the element pointed to by the element we are removing current.pointers[i]=current.pointers[i].pointers[i]; // Go down a step to keep correcting pointers where needed break; } if(current.pointers[i].index>index){ // At this point, current holds the largest index at this level that is smaller than our desired index // so it's time to go down a step break; } // Go sideways at this level current=current.pointers[i]; } } // If we found a value, decrease the size counter and return it if(value!=null)size--; return value; } public int GetFirstIndex(){ // If there are any elements in the list, return the index of the first if(firstElement.pointers[0]!=null)return firstElement.pointers[0].index; return -1; } public int GetLastIndex(){ // If the list is empty return -1 if(firstElement.pointers[0]==null)return -1; // Start at the dummy element that holds no value SkipListElement<T> current=firstElement; // Go through each level from the top for(int i=height-1;i>=0;i--){ // Keep going sideways at the current level until the pointer to the next is null, then go down while(current.pointers[i]!=null){ // Go sideways at this level current=current.pointers[i]; } } return current.index; } public T Get(int index){ // correct index if(circularEdge>-1 && index>=circularEdge)index=index % circularEdge; // Start at the dummy element that holds no value SkipListElement<T> current=firstElement; // Go through each level from the top for(int i=height-1;i>=0;i--){ // Keep going sideways at the current level until the pointer to the next has a too high index while(current.pointers[i]!=null){ // If the next element has the right index, return it's first value if(current.pointers[i].index==index){ return current.pointers[i].list[0]; } if(current.pointers[i].index>index){ // At this point, current holds the largest index at this level that is smaller than our desired index // so it's time to go down a step break; } // Go sideways at this level current=current.pointers[i]; } } return default(T); } public T GetClosest(int index){ // correct index if(circularEdge>-1 && index>=circularEdge)index=index % circularEdge; // Start at the dummy element that holds no value SkipListElement<T> current=firstElement; // Quick check for empty list if(current.pointers[0]==null)return default(T); // Quick check for one element list if(size==1)return current.pointers[0].list[0]; // Go through each level from the top for(int i=height-1;i>=0;i--){ // Keep going sideways at the current level until the pointer to the next has a too high index while(current.pointers[i]!=null){ // If the next element has the right index, return it's first value if(current.pointers[i].index==index){ return current.pointers[i].list[0]; } if(current.pointers[i].index>index){ // At this point, current holds the largest index at this level that is smaller than our desired index // so it's time to go down a step break; } // Go sideways at this level current=current.pointers[i]; } } // TODO: this whole section ought to be written neater, having distance calculation and comparison code only once if(current.index==-1){ // We are still positioned at the starting element. // If we are not circular, the first element is it if(circularEdge==-1)return current.pointers[0].list[0]; // ...otherwise, this means either the first or the last element is the closest int first=GetFirstIndex(); int last=GetLastIndex(); // Calculate distances from index int d1=first-index; int d2=index+(circularEdge-last); // return closest if(d1<d2){ return current.pointers[0].list[0]; }else{ return Get(last); } } if(current.pointers[0]==null){ // We are positioned at the end of the list, if we are not circular the last element must be the one // closest to our desired index. if(circularEdge==-1)return current.list[0]; int first=GetFirstIndex(); int last=GetLastIndex(); // Calculate distances from index int d1=first+(circularEdge-index); int d2=index-last; // return closest if(d1<d2){ return Get(first); }else{ return Get(last); } } // We are somewhere between elements. Calculate the distance to current and the next element // and return the one closest to the desired index. int d3=index-current.index; int d4=current.pointers[0].index-index; if(d3<d4)return current.list[0]; return current.pointers[0].list[0]; } public List<T> getAll(int index){ // correct index if(circularEdge>-1 && index>=circularEdge)index=index % circularEdge; List<T> result=new List<T>(); // Start at the dummy element that holds no value SkipListElement<T> current=firstElement; for(int i=height-1;i>=0;i--){ // Keep going sideways at the current level until the pointer to the next has a too high index while(current.pointers[i]!=null){ // If the next element has the right index, return all of its values if(current.pointers[i].index==index){ current=current.pointers[i]; for(int n=0;n<current.list.Length;n++){ if(current.list[n]!=null)result.Add(current.list[n]); } return result; } if(current.pointers[i].index>index){ // At this point, current holds the largest index at this level that is smaller than our desired index // so it's time to go down a step break; } // Go sideways at this level current=current.pointers[i]; } } return result; } // TODO: We should add a version matching the .net List.GetRange public List<T> SubList(int startIndex,int endIndex){ // correct index if(circularEdge>-1){ if(startIndex>=circularEdge)startIndex=startIndex % circularEdge; if(endIndex>=circularEdge)endIndex=endIndex % circularEdge; } // BUG: is this really the semantics we want for ranges? List<T> result=new List<T>(); // Start at the dummy element that holds no value SkipListElement<T> current=firstElement; for(int i=height-1;i>=0;i--){ // Keep going sideways at the current level until the pointer to the next has a too high index while(current.pointers[i]!=null){ if (current.pointers[i].index == startIndex){ // We have found an element that matches the starting index current=current.pointers[i]; for(int n=0;n<current.list.Length;n++){ if(current.list[n]!=null)result.Add(current.list[n]); } if(endIndex>=startIndex){ // Keep going at the lowest level while there are still elements in the list and // their index are lower than or equal to the end index while(current.pointers[0]!=null && current.pointers[0].index<=endIndex){ for(int n=0;n<current.pointers[0].list.Length;n++){ if(current.pointers[0].list[n]!=null)result.Add(current.pointers[0].list[n]); } current=current.pointers[0]; } return result; }else{ // First take all elements to the end while(current.pointers[0]!=null){ for(int n=0;n<current.pointers[0].list.Length;n++){ if(current.pointers[0].list[n]!=null)result.Add(current.pointers[0].list[n]); } current=current.pointers[0]; } current=firstElement; // ...then take all elements until the end index while(current.pointers[0]!=null && current.pointers[0].index<=endIndex){ for(int n=0;n<current.pointers[0].list.Length;n++){ if(current.pointers[0].list[n]!=null)result.Add(current.pointers[0].list[n]); } current=current.pointers[0]; } return result; } } if(current.pointers[i].index>startIndex){ // At this point, current holds the largest index at this level that is smaller than our desired start index // so it's time to go down a step break; } // Go sideways at this level current=current.pointers[i]; } } // If we got to this point there was no exact match to our desired starting index, we either ran out of elements or // we are at the last element that is smaller than our desired starting index. if(endIndex>=startIndex){ // Keep going at the lowest level while there are still elements in the list and // their index are lower than or equal to the end index while(current.pointers[0]!=null && current.pointers[0].index<=endIndex){ for(int n=0;n<current.pointers[0].list.Length;n++){ if(current.pointers[0].list[n]!=null)result.Add(current.pointers[0].list[n]); } current=current.pointers[0]; } return result; }else{ // First take all elements to the end while(current.pointers[0]!=null){ for(int n=0;n<current.pointers[0].list.Length;n++){ if(current.pointers[0].list[n]!=null)result.Add(current.pointers[0].list[n]); } current=current.pointers[0]; } current=firstElement; // ...then take all elements until the end index while(current.pointers[0]!=null && current.pointers[0].index<=endIndex){ for(int n=0;n<current.pointers[0].list.Length;n++){ if(current.pointers[0].list[n]!=null)result.Add(current.pointers[0].list[n]); } current=current.pointers[0]; } return result; } } public void Dump(){ Console.WriteLine("SkipList.Dump()"); SkipListElement<T> e=firstElement; while(e!=null){ Console.Write(" - "+e.index+","+e.list[0]+" : ("); for(int i=0;i<height;i++){ if(e.pointers[i]!=null){ Console.Write(e.pointers[i].list[0]); } Console.Write(","); } Console.WriteLine(")"); e=e.pointers[0]; } } /* IEnumerator<T> IEnumerable<T>.GetEnumerator(){ return (IEnumerator<T>) GetEnumerator(); }*/ public SkipListEnumerator<T> GetEnumerator() { return new SkipListEnumerator<T>(this); } } public class SkipListEnumerator<T> : IEnumerator<T>{ private SkipList<T> list; private SkipListElement<T> current,last; private int index,lastIndex; public SkipListEnumerator(SkipList<T> list){ this.list=list; current=list.firstElement; index=0; last=null; lastIndex=-1; } public bool MoveNext(){ if(index < current.list.Length && current.list[index]!=null)return true; return current.pointers[0]!=null; } public object Current{ get{ return getCurrent(); } } private T getCurrent(){ // If we have values left in the current element, return it if(index < current.list.Length && current.list[index]!=null){ last=current; lastIndex=index; return current.list[index ++]; } // If not, move to next element current=current.pointers[0]; index=0; // if(current==null)throw new NoSuchElementException(); // TODO: This seems wrong return getCurrent(); // This recursion should happen once at most unless an error left empty skiplist elements in the list } public void Reset(){ current=list.firstElement; index=0; last=null; lastIndex=-1; } public void Dispose(){ } T IEnumerator<T>.Current{ get{ return getCurrent(); } } } public class SkipListElement<T>{ public SkipListElement<T>[] pointers; public int index; public T[] list; public SkipListElement(int height,int index,T value){ pointers=new SkipListElement<T>[height]; this.index=index; this.list=new T[1]; this.list[0]=value; } public SkipListElement(int height,int index){ pointers=new SkipListElement<T>[height]; this.index=index; this.list=new T[1]; this.list[0]=default(T); } // TODO: Is this really the standard way to compare objects in c#? public bool Contains(T o){ foreach(T o2 in list){ if(o2!=null)if(o.Equals(o2))return true; } return false; } public void Replace(T obj){ // Clear out any old values list=new T[1]; // Set the new value list[0]=obj; } public void Add(T obj){ // First check to see that we have free space in the current array if(list[list.Length-1]!=null){ // We need to expand capacity, do this by doubling the current capacity T[] tmp=new T[list.Length*2]; // Copy the old array into the first part of the new array for(int i=0;i<list.Length;i++)tmp[i]=list[i]; list=tmp; } // Place the new value in the first free spot for(int i=0;i<list.Length;i++){ if(list[i]==null){ list[i]=obj; break; } } } public void removeValue(int index){ // Start at the given index and move every element one index down for(int i=index;i<list.Length-1;i++){ list[i]=list[i+1]; } // set the last element to null list[list.Length-1]=default(T); // TODO: is this the correct way of dealing with null values in generics? } } public class Test{ static void Main(){ Console.WriteLine("Creating new list"); SkipList<string> l=new SkipList<string>(); l.Dump(); Console.WriteLine("\nAdding values"); l.Set(1,"A 1"); l.Set(12,"A 12"); l.Set(7,"A 7"); l.Set(9,"A 9"); l.Dump(); Console.WriteLine("\nAdding values"); l.Set(5,"B 5"); l.Set(16,"B 16"); l.Add(12,"B 12"); l.Set(2,"B 2"); l.Set(1,"B 1"); l.Dump(); Console.WriteLine("\nAdding and removing values"); l.Add(12,"C 12"); l.Remove(9); l.Dump(); Console.WriteLine("\nIterating through all values"); Console.Write("["); foreach(String str in l){ Console.Write(str+","); } Console.WriteLine("]"); Console.WriteLine("\nFetching values"); Console.WriteLine("l.GetFirstIndex()->"+l.GetFirstIndex()); Console.WriteLine("l.GetLastIndex()->"+l.GetLastIndex()); Console.WriteLine("l.Get(12)->"+l.Get(12)); Console.WriteLine("l.Get(13)->"+l.Get(13)); Console.Write("l.getAll(12)->["); foreach(string str in l.getAll(12)){ Console.Write(str+", "); } Console.WriteLine("]"); Console.Write("l.SubList(2,7)->["); foreach(string str in l.SubList(2,7)){ Console.Write(str+", "); } Console.WriteLine("]"); Console.Write("l.SubList(3,7)->["); foreach(string str in l.SubList(3,7)){ Console.Write(str+", "); } Console.WriteLine("]"); Console.Write("l.SubList(4,13)->"); foreach(string str in l.SubList(4,13)){ Console.Write(str+", "); } Console.WriteLine("]"); Console.WriteLine("l.GetClosest(3)->"+l.GetClosest(3)); Console.WriteLine("l.GetClosest(4)->"+l.GetClosest(4)); Console.WriteLine("l.GetClosest(31)->"+l.GetClosest(31)); Console.WriteLine("\nSetting the list to circular at 35"); l.SetCircular(35); Console.WriteLine("l.GetClosest(31)->"+l.GetClosest(31)); Console.WriteLine("l.GetClosest(0)->"+l.GetClosest(0)); Console.Write("l.subList(13,4)->["); foreach(string str in l.SubList(13,4)){ Console.Write(str+", "); } Console.WriteLine("]"); } } }
//------------------------------------------------------------------------------ // <copyright file="DbBuffer.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.ProviderBase { using System; using System.Data.Common; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; // 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) { offset += BaseOffset; Validate(offset, 2); 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); int length = UnsafeNativeMethods.lstrlenW(ptr); Validate(offset, (2*(length+1))); value = Marshal.PtrToStringUni(ptr, length); } finally { if (mustRelease) { DangerousRelease(); } } return value; } 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) { Int64 value = ReadInt64(offset); return BitConverter.Int64BitsToDouble(value); } internal Int16 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 Int32 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 Int64 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 Single ReadSingle(int offset) { Int32 value = ReadInt32(offset); return *(Single*)&value; } override protected 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, Single value) { WriteInt32(offset, *(Int32*)&value); } internal void ZeroMemory() { bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr ptr = DangerousGetHandle(); SafeNativeMethods.ZeroMemory(ptr, (IntPtr)Length); } finally { if (mustRelease) { DangerousRelease(); } } } 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); } [ConditionalAttribute("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 System.Linq; using AutoMapper; using Moq; using NUnit.Framework; using umbraco; using umbraco.cms.presentation; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Profiling; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Models.Mapping; using Umbraco.Web.PropertyEditors; namespace Umbraco.Tests.Models.Mapping { [TestFixture] public class ContentTypeModelMappingTests : BaseUmbracoConfigurationTest { //Mocks of services that can be setup on a test by test basis to return whatever we want private readonly Mock<IContentTypeService> _contentTypeService = new Mock<IContentTypeService>(); private readonly Mock<IContentService> _contentService = new Mock<IContentService>(); private readonly Mock<IDataTypeService> _dataTypeService = new Mock<IDataTypeService>(); private Mock<PropertyEditorResolver> _propertyEditorResolver; private readonly Mock<IEntityService> _entityService = new Mock<IEntityService>(); private readonly Mock<IFileService> _fileService = new Mock<IFileService>(); [SetUp] public void Setup() { var nullCacheHelper = CacheHelper.CreateDisabledCacheHelper(); //Create an app context using mocks var appContext = new ApplicationContext( new DatabaseContext(Mock.Of<IScopeProviderInternal>(), Mock.Of<ILogger>(), Mock.Of<ISqlSyntaxProvider>(), "test"), //Create service context using mocks new ServiceContext( contentService: _contentService.Object, contentTypeService:_contentTypeService.Object, dataTypeService:_dataTypeService.Object, entityService:_entityService.Object, fileService: _fileService.Object), nullCacheHelper, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); //create a fake property editor resolver to return fake property editors Func<IEnumerable<Type>> typeListProducerList = Enumerable.Empty<Type>; _propertyEditorResolver = new Mock<PropertyEditorResolver>( //ctor args Mock.Of<IServiceProvider>(), Mock.Of<ILogger>(), typeListProducerList, nullCacheHelper.RuntimeCache); Mapper.Initialize(configuration => { //initialize our content type mapper var mapper = new ContentTypeModelMapper(new Lazy<PropertyEditorResolver>(() => _propertyEditorResolver.Object)); mapper.ConfigureMappings(configuration, appContext); var entityMapper = new EntityModelMapper(); entityMapper.ConfigureMappings(configuration, appContext); }); } [Test] public void MemberTypeSave_To_IMemberType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>())) .Returns(Mock.Of<IDataTypeDefinition>( definition => definition.Id == 555 && definition.PropertyEditorAlias == "myPropertyType" && definition.DatabaseType == DataTypeDatabaseType.Nvarchar)); var display = CreateMemberTypeSave(); //Act var result = Mapper.Map<IMemberType>(display); //Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); Assert.AreEqual(display.Id, result.Id); Assert.AreEqual(display.Name, result.Name); Assert.AreEqual(display.ParentId, result.ParentId); Assert.AreEqual(display.Path, result.Path); Assert.AreEqual(display.Thumbnail, result.Thumbnail); Assert.AreEqual(display.IsContainer, result.IsContainer); Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot); Assert.AreEqual(display.CreateDate, result.CreateDate); Assert.AreEqual(display.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); for (var i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); var propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeDefinitionId); Assert.AreEqual(propTypes.ElementAt(j).MemberCanViewProperty, result.MemberCanViewProperty(result.PropertyTypes.ElementAt(j).Alias)); Assert.AreEqual(propTypes.ElementAt(j).MemberCanEditProperty, result.MemberCanEditProperty(result.PropertyTypes.ElementAt(j).Alias)); Assert.AreEqual(propTypes.ElementAt(j).IsSensitiveData, result.IsSensitiveProperty(result.PropertyTypes.ElementAt(j).Alias)); } } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } } [Test] public void MediaTypeSave_To_IMediaType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>())) .Returns(Mock.Of<IDataTypeDefinition>( definition => definition.Id == 555 && definition.PropertyEditorAlias == "myPropertyType" && definition.DatabaseType == DataTypeDatabaseType.Nvarchar)); var display = CreateMediaTypeSave(); //Act var result = Mapper.Map<IMediaType>(display); //Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); Assert.AreEqual(display.Id, result.Id); Assert.AreEqual(display.Name, result.Name); Assert.AreEqual(display.ParentId, result.ParentId); Assert.AreEqual(display.Path, result.Path); Assert.AreEqual(display.Thumbnail, result.Thumbnail); Assert.AreEqual(display.IsContainer, result.IsContainer); Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot); Assert.AreEqual(display.CreateDate, result.CreateDate); Assert.AreEqual(display.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); for (var i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); var propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeDefinitionId); } } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } } [Test] public void ContentTypeSave_To_IContentType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>())) .Returns(Mock.Of<IDataTypeDefinition>( definition => definition.Id == 555 && definition.PropertyEditorAlias == "myPropertyType" && definition.DatabaseType == DataTypeDatabaseType.Nvarchar)); _fileService.Setup(x => x.GetTemplate(It.IsAny<string>())) .Returns((string alias) => Mock.Of<ITemplate>( definition => definition.Id == alias.GetHashCode() && definition.Alias == alias)); var display = CreateContentTypeSave(); //Act var result = Mapper.Map<IContentType>(display); //Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); Assert.AreEqual(display.Id, result.Id); Assert.AreEqual(display.Name, result.Name); Assert.AreEqual(display.ParentId, result.ParentId); Assert.AreEqual(display.Path, result.Path); Assert.AreEqual(display.Thumbnail, result.Thumbnail); Assert.AreEqual(display.IsContainer, result.IsContainer); Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot); Assert.AreEqual(display.CreateDate, result.CreateDate); Assert.AreEqual(display.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); for (var i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); var propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeDefinitionId); } } var allowedTemplateAliases = display.AllowedTemplates .Concat(new[] {display.DefaultTemplate}) .Distinct(); Assert.AreEqual(allowedTemplateAliases.Count(), result.AllowedTemplates.Count()); for (var i = 0; i < display.AllowedTemplates.Count(); i++) { Assert.AreEqual(display.AllowedTemplates.ElementAt(i), result.AllowedTemplates.ElementAt(i).Alias); } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } } [Test] public void MediaTypeSave_With_Composition_To_IMediaType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>())) .Returns(Mock.Of<IDataTypeDefinition>( definition => definition.Id == 555 && definition.PropertyEditorAlias == "myPropertyType" && definition.DatabaseType == DataTypeDatabaseType.Nvarchar)); var display = CreateCompositionMediaTypeSave(); //Act var result = Mapper.Map<IMediaType>(display); //Assert //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); } [Test] public void ContentTypeSave_With_Composition_To_IContentType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>())) .Returns(Mock.Of<IDataTypeDefinition>( definition => definition.Id == 555 && definition.PropertyEditorAlias == "myPropertyType" && definition.DatabaseType == DataTypeDatabaseType.Nvarchar)); var display = CreateCompositionContentTypeSave(); //Act var result = Mapper.Map<IContentType>(display); //Assert //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); } [Test] public void IMemberType_To_MemberTypeDisplay() { //Arrange // setup the mocks to return the data we want to test against... // for any call to GetPreValuesCollectionByDataTypeId just return an empty dictionary for now // TODO: but we'll need to change this to return some pre-values to test the mappings _dataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny<int>())) .Returns(new PreValueCollection(new Dictionary<string, PreValue>())); //return a textbox property editor for any requested editor by alias _propertyEditorResolver.Setup(resolver => resolver.GetByAlias(It.IsAny<string>())) .Returns(new TextboxPropertyEditor()); //for testing, just return a list of whatever property editors we want _propertyEditorResolver.Setup(resolver => resolver.PropertyEditors) .Returns(new[] { new TextboxPropertyEditor() }); var memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.MemberTypePropertyTypes[memberType.PropertyTypes.Last().Alias] = new MemberTypePropertyProfileAccess(true, true, true); MockedContentTypes.EnsureAllIds(memberType, 8888); //Act var result = Mapper.Map<MemberTypeDisplay>(memberType); //Assert Assert.AreEqual(memberType.Alias, result.Alias); Assert.AreEqual(memberType.Description, result.Description); Assert.AreEqual(memberType.Icon, result.Icon); Assert.AreEqual(memberType.Id, result.Id); Assert.AreEqual(memberType.Name, result.Name); Assert.AreEqual(memberType.ParentId, result.ParentId); Assert.AreEqual(memberType.Path, result.Path); Assert.AreEqual(memberType.Thumbnail, result.Thumbnail); Assert.AreEqual(memberType.IsContainer, result.IsContainer); Assert.AreEqual(memberType.CreateDate, result.CreateDate); Assert.AreEqual(memberType.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(memberType.PropertyGroups.Count(), result.Groups.Count()); for (var i = 0; i < memberType.PropertyGroups.Count(); i++) { Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name); var propTypes = memberType.PropertyGroups.ElementAt(i).PropertyTypes; Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeDefinitionId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); Assert.AreEqual(memberType.MemberCanViewProperty(propTypes.ElementAt(j).Alias), result.Groups.ElementAt(i).Properties.ElementAt(j).MemberCanViewProperty); Assert.AreEqual(memberType.MemberCanEditProperty(propTypes.ElementAt(j).Alias), result.Groups.ElementAt(i).Properties.ElementAt(j).MemberCanEditProperty); } } Assert.AreEqual(memberType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < memberType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(memberType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void IMediaType_To_MediaTypeDisplay() { //Arrange // setup the mocks to return the data we want to test against... // for any call to GetPreValuesCollectionByDataTypeId just return an empty dictionary for now // TODO: but we'll need to change this to return some pre-values to test the mappings _dataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny<int>())) .Returns(new PreValueCollection(new Dictionary<string, PreValue>())); //return a textbox property editor for any requested editor by alias _propertyEditorResolver.Setup(resolver => resolver.GetByAlias(It.IsAny<string>())) .Returns(new TextboxPropertyEditor()); //for testing, just return a list of whatever property editors we want _propertyEditorResolver.Setup(resolver => resolver.PropertyEditors) .Returns(new[] { new TextboxPropertyEditor() }); var mediaType = MockedContentTypes.CreateImageMediaType(); MockedContentTypes.EnsureAllIds(mediaType, 8888); //Act var result = Mapper.Map<MediaTypeDisplay>(mediaType); //Assert Assert.AreEqual(mediaType.Alias, result.Alias); Assert.AreEqual(mediaType.Description, result.Description); Assert.AreEqual(mediaType.Icon, result.Icon); Assert.AreEqual(mediaType.Id, result.Id); Assert.AreEqual(mediaType.Name, result.Name); Assert.AreEqual(mediaType.ParentId, result.ParentId); Assert.AreEqual(mediaType.Path, result.Path); Assert.AreEqual(mediaType.Thumbnail, result.Thumbnail); Assert.AreEqual(mediaType.IsContainer, result.IsContainer); Assert.AreEqual(mediaType.CreateDate, result.CreateDate); Assert.AreEqual(mediaType.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(mediaType.PropertyGroups.Count(), result.Groups.Count()); for (var i = 0; i < mediaType.PropertyGroups.Count(); i++) { Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name); var propTypes = mediaType.PropertyGroups.ElementAt(i).PropertyTypes; Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeDefinitionId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); } } Assert.AreEqual(mediaType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < mediaType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(mediaType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void IContentType_To_ContentTypeDisplay() { //Arrange // setup the mocks to return the data we want to test against... // for any call to GetPreValuesCollectionByDataTypeId just return an empty dictionary for now // TODO: but we'll need to change this to return some pre-values to test the mappings _dataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny<int>())) .Returns(new PreValueCollection(new Dictionary<string, PreValue>())); //return a textbox property editor for any requested editor by alias _propertyEditorResolver.Setup(resolver => resolver.GetByAlias(It.IsAny<string>())) .Returns(new TextboxPropertyEditor()); //for testing, just return a list of whatever property editors we want _propertyEditorResolver.Setup(resolver => resolver.PropertyEditors) .Returns(new[] { new TextboxPropertyEditor() }); var contentType = MockedContentTypes.CreateTextpageContentType(); MockedContentTypes.EnsureAllIds(contentType, 8888); //Act var result = Mapper.Map<DocumentTypeDisplay>(contentType); //Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); Assert.AreEqual(contentType.Id, result.Id); Assert.AreEqual(contentType.Name, result.Name); Assert.AreEqual(contentType.ParentId, result.ParentId); Assert.AreEqual(contentType.Path, result.Path); Assert.AreEqual(contentType.Thumbnail, result.Thumbnail); Assert.AreEqual(contentType.IsContainer, result.IsContainer); Assert.AreEqual(contentType.CreateDate, result.CreateDate); Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(contentType.PropertyGroups.Count, result.Groups.Count()); for (var i = 0; i < contentType.PropertyGroups.Count; i++) { Assert.AreEqual(contentType.PropertyGroups[i].Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(contentType.PropertyGroups[i].Name, result.Groups.ElementAt(i).Name); var propTypes = contentType.PropertyGroups[i].PropertyTypes; Assert.AreEqual(propTypes.Count, result.Groups.ElementAt(i).Properties.Count()); for (var j = 0; j < propTypes.Count; j++) { Assert.AreEqual(propTypes[j].Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes[j].DataTypeDefinitionId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); } } Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count()); for (var i = 0; i < contentType.AllowedTemplates.Count(); i++) { Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id); } Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void MemberPropertyGroupBasic_To_MemberPropertyGroup() { _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>())) .Returns(new DataTypeDefinition("test")); var basic = new PropertyGroupBasic<MemberPropertyTypeBasic> { Id = 222, Name = "Group 1", SortOrder = 1, Properties = new[] { new MemberPropertyTypeBasic() { MemberCanEditProperty = true, MemberCanViewProperty = true, IsSensitiveData = true, Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = null } }, new MemberPropertyTypeBasic() { MemberCanViewProperty = false, MemberCanEditProperty = false, IsSensitiveData = false, Id = 34, SortOrder = 2, Alias = "prop2", Description = "property 2", DataTypeId = 99, GroupId = 222, Label = "Prop 2", Validation = new PropertyTypeValidation() { Mandatory = false, Pattern = null } }, } }; var contentType = new MemberTypeSave { Id = 0, ParentId = -1, Alias = "alias", Groups = new[] { basic } }; // proper group properties mapping takes place when mapping the content type, // not when mapping the group - because of inherited properties and such //var result = Mapper.Map<PropertyGroup>(basic); var result = Mapper.Map<IMemberType>(contentType).PropertyGroups[0]; Assert.AreEqual(basic.Name, result.Name); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Properties.Count(), result.PropertyTypes.Count()); } [Test] public void PropertyGroupBasic_To_PropertyGroup() { _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>())) .Returns(new DataTypeDefinition("test")); var basic = new PropertyGroupBasic<PropertyTypeBasic> { Id = 222, Name = "Group 1", SortOrder = 1, Properties = new[] { new PropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = null } }, new PropertyTypeBasic() { Id = 34, SortOrder = 2, Alias = "prop2", Description = "property 2", DataTypeId = 99, GroupId = 222, Label = "Prop 2", Validation = new PropertyTypeValidation() { Mandatory = false, Pattern = null } }, } }; var contentType = new DocumentTypeSave { Id = 0, ParentId = -1, Alias = "alias", AllowedTemplates = Enumerable.Empty<string>(), Groups = new[] { basic } }; // proper group properties mapping takes place when mapping the content type, // not when mapping the group - because of inherited properties and such //var result = Mapper.Map<PropertyGroup>(basic); var result = Mapper.Map<IContentType>(contentType).PropertyGroups[0]; Assert.AreEqual(basic.Name, result.Name); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Properties.Count(), result.PropertyTypes.Count()); } [Test] public void MemberPropertyTypeBasic_To_PropertyType() { _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>())) .Returns(new DataTypeDefinition("test")); var basic = new MemberPropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = "xyz" } }; var result = Mapper.Map<PropertyType>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.DataTypeId, result.DataTypeDefinitionId); Assert.AreEqual(basic.Label, result.Name); Assert.AreEqual(basic.Validation.Mandatory, result.Mandatory); Assert.AreEqual(basic.Validation.Pattern, result.ValidationRegExp); } [Test] public void PropertyTypeBasic_To_PropertyType() { _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>())) .Returns(new DataTypeDefinition("test")); var basic = new PropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = "xyz" } }; var result = Mapper.Map<PropertyType>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.DataTypeId, result.DataTypeDefinitionId); Assert.AreEqual(basic.Label, result.Name); Assert.AreEqual(basic.Validation.Mandatory, result.Mandatory); Assert.AreEqual(basic.Validation.Pattern, result.ValidationRegExp); } [Test] public void IMediaTypeComposition_To_MediaTypeDisplay() { //Arrange // setup the mocks to return the data we want to test against... // for any call to GetPreValuesCollectionByDataTypeId just return an empty dictionary for now // TODO: but we'll need to change this to return some pre-values to test the mappings _dataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny<int>())) .Returns(new PreValueCollection(new Dictionary<string, PreValue>())); _entityService.Setup(x => x.GetObjectType(It.IsAny<int>())) .Returns(UmbracoObjectTypes.DocumentType); //return a textbox property editor for any requested editor by alias _propertyEditorResolver.Setup(resolver => resolver.GetByAlias(It.IsAny<string>())) .Returns(new TextboxPropertyEditor()); //for testing, just return a list of whatever property editors we want _propertyEditorResolver.Setup(resolver => resolver.PropertyEditors) .Returns(new[] { new TextboxPropertyEditor() }); var ctMain = MockedContentTypes.CreateSimpleMediaType("parent", "Parent"); //not assigned to tab ctMain.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext) { Alias = "umbracoUrlName", Name = "Slug", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); MockedContentTypes.EnsureAllIds(ctMain, 8888); var ctChild1 = MockedContentTypes.CreateSimpleMediaType("child1", "Child 1", ctMain, true); ctChild1.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext) { Alias = "someProperty", Name = "Some Property", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }, "Another tab"); MockedContentTypes.EnsureAllIds(ctChild1, 7777); var contentType = MockedContentTypes.CreateSimpleMediaType("child2", "Child 2", ctChild1, true, "CustomGroup"); //not assigned to tab contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext) { Alias = "umbracoUrlAlias", Name = "AltUrl", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); MockedContentTypes.EnsureAllIds(contentType, 6666); //Act var result = Mapper.Map<MediaTypeDisplay>(contentType); //Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); Assert.AreEqual(contentType.Id, result.Id); Assert.AreEqual(contentType.Name, result.Name); Assert.AreEqual(contentType.ParentId, result.ParentId); Assert.AreEqual(contentType.Path, result.Path); Assert.AreEqual(contentType.Thumbnail, result.Thumbnail); Assert.AreEqual(contentType.IsContainer, result.IsContainer); Assert.AreEqual(contentType.CreateDate, result.CreateDate); Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false)); Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties)); Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false)); var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false)); Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count()); Assert.IsTrue(allPropertyIdsMapped.ContainsAll(allSourcePropertyIds)); Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any())); Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] { ctMain.Id, ctChild1.Id })); Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void IContentTypeComposition_To_ContentTypeDisplay() { //Arrange // setup the mocks to return the data we want to test against... // for any call to GetPreValuesCollectionByDataTypeId just return an empty dictionary for now // TODO: but we'll need to change this to return some pre-values to test the mappings _dataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny<int>())) .Returns(new PreValueCollection(new Dictionary<string, PreValue>())); _entityService.Setup(x => x.GetObjectType(It.IsAny<int>())) .Returns(UmbracoObjectTypes.DocumentType); //return a textbox property editor for any requested editor by alias _propertyEditorResolver.Setup(resolver => resolver.GetByAlias(It.IsAny<string>())) .Returns(new TextboxPropertyEditor()); //for testing, just return a list of whatever property editors we want _propertyEditorResolver.Setup(resolver => resolver.PropertyEditors) .Returns(new[] { new TextboxPropertyEditor() }); var ctMain = MockedContentTypes.CreateSimpleContentType(); //not assigned to tab ctMain.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext) { Alias = "umbracoUrlName", Name = "Slug", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); MockedContentTypes.EnsureAllIds(ctMain, 8888); var ctChild1 = MockedContentTypes.CreateSimpleContentType("child1", "Child 1", ctMain, true); ctChild1.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext) { Alias = "someProperty", Name = "Some Property", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }, "Another tab"); MockedContentTypes.EnsureAllIds(ctChild1, 7777); var contentType = MockedContentTypes.CreateSimpleContentType("child2", "Child 2", ctChild1, true, "CustomGroup"); //not assigned to tab contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext) { Alias = "umbracoUrlAlias", Name = "AltUrl", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); MockedContentTypes.EnsureAllIds(contentType, 6666); //Act var result = Mapper.Map<DocumentTypeDisplay>(contentType); //Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); Assert.AreEqual(contentType.Id, result.Id); Assert.AreEqual(contentType.Name, result.Name); Assert.AreEqual(contentType.ParentId, result.ParentId); Assert.AreEqual(contentType.Path, result.Path); Assert.AreEqual(contentType.Thumbnail, result.Thumbnail); Assert.AreEqual(contentType.IsContainer, result.IsContainer); Assert.AreEqual(contentType.CreateDate, result.CreateDate); Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false)); Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties)); Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false)); var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false)); Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count()); Assert.IsTrue(allPropertyIdsMapped.ContainsAll(allSourcePropertyIds)); Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any())); Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] {ctMain.Id, ctChild1.Id})); Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count()); for (var i = 0; i < contentType.AllowedTemplates.Count(); i++) { Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id); } Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void MemberPropertyTypeBasic_To_MemberPropertyTypeDisplay() { _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>())) .Returns(new DataTypeDefinition("test")); var basic = new MemberPropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", MemberCanViewProperty = true, MemberCanEditProperty = true, IsSensitiveData = true, Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = "xyz" } }; var result = Mapper.Map<MemberPropertyTypeDisplay>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.GroupId, result.GroupId); Assert.AreEqual(basic.Inherited, result.Inherited); Assert.AreEqual(basic.Label, result.Label); Assert.AreEqual(basic.Validation, result.Validation); Assert.AreEqual(basic.MemberCanViewProperty, result.MemberCanViewProperty); Assert.AreEqual(basic.MemberCanEditProperty, result.MemberCanEditProperty); Assert.AreEqual(basic.IsSensitiveData, result.IsSensitiveData); } [Test] public void PropertyTypeBasic_To_PropertyTypeDisplay() { _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>())) .Returns(new DataTypeDefinition("test")); var basic = new PropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = "xyz" } }; var result = Mapper.Map<PropertyTypeDisplay>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.GroupId, result.GroupId); Assert.AreEqual(basic.Inherited, result.Inherited); Assert.AreEqual(basic.Label, result.Label); Assert.AreEqual(basic.Validation, result.Validation); } private MemberTypeSave CreateMemberTypeSave() { return new MemberTypeSave { Alias = "test", AllowAsRoot = true, AllowedContentTypes = new[] { 666, 667 }, Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<MemberPropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new [] { new MemberPropertyTypeBasic { MemberCanEditProperty = true, MemberCanViewProperty = true, IsSensitiveData = true, Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } } } }; } private MediaTypeSave CreateMediaTypeSave() { return new MediaTypeSave { Alias = "test", AllowAsRoot = true, AllowedContentTypes = new[] { 666, 667 }, Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new [] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } } } }; } private DocumentTypeSave CreateContentTypeSave() { return new DocumentTypeSave { Alias = "test", AllowAsRoot = true, AllowedTemplates = new [] { "template1", "template2" }, AllowedContentTypes = new [] {666, 667}, DefaultTemplate = "test", Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new [] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new [] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } } } }; } private MediaTypeSave CreateCompositionMediaTypeSave() { return new MediaTypeSave { Alias = "test", AllowAsRoot = true, AllowedContentTypes = new[] { 666, 667 }, Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new[] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } }, new PropertyGroupBasic<PropertyTypeBasic>() { Id = 894, Name = "Tab 2", SortOrder = 0, Inherited = true, Properties = new[] { new PropertyTypeBasic { Alias = "parentProperty", Description = "this is a property from the parent", Inherited = true, Label = "Parent property", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } } } }; } private DocumentTypeSave CreateCompositionContentTypeSave() { return new DocumentTypeSave { Alias = "test", AllowAsRoot = true, AllowedTemplates = new[] { "template1", "template2" }, AllowedContentTypes = new[] { 666, 667 }, DefaultTemplate = "test", Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new[] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } }, new PropertyGroupBasic<PropertyTypeBasic>() { Id = 894, Name = "Tab 2", SortOrder = 0, Inherited = true, Properties = new[] { new PropertyTypeBasic { Alias = "parentProperty", Description = "this is a property from the parent", Inherited = true, Label = "Parent property", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } } } }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using OpenPriceConfig.Data; using OpenPriceConfig.Models; using Microsoft.AspNetCore.Authorization; using System.Globalization; namespace OpenPriceConfig.Controllers { [Authorize] public class OptionsController : Controller { private readonly ApplicationDbContext _context; public OptionsController(ApplicationDbContext context) { _context = context; } // GET: Options public async Task<IActionResult> Index(int? id/*configuratorID*/) { if (id == null) return NotFound(); var options = from o in _context.Option where o.Configurator.ID == id orderby o.Order select o; var optionsq = options .Include(o => o.BracketPricing) .Include(o => o.DescriptionLocale) .Include(o => o.Configurator); ViewData["Configurator"] = await _context.Configurator.Where(c => c.ID == id).FirstAsync(); //var applicationDbContext = _context.Option.Include(o => o.DescriptionLocale); return View(await optionsq.ToListAsync()); } // GET: Options/Create public async Task<IActionResult> Create(int? id/*configurator id*/) { if(id == null) { return NotFound(); } ViewData["Configurator"] = await _context.Configurator.Where(c => c.ID == id).FirstAsync(); ViewData["ConfiguratorID"] = new SelectList(_context.Configurator, "ID", "Name"); ViewData["DescriptionLocaleID"] = new SelectList(_context.Locale, "ID", "Tag"); PopulateInputTypeDropDownList(null); PopulateBracketPricingTypeDropDownList(null); return View(); } // POST: Options/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(int? id/*Configurator ID*/, [Bind("DescriptionLocaleID,Name,OptionTag,Order,Price,InputType,BracketPricingType")] Option option) { if (ModelState.IsValid) { if (id == null) { return NotFound(); } var configuratorQuery = from c in _context.Configurator where (c.ID == id) select c; var configurator = await configuratorQuery.FirstOrDefaultAsync(); option.Configurator = configurator; option.UpdateBracketPricings(); _context.Add(option); //option.GenerateBracketPricings(configurator.FloorsNumber); await _context.SaveChangesAsync(); return RedirectToAction("Index", new { id = configurator.ID }); } ViewData["DescriptionLocaleID"] = new SelectList(_context.Locale, "ID", "ID", option.DescriptionLocaleID); return View(option); } // GET: Options/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var option = await _context.Option .Include(o => o.Configurator) .SingleOrDefaultAsync(m => m.ID == id); if (option == null) { return NotFound(); } PopulateInputTypeDropDownList(option); PopulateBracketPricingTypeDropDownList(option); ViewData["DescriptionLocaleID"] = new SelectList(_context.Locale, "ID", "Tag", option.DescriptionLocaleID); return View(option); } // POST: Options/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("ID,DescriptionLocaleID,Name,OptionTag,Order,Price,InputType,BracketPricingType")] Option option) { if (id != option.ID) { return NotFound(); } if (ModelState.IsValid) { var configurator = await (from o in _context.Option where o.ID == option.ID select o.Configurator).FirstAsync(); try { _context.Update(option); await _context.SaveChangesAsync(); option = await _context.Option.Include(o => o.Configurator).Include(o => o.BracketPricing).SingleAsync(o => o.ID == id); option.UpdateBracketPricings(); //Need to call again so bracket pricings are updated _context.Update(option); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!OptionExists(option.ID)) { return NotFound(); } else { throw; } } return RedirectToAction("Index", new { id = configurator.ID }); } ViewData["DescriptionLocaleID"] = new SelectList(_context.Locale, "ID", "ID", option.DescriptionLocaleID); return View(option); } // GET: Options/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var option = await _context.Option.Include(o => o.Configurator).SingleOrDefaultAsync(m => m.ID == id); if (option == null) { return NotFound(); } return View(option); } // POST: Options/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var option = await _context.Option.Include(o => o.Configurator).SingleOrDefaultAsync(m => m.ID == id); var configurator = option.Configurator; option.UpdateBracketPricings(); _context.Option.Remove(option); await _context.SaveChangesAsync(); return RedirectToAction("Index", new { id = configurator.ID }); } // GET: BracketPricings/Edit/5 public async Task<IActionResult> EditBracketPricings(int? id/*optionID*/) { if (id == null) { return NotFound(); } var option = await _context.Option .Where(o => o.ID == id) .Include(o => o.Configurator) .FirstAsync(); var bracketPricing = await _context.BracketPricing.Where(b => b.OptionID == id).OrderBy(b => b.Level).ToListAsync(); //Generate a list of bracket pricing if not existing if (bracketPricing == null || bracketPricing.Count == 0) { option.UpdateBracketPricings(); _context.Update(option); await _context.SaveChangesAsync(); } return View(option); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EditBracketPricings(int? id, ICollection<BracketPricing> bracketPricing) { if (id == null) { return NotFound(); } var option = await _context.Option .Where(o => o.ID == id) .Include(o => o.Configurator) .Include(o => o.BracketPricing) .FirstAsync(); var bpFormList = bracketPricing.ToList(); var bpOptionList = option.BracketPricing.OrderBy(bp => bp.Level).ToList(); for (int i = 0; i < option.BracketPricing.Count; i++) { bpOptionList[i].Price = bpFormList[i].Price; _context.Update(bpOptionList[i]); } await _context.SaveChangesAsync(); return RedirectToAction("Index", new { id = option.Configurator.ID }); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ParseBracketPricingString(int? id, string inputText) { if (id == null) { return NotFound(); } char[] validchars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', ',' }; var inputSplit = inputText.Split('\t'); List<decimal> decimals = new List<decimal>(); foreach(var inp in inputSplit) { var chararr = inp.Where(c => validchars.Contains(c)).ToArray(); var str = new string(chararr).Replace(',', '.'); decimal dec; var ok = decimal.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out dec); if (string.IsNullOrEmpty(str) || !ok) continue; decimals.Add(dec); } var option = await _context.Option .Where(o => o.ID == id) .Include(o => o.Configurator) .Include(o => o.BracketPricing) .FirstAsync(); if(option.BracketPricing.Count != decimals.Count) { return BadRequest(); } var orderedBp = option.BracketPricing.OrderBy(o => o.Level).ToArray(); for(int i = 0; i < decimals.Count; i++ ) { orderedBp[i].Price = decimals[i]; _context.Update(orderedBp[i]); } await _context.SaveChangesAsync(); return RedirectToAction("Index", new { id = option.Configurator.ID }); } private bool OptionExists(int id) { return _context.Option.Any(e => e.ID == id); } void PopulateInputTypeDropDownList(Option option) { List<object> inputTypes = new List<object>() { }; var inputTypesNames = Enum.GetNames(typeof(Option.InputTypes)); var inputTypesValues = Enum.GetValues(typeof(Option.InputTypes)); for (int i = 0; i < inputTypesNames.Length; i++) { inputTypes.Add(new { Value = inputTypesValues.GetValue(i), Name = inputTypesNames[i] }); } ViewData["InputTypeID"] = new SelectList(inputTypes, "Value", "Name", option?.InputType); } void PopulateBracketPricingTypeDropDownList(Option option) { List<object> inputTypes = new List<object>() { }; var bracketPricingTypesNames = Enum.GetNames(typeof(Option.BracketPricingTypes)); var bracketPricingTypesValues = Enum.GetValues(typeof(Option.BracketPricingTypes)); for (int i = 0; i < bracketPricingTypesNames.Length; i++) { inputTypes.Add(new { Value = bracketPricingTypesValues.GetValue(i), Name = bracketPricingTypesNames[i] }); } ViewData["BracketPricingTypeID"] = new SelectList(inputTypes, "Value", "Name", option?.InputType); } } }
using System.Collections.Generic; using System.Linq; using Content.Client.Examine; using Content.Client.Verbs; using Content.Client.Viewport; using Content.Shared.CCVar; using Content.Shared.Input; using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Client.Input; using Robust.Client.Player; using Robust.Client.State; using Robust.Client.UserInterface; using Robust.Shared.Configuration; using Robust.Shared.GameObjects; using Robust.Shared.Input; using Robust.Shared.Input.Binding; using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Maths; using Robust.Shared.Timing; namespace Content.Client.ContextMenu.UI { /// <summary> /// This class handles the displaying of the entity context menu. /// </summary> /// <remarks> /// In addition to the normal <see cref="ContextMenuPresenter"/> functionality, this also provides functions get /// a list of entities near the mouse position, add them to the context menu grouped by prototypes, and remove /// them from the menu as they move out of sight. /// </remarks> public sealed partial class EntityMenuPresenter : ContextMenuPresenter { [Dependency] private readonly IEntitySystemManager _systemManager = default!; [Dependency] private readonly IEntityManager _entityManager = default!; [Dependency] private readonly IPlayerManager _playerManager = default!; [Dependency] private readonly IStateManager _stateManager = default!; [Dependency] private readonly IInputManager _inputManager = default!; [Dependency] private readonly IConfigurationManager _cfg = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; [Dependency] private readonly IUserInterfaceManager _userInterfaceManager = default!; [Dependency] private readonly IEyeManager _eyeManager = default!; private readonly VerbSystem _verbSystem; private readonly ExamineSystem _examineSystem; /// <summary> /// This maps the currently displayed entities to the actual GUI elements. /// </summary> /// <remarks> /// This is used remove GUI elements when the entities are deleted. or leave the LOS. /// </remarks> public Dictionary<EntityUid, EntityMenuElement> Elements = new(); public EntityMenuPresenter(VerbSystem verbSystem) : base() { IoCManager.InjectDependencies(this); _verbSystem = verbSystem; _examineSystem = EntitySystem.Get<ExamineSystem>(); _cfg.OnValueChanged(CCVars.EntityMenuGroupingType, OnGroupingChanged, true); CommandBinds.Builder .Bind(ContentKeyFunctions.OpenContextMenu, new PointerInputCmdHandler(HandleOpenEntityMenu, outsidePrediction: true)) .Register<EntityMenuPresenter>(); } public override void Dispose() { base.Dispose(); Elements.Clear(); CommandBinds.Unregister<EntityMenuPresenter>(); } /// <summary> /// Given a list of entities, sort them into groups and them to a new entity menu. /// </summary> public void OpenRootMenu(List<EntityUid> entities) { // close any old menus first. if (RootMenu.Visible) Close(); var entitySpriteStates = GroupEntities(entities); var orderedStates = entitySpriteStates.ToList(); orderedStates.Sort((x, y) => string.CompareOrdinal(_entityManager.GetComponent<MetaDataComponent>(x.First()).EntityPrototype?.Name, _entityManager.GetComponent<MetaDataComponent>(y.First()).EntityPrototype?.Name)); Elements.Clear(); AddToUI(orderedStates); var box = UIBox2.FromDimensions(_userInterfaceManager.MousePositionScaled.Position, (1, 1)); RootMenu.Open(box); } public override void OnKeyBindDown(ContextMenuElement element, GUIBoundKeyEventArgs args) { base.OnKeyBindDown(element, args); if (element is not EntityMenuElement entityElement) return; // get an entity associated with this element var entity = entityElement.Entity; entity ??= GetFirstEntityOrNull(element.SubMenu); // Deleted() automatically checks for null & existence. if (_entityManager.Deleted(entity)) return; // open verb menu? if (args.Function == ContentKeyFunctions.OpenContextMenu) { _verbSystem.VerbMenu.OpenVerbMenu(entity.Value); args.Handle(); return; } // do examination? if (args.Function == ContentKeyFunctions.ExamineEntity) { _systemManager.GetEntitySystem<ExamineSystem>().DoExamine(entity.Value); args.Handle(); return; } // do some other server-side interaction? if (args.Function == EngineKeyFunctions.Use || args.Function == ContentKeyFunctions.ActivateItemInWorld || args.Function == ContentKeyFunctions.AltActivateItemInWorld || args.Function == ContentKeyFunctions.Point || args.Function == ContentKeyFunctions.TryPullObject || args.Function == ContentKeyFunctions.MovePulledObject) { var inputSys = _systemManager.GetEntitySystem<InputSystem>(); var func = args.Function; var funcId = _inputManager.NetworkBindMap.KeyFunctionID(func); var message = new FullInputCmdMessage(_gameTiming.CurTick, _gameTiming.TickFraction, funcId, BoundKeyState.Down, _entityManager.GetComponent<TransformComponent>(entity.Value).Coordinates, args.PointerLocation, entity.Value); var session = _playerManager.LocalPlayer?.Session; if (session != null) { inputSys.HandleInputCommand(session, func, message); } _verbSystem.CloseAllMenus(); args.Handle(); return; } } private bool HandleOpenEntityMenu(in PointerInputCmdHandler.PointerInputCmdArgs args) { if (args.State != BoundKeyState.Down) return false; if (_stateManager.CurrentState is not GameScreenBase) return false; var coords = args.Coordinates.ToMap(_entityManager); if (_verbSystem.TryGetEntityMenuEntities(coords, out var entities)) OpenRootMenu(entities); return true; } /// <summary> /// Check that entities in the context menu are still visible. If not, remove them from the context menu. /// </summary> public void Update() { if (!RootMenu.Visible) return; if (_playerManager.LocalPlayer?.ControlledEntity is not { } player || !player.IsValid()) return; // Do we need to do in-range unOccluded checks? var ignoreFov = !_eyeManager.CurrentEye.DrawFov || (_verbSystem.Visibility & MenuVisibility.NoFov) == MenuVisibility.NoFov; foreach (var entity in Elements.Keys.ToList()) { if (_entityManager.Deleted(entity) || !ignoreFov && !_examineSystem.CanExamine(player, entity)) RemoveEntity(entity); } } /// <summary> /// Add menu elements for a list of grouped entities; /// </summary> /// <param name="entityGroups"> A list of entity groups. Entities are grouped together based on prototype.</param> private void AddToUI(List<List<EntityUid>> entityGroups) { // If there is only a single group. We will just directly list individual entities if (entityGroups.Count == 1) { foreach (var entity in entityGroups[0]) { var element = new EntityMenuElement(entity); AddElement(RootMenu, element); Elements.TryAdd(entity, element); } return; } foreach (var group in entityGroups) { if (group.Count > 1) { AddGroupToUI(group); continue; } // this group only has a single entity, add a simple menu element var element = new EntityMenuElement(group[0]); AddElement(RootMenu, element); Elements.TryAdd(group[0], element); } } /// <summary> /// Given a group of entities, add a menu element that has a pop-up sub-menu listing group members /// </summary> private void AddGroupToUI(List<EntityUid> group) { EntityMenuElement element = new(); ContextMenuPopup subMenu = new(this, element); foreach (var entity in group) { var subElement = new EntityMenuElement(entity); AddElement(subMenu, subElement); Elements.TryAdd(entity, subElement); } UpdateElement(element); AddElement(RootMenu, element); } /// <summary> /// Remove an entity from the entity context menu. /// </summary> private void RemoveEntity(EntityUid entity) { // find the element associated with this entity if (!Elements.TryGetValue(entity, out var element)) { Logger.Error($"Attempted to remove unknown entity from the entity menu: {_entityManager.GetComponent<MetaDataComponent>(entity).EntityName} ({entity})"); return; } // remove the element var parent = element.ParentMenu?.ParentElement; element.Dispose(); Elements.Remove(entity); // update any parent elements if (parent is EntityMenuElement e) UpdateElement(e); // if the verb menu is open and targeting this entity, close it. if (_verbSystem.VerbMenu.CurrentTarget == entity) _verbSystem.VerbMenu.Close(); // If this was the last entity, close the entity menu if (RootMenu.MenuBody.ChildCount == 0) Close(); } /// <summary> /// Update the information displayed by a menu element. /// </summary> /// <remarks> /// This is called when initializing elements or after an element was removed from a sub-menu. /// </remarks> private void UpdateElement(EntityMenuElement element) { if (element.SubMenu == null) return; // Get the first entity in the sub-menus var entity = GetFirstEntityOrNull(element.SubMenu); if (entity == null) { // This whole element has no associated entities. We should remove it element.Dispose(); return; } element.UpdateEntity(entity); // Update the entity count & count label element.Count = 0; foreach (var subElement in element.SubMenu.MenuBody.Children) { if (subElement is EntityMenuElement entityElement) element.Count += entityElement.Count; } element.CountLabel.Text = element.Count.ToString(); if (element.Count == 1) { // There was only one entity in the sub-menu. So we will just remove the sub-menu and point directly to // that entity. element.Entity = entity; element.SubMenu.Dispose(); element.SubMenu = null; element.CountLabel.Visible = false; Elements[entity.Value] = element; } // update the parent element, so that it's count and entity icon gets updated. var parent = element.ParentMenu?.ParentElement; if (parent is EntityMenuElement e) UpdateElement(e); } /// <summary> /// Recursively look through a sub-menu and return the first entity. /// </summary> private EntityUid? GetFirstEntityOrNull(ContextMenuPopup? menu) { if (menu == null) return null; foreach (var element in menu.MenuBody.Children) { if (element is not EntityMenuElement entityElement) continue; if (entityElement.Entity != null) { if (!_entityManager.Deleted(entityElement.Entity)) return entityElement.Entity; continue; } // if the element has no entity, its a group of entities with another attached sub-menu. var entity = GetFirstEntityOrNull(entityElement.SubMenu); if (entity != null) return entity; } return null; } public override void OpenSubMenu(ContextMenuElement element) { base.OpenSubMenu(element); // In case the verb menu is currently open, ensure that it is shown ABOVE the entity menu. if (_verbSystem.VerbMenu.Menus.TryPeek(out var menu) && menu.Visible) { menu.ParentElement?.ParentMenu?.SetPositionLast(); menu.SetPositionLast(); } } } }
using UnityEngine; using System.Collections.Generic; namespace DCM.Old { [System.Obsolete("This Class is obsolete")] public class TextureCombineUtility { //For this class we use a struce that holds the texture and a rect for the new UV positions in the texture atlas public struct TexturePosition { public Texture2D[] textures; public Rect position; } /** * This function returns two variables: -> The tecture atlas -> An array of the old textures and their new positions. (Used for UV modification) */ public static Material combine(Material[] combines, out TexturePosition[] texturePositions, TextureAtlasInfo atlasInfo) { if (atlasInfo == null) { Debug.LogError("atlasInfo is null. Try removing and reattaching combine children component"); texturePositions = null; return null; } if (atlasInfo.shaderPropertiesToLookFor.Length <= 0) { Debug.LogError("You need to enter some shader properties to look for into Atlas Info. Cannot combine with 0 properties"); texturePositions = null; return null; } List<ShaderProperties> properties = new List<ShaderProperties>(); for (int i = 0; i < atlasInfo.shaderPropertiesToLookFor.Length; i++) { if (combines [0].HasProperty(atlasInfo.shaderPropertiesToLookFor [i].propertyName)) { properties.Add(atlasInfo.shaderPropertiesToLookFor [i]); } } texturePositions = new TexturePosition[combines.Length]; for (int i = 0; i < combines.Length; i++) { TexturePosition tempTexturePosition = new TexturePosition(); tempTexturePosition.textures = new Texture2D[properties.Count]; for (int j = 0; j < properties.Count; j++) { //Debug.Log((combines[i].GetTexture(properties[j].propertyName) == null) + ", " + properties[j].propertyName + ", " + combines[i].name); if (combines [i].GetTexture(properties [j].propertyName) == null) { Debug.LogError("Cannot combine textures when using Unity's default material texture"); texturePositions = null; return null; } tempTexturePosition.textures [j] = Object.Instantiate(combines [i].GetTexture(properties [j].propertyName)) as Texture2D; tempTexturePosition.textures [j].name = tempTexturePosition.textures [j].name.Remove(tempTexturePosition.textures [j].name.IndexOf("(Clone)", System.StringComparison.Ordinal)); } texturePositions [i] = tempTexturePosition; } textureQuickSort(texturePositions, 0, texturePositions.Length - 1); for (int i = 0; i < texturePositions.Length; i++) { for (int j = 1; j < texturePositions[i].textures.Length; j++) { texturePositions [i].textures [j] = scaleTexture(texturePositions [i].textures [j], texturePositions [i].textures [0].width, texturePositions [i].textures [0].height); } } texturePositions [0].position.x = texturePositions [0].position.y = 0; texturePositions [0].position.width = texturePositions [0].textures [0].width; texturePositions [0].position.height = texturePositions [0].textures [0].height; int height = texturePositions [0].textures [0].height; int width = texturePositions [0].textures [0].width; int widthIndex = width; int heightIndex = 0; bool useHeightAsReference = true; for (int i = 1; i < texturePositions.Length; i++) { texturePositions [i].position.x = widthIndex; texturePositions [i].position.y = heightIndex; texturePositions [i].position.width = texturePositions [i].textures [0].width; texturePositions [i].position.height = texturePositions [i].textures [0].height; if (useHeightAsReference) { if (widthIndex + texturePositions [i].textures [0].width > width) { width = widthIndex + texturePositions [i].textures [0].width; } heightIndex += texturePositions [i].textures [0].height; if (heightIndex >= height) { useHeightAsReference = false; height = heightIndex; heightIndex = height; widthIndex = 0; } } else { if (heightIndex + texturePositions [i].textures [0].height > height) { height = heightIndex + texturePositions [i].textures [0].height; } widthIndex += texturePositions [i].textures [0].width; if (widthIndex >= width) { useHeightAsReference = true; width = widthIndex; widthIndex = width; heightIndex = 0; } } } if (height > width) { width = height; } else { height = width; } float textureSizeFactor = 1.0f / height; Material newMaterial = new Material(combines [0]); for (int i = 0; i < properties.Count; i++) { Texture2D combinesTextures = new Texture2D(width, height, (atlasInfo.ignoreAlpha && !properties [i].markAsNormal) ? TextureFormat.RGB24 : TextureFormat.ARGB32, true); combinesTextures.anisoLevel = atlasInfo.anisoLevel; combinesTextures.filterMode = atlasInfo.filterMode; combinesTextures.wrapMode = atlasInfo.wrapMode; for (int j = 0; j < texturePositions.Length; j++) { combinesTextures.SetPixels((int)texturePositions [j].position.x, (int)texturePositions [j].position.y, texturePositions [j].textures [i].width, texturePositions [j].textures [i].height, texturePositions [j].textures [i].GetPixels()); } combinesTextures.Apply(); if (atlasInfo.compressTexturesInMemory) { combinesTextures.Compress(true); } newMaterial.SetTexture(properties [i].propertyName, combinesTextures); } for (int i = 0; i < texturePositions.Length; i++) { texturePositions [i].position.x = texturePositions [i].position.x * textureSizeFactor; texturePositions [i].position.y = texturePositions [i].position.y * textureSizeFactor; texturePositions [i].position.width = texturePositions [i].position.width * textureSizeFactor; texturePositions [i].position.height = texturePositions [i].position.height * textureSizeFactor; } return newMaterial; } static void textureQuickSort(TexturePosition[] textures, int low, int high) { if (low < high) { int pivot = partition(textures, low, high); textureQuickSort(textures, low, pivot - 1); textureQuickSort(textures, pivot + 1, high); } } static int partition(TexturePosition[] texturePositions, int low, int high) { TexturePosition pivot_item; int pivotPosition = low; pivot_item = texturePositions [pivotPosition]; for (int i = low + 1; i <= high; i++) { if (texturePositions [i].textures [0].height > pivot_item.textures [0].height) { pivotPosition++; swap(texturePositions, pivotPosition, i); } } swap(texturePositions, low, pivotPosition); return pivotPosition; } static void swap(TexturePosition[] textures, int i, int j) { TexturePosition temp = textures [i]; textures [i] = textures [j]; textures [j] = temp; } static Texture2D scaleTexture(Texture2D oldTexture, int width, int height) { Color[] oldTextureColors = oldTexture.GetPixels(); Color[] newTextureColors = new Color[width * height]; float ratioX = 1.0f / ((float)width / (oldTexture.width - 1)); float ratioY = 1.0f / ((float)height / (oldTexture.height - 1)); int oldWidth = oldTexture.width; int newWidth = width; for (int y = 0; y < height; y++) { int yFloor = Mathf.FloorToInt(y * ratioY); int y1 = yFloor * oldWidth; int y2 = (yFloor + 1) * oldWidth; int yWidth = y * newWidth; for (int x = 0; x < newWidth; x++) { int xFloor = Mathf.FloorToInt(x * ratioX); float xLerp = x * ratioX - xFloor; newTextureColors [yWidth + x] = colorLerpUnclamped(colorLerpUnclamped(oldTextureColors [y1 + xFloor], oldTextureColors [y1 + xFloor + 1], xLerp), colorLerpUnclamped(oldTextureColors [y2 + xFloor], oldTextureColors [y2 + xFloor + 1], xLerp), y * ratioY - yFloor); } } Texture2D newTexture = new Texture2D(width, height, oldTexture.format, false); newTexture.SetPixels(newTextureColors); newTexture.Apply(); return newTexture; } static Color colorLerpUnclamped(Color color1, Color color2, float v) { return new Color(color1.r + (color2.r - color1.r) * v, color1.g + (color2.g - color1.g) * v, color1.b + (color2.b - color1.b) * v, color1.a + (color2.a - color1.a) * v); } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: Brushes.cs // // Description: A static class which contains well-known SolidColorBrushes. // // History: // 04/29/2003 : [....] - Created it // //--------------------------------------------------------------------------- using System.Windows.Media; using MS.Internal; using System; namespace System.Windows.Media { /// <summary> /// Brushes - A collection of well-known SolidColorBrushes /// </summary> public sealed class Brushes { #region Constructors /// <summary> /// Private constructor - prevents instantiation. /// </summary> private Brushes() {} #endregion Constructors #region static Known SolidColorBrushes /// <summary> /// Well-known SolidColorBrush: AliceBlue /// </summary> public static SolidColorBrush AliceBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.AliceBlue); } } /// <summary> /// Well-known SolidColorBrush: AntiqueWhite /// </summary> public static SolidColorBrush AntiqueWhite { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.AntiqueWhite); } } /// <summary> /// Well-known SolidColorBrush: Aqua /// </summary> public static SolidColorBrush Aqua { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Aqua); } } /// <summary> /// Well-known SolidColorBrush: Aquamarine /// </summary> public static SolidColorBrush Aquamarine { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Aquamarine); } } /// <summary> /// Well-known SolidColorBrush: Azure /// </summary> public static SolidColorBrush Azure { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Azure); } } /// <summary> /// Well-known SolidColorBrush: Beige /// </summary> public static SolidColorBrush Beige { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Beige); } } /// <summary> /// Well-known SolidColorBrush: Bisque /// </summary> public static SolidColorBrush Bisque { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Bisque); } } /// <summary> /// Well-known SolidColorBrush: Black /// </summary> public static SolidColorBrush Black { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Black); } } /// <summary> /// Well-known SolidColorBrush: BlanchedAlmond /// </summary> public static SolidColorBrush BlanchedAlmond { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.BlanchedAlmond); } } /// <summary> /// Well-known SolidColorBrush: Blue /// </summary> public static SolidColorBrush Blue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Blue); } } /// <summary> /// Well-known SolidColorBrush: BlueViolet /// </summary> public static SolidColorBrush BlueViolet { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.BlueViolet); } } /// <summary> /// Well-known SolidColorBrush: Brown /// </summary> public static SolidColorBrush Brown { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Brown); } } /// <summary> /// Well-known SolidColorBrush: BurlyWood /// </summary> public static SolidColorBrush BurlyWood { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.BurlyWood); } } /// <summary> /// Well-known SolidColorBrush: CadetBlue /// </summary> public static SolidColorBrush CadetBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.CadetBlue); } } /// <summary> /// Well-known SolidColorBrush: Chartreuse /// </summary> public static SolidColorBrush Chartreuse { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Chartreuse); } } /// <summary> /// Well-known SolidColorBrush: Chocolate /// </summary> public static SolidColorBrush Chocolate { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Chocolate); } } /// <summary> /// Well-known SolidColorBrush: Coral /// </summary> public static SolidColorBrush Coral { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Coral); } } /// <summary> /// Well-known SolidColorBrush: CornflowerBlue /// </summary> public static SolidColorBrush CornflowerBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.CornflowerBlue); } } /// <summary> /// Well-known SolidColorBrush: Cornsilk /// </summary> public static SolidColorBrush Cornsilk { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Cornsilk); } } /// <summary> /// Well-known SolidColorBrush: Crimson /// </summary> public static SolidColorBrush Crimson { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Crimson); } } /// <summary> /// Well-known SolidColorBrush: Cyan /// </summary> public static SolidColorBrush Cyan { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Cyan); } } /// <summary> /// Well-known SolidColorBrush: DarkBlue /// </summary> public static SolidColorBrush DarkBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkBlue); } } /// <summary> /// Well-known SolidColorBrush: DarkCyan /// </summary> public static SolidColorBrush DarkCyan { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkCyan); } } /// <summary> /// Well-known SolidColorBrush: DarkGoldenrod /// </summary> public static SolidColorBrush DarkGoldenrod { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkGoldenrod); } } /// <summary> /// Well-known SolidColorBrush: DarkGray /// </summary> public static SolidColorBrush DarkGray { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkGray); } } /// <summary> /// Well-known SolidColorBrush: DarkGreen /// </summary> public static SolidColorBrush DarkGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkGreen); } } /// <summary> /// Well-known SolidColorBrush: DarkKhaki /// </summary> public static SolidColorBrush DarkKhaki { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkKhaki); } } /// <summary> /// Well-known SolidColorBrush: DarkMagenta /// </summary> public static SolidColorBrush DarkMagenta { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkMagenta); } } /// <summary> /// Well-known SolidColorBrush: DarkOliveGreen /// </summary> public static SolidColorBrush DarkOliveGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkOliveGreen); } } /// <summary> /// Well-known SolidColorBrush: DarkOrange /// </summary> public static SolidColorBrush DarkOrange { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkOrange); } } /// <summary> /// Well-known SolidColorBrush: DarkOrchid /// </summary> public static SolidColorBrush DarkOrchid { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkOrchid); } } /// <summary> /// Well-known SolidColorBrush: DarkRed /// </summary> public static SolidColorBrush DarkRed { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkRed); } } /// <summary> /// Well-known SolidColorBrush: DarkSalmon /// </summary> public static SolidColorBrush DarkSalmon { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkSalmon); } } /// <summary> /// Well-known SolidColorBrush: DarkSeaGreen /// </summary> public static SolidColorBrush DarkSeaGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkSeaGreen); } } /// <summary> /// Well-known SolidColorBrush: DarkSlateBlue /// </summary> public static SolidColorBrush DarkSlateBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkSlateBlue); } } /// <summary> /// Well-known SolidColorBrush: DarkSlateGray /// </summary> public static SolidColorBrush DarkSlateGray { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkSlateGray); } } /// <summary> /// Well-known SolidColorBrush: DarkTurquoise /// </summary> public static SolidColorBrush DarkTurquoise { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkTurquoise); } } /// <summary> /// Well-known SolidColorBrush: DarkViolet /// </summary> public static SolidColorBrush DarkViolet { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DarkViolet); } } /// <summary> /// Well-known SolidColorBrush: DeepPink /// </summary> public static SolidColorBrush DeepPink { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DeepPink); } } /// <summary> /// Well-known SolidColorBrush: DeepSkyBlue /// </summary> public static SolidColorBrush DeepSkyBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DeepSkyBlue); } } /// <summary> /// Well-known SolidColorBrush: DimGray /// </summary> public static SolidColorBrush DimGray { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DimGray); } } /// <summary> /// Well-known SolidColorBrush: DodgerBlue /// </summary> public static SolidColorBrush DodgerBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.DodgerBlue); } } /// <summary> /// Well-known SolidColorBrush: Firebrick /// </summary> public static SolidColorBrush Firebrick { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Firebrick); } } /// <summary> /// Well-known SolidColorBrush: FloralWhite /// </summary> public static SolidColorBrush FloralWhite { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.FloralWhite); } } /// <summary> /// Well-known SolidColorBrush: ForestGreen /// </summary> public static SolidColorBrush ForestGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.ForestGreen); } } /// <summary> /// Well-known SolidColorBrush: Fuchsia /// </summary> public static SolidColorBrush Fuchsia { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Fuchsia); } } /// <summary> /// Well-known SolidColorBrush: Gainsboro /// </summary> public static SolidColorBrush Gainsboro { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Gainsboro); } } /// <summary> /// Well-known SolidColorBrush: GhostWhite /// </summary> public static SolidColorBrush GhostWhite { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.GhostWhite); } } /// <summary> /// Well-known SolidColorBrush: Gold /// </summary> public static SolidColorBrush Gold { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Gold); } } /// <summary> /// Well-known SolidColorBrush: Goldenrod /// </summary> public static SolidColorBrush Goldenrod { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Goldenrod); } } /// <summary> /// Well-known SolidColorBrush: Gray /// </summary> public static SolidColorBrush Gray { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Gray); } } /// <summary> /// Well-known SolidColorBrush: Green /// </summary> public static SolidColorBrush Green { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Green); } } /// <summary> /// Well-known SolidColorBrush: GreenYellow /// </summary> public static SolidColorBrush GreenYellow { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.GreenYellow); } } /// <summary> /// Well-known SolidColorBrush: Honeydew /// </summary> public static SolidColorBrush Honeydew { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Honeydew); } } /// <summary> /// Well-known SolidColorBrush: HotPink /// </summary> public static SolidColorBrush HotPink { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.HotPink); } } /// <summary> /// Well-known SolidColorBrush: IndianRed /// </summary> public static SolidColorBrush IndianRed { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.IndianRed); } } /// <summary> /// Well-known SolidColorBrush: Indigo /// </summary> public static SolidColorBrush Indigo { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Indigo); } } /// <summary> /// Well-known SolidColorBrush: Ivory /// </summary> public static SolidColorBrush Ivory { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Ivory); } } /// <summary> /// Well-known SolidColorBrush: Khaki /// </summary> public static SolidColorBrush Khaki { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Khaki); } } /// <summary> /// Well-known SolidColorBrush: Lavender /// </summary> public static SolidColorBrush Lavender { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Lavender); } } /// <summary> /// Well-known SolidColorBrush: LavenderBlush /// </summary> public static SolidColorBrush LavenderBlush { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LavenderBlush); } } /// <summary> /// Well-known SolidColorBrush: LawnGreen /// </summary> public static SolidColorBrush LawnGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LawnGreen); } } /// <summary> /// Well-known SolidColorBrush: LemonChiffon /// </summary> public static SolidColorBrush LemonChiffon { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LemonChiffon); } } /// <summary> /// Well-known SolidColorBrush: LightBlue /// </summary> public static SolidColorBrush LightBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightBlue); } } /// <summary> /// Well-known SolidColorBrush: LightCoral /// </summary> public static SolidColorBrush LightCoral { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightCoral); } } /// <summary> /// Well-known SolidColorBrush: LightCyan /// </summary> public static SolidColorBrush LightCyan { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightCyan); } } /// <summary> /// Well-known SolidColorBrush: LightGoldenrodYellow /// </summary> public static SolidColorBrush LightGoldenrodYellow { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightGoldenrodYellow); } } /// <summary> /// Well-known SolidColorBrush: LightGray /// </summary> public static SolidColorBrush LightGray { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightGray); } } /// <summary> /// Well-known SolidColorBrush: LightGreen /// </summary> public static SolidColorBrush LightGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightGreen); } } /// <summary> /// Well-known SolidColorBrush: LightPink /// </summary> public static SolidColorBrush LightPink { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightPink); } } /// <summary> /// Well-known SolidColorBrush: LightSalmon /// </summary> public static SolidColorBrush LightSalmon { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightSalmon); } } /// <summary> /// Well-known SolidColorBrush: LightSeaGreen /// </summary> public static SolidColorBrush LightSeaGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightSeaGreen); } } /// <summary> /// Well-known SolidColorBrush: LightSkyBlue /// </summary> public static SolidColorBrush LightSkyBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightSkyBlue); } } /// <summary> /// Well-known SolidColorBrush: LightSlateGray /// </summary> public static SolidColorBrush LightSlateGray { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightSlateGray); } } /// <summary> /// Well-known SolidColorBrush: LightSteelBlue /// </summary> public static SolidColorBrush LightSteelBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightSteelBlue); } } /// <summary> /// Well-known SolidColorBrush: LightYellow /// </summary> public static SolidColorBrush LightYellow { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LightYellow); } } /// <summary> /// Well-known SolidColorBrush: Lime /// </summary> public static SolidColorBrush Lime { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Lime); } } /// <summary> /// Well-known SolidColorBrush: LimeGreen /// </summary> public static SolidColorBrush LimeGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.LimeGreen); } } /// <summary> /// Well-known SolidColorBrush: Linen /// </summary> public static SolidColorBrush Linen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Linen); } } /// <summary> /// Well-known SolidColorBrush: Magenta /// </summary> public static SolidColorBrush Magenta { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Magenta); } } /// <summary> /// Well-known SolidColorBrush: Maroon /// </summary> public static SolidColorBrush Maroon { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Maroon); } } /// <summary> /// Well-known SolidColorBrush: MediumAquamarine /// </summary> public static SolidColorBrush MediumAquamarine { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MediumAquamarine); } } /// <summary> /// Well-known SolidColorBrush: MediumBlue /// </summary> public static SolidColorBrush MediumBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MediumBlue); } } /// <summary> /// Well-known SolidColorBrush: MediumOrchid /// </summary> public static SolidColorBrush MediumOrchid { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MediumOrchid); } } /// <summary> /// Well-known SolidColorBrush: MediumPurple /// </summary> public static SolidColorBrush MediumPurple { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MediumPurple); } } /// <summary> /// Well-known SolidColorBrush: MediumSeaGreen /// </summary> public static SolidColorBrush MediumSeaGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MediumSeaGreen); } } /// <summary> /// Well-known SolidColorBrush: MediumSlateBlue /// </summary> public static SolidColorBrush MediumSlateBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MediumSlateBlue); } } /// <summary> /// Well-known SolidColorBrush: MediumSpringGreen /// </summary> public static SolidColorBrush MediumSpringGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MediumSpringGreen); } } /// <summary> /// Well-known SolidColorBrush: MediumTurquoise /// </summary> public static SolidColorBrush MediumTurquoise { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MediumTurquoise); } } /// <summary> /// Well-known SolidColorBrush: MediumVioletRed /// </summary> public static SolidColorBrush MediumVioletRed { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MediumVioletRed); } } /// <summary> /// Well-known SolidColorBrush: MidnightBlue /// </summary> public static SolidColorBrush MidnightBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MidnightBlue); } } /// <summary> /// Well-known SolidColorBrush: MintCream /// </summary> public static SolidColorBrush MintCream { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MintCream); } } /// <summary> /// Well-known SolidColorBrush: MistyRose /// </summary> public static SolidColorBrush MistyRose { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.MistyRose); } } /// <summary> /// Well-known SolidColorBrush: Moccasin /// </summary> public static SolidColorBrush Moccasin { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Moccasin); } } /// <summary> /// Well-known SolidColorBrush: NavajoWhite /// </summary> public static SolidColorBrush NavajoWhite { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.NavajoWhite); } } /// <summary> /// Well-known SolidColorBrush: Navy /// </summary> public static SolidColorBrush Navy { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Navy); } } /// <summary> /// Well-known SolidColorBrush: OldLace /// </summary> public static SolidColorBrush OldLace { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.OldLace); } } /// <summary> /// Well-known SolidColorBrush: Olive /// </summary> public static SolidColorBrush Olive { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Olive); } } /// <summary> /// Well-known SolidColorBrush: OliveDrab /// </summary> public static SolidColorBrush OliveDrab { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.OliveDrab); } } /// <summary> /// Well-known SolidColorBrush: Orange /// </summary> public static SolidColorBrush Orange { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Orange); } } /// <summary> /// Well-known SolidColorBrush: OrangeRed /// </summary> public static SolidColorBrush OrangeRed { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.OrangeRed); } } /// <summary> /// Well-known SolidColorBrush: Orchid /// </summary> public static SolidColorBrush Orchid { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Orchid); } } /// <summary> /// Well-known SolidColorBrush: PaleGoldenrod /// </summary> public static SolidColorBrush PaleGoldenrod { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.PaleGoldenrod); } } /// <summary> /// Well-known SolidColorBrush: PaleGreen /// </summary> public static SolidColorBrush PaleGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.PaleGreen); } } /// <summary> /// Well-known SolidColorBrush: PaleTurquoise /// </summary> public static SolidColorBrush PaleTurquoise { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.PaleTurquoise); } } /// <summary> /// Well-known SolidColorBrush: PaleVioletRed /// </summary> public static SolidColorBrush PaleVioletRed { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.PaleVioletRed); } } /// <summary> /// Well-known SolidColorBrush: PapayaWhip /// </summary> public static SolidColorBrush PapayaWhip { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.PapayaWhip); } } /// <summary> /// Well-known SolidColorBrush: PeachPuff /// </summary> public static SolidColorBrush PeachPuff { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.PeachPuff); } } /// <summary> /// Well-known SolidColorBrush: Peru /// </summary> public static SolidColorBrush Peru { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Peru); } } /// <summary> /// Well-known SolidColorBrush: Pink /// </summary> public static SolidColorBrush Pink { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Pink); } } /// <summary> /// Well-known SolidColorBrush: Plum /// </summary> public static SolidColorBrush Plum { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Plum); } } /// <summary> /// Well-known SolidColorBrush: PowderBlue /// </summary> public static SolidColorBrush PowderBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.PowderBlue); } } /// <summary> /// Well-known SolidColorBrush: Purple /// </summary> public static SolidColorBrush Purple { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Purple); } } /// <summary> /// Well-known SolidColorBrush: Red /// </summary> public static SolidColorBrush Red { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Red); } } /// <summary> /// Well-known SolidColorBrush: RosyBrown /// </summary> public static SolidColorBrush RosyBrown { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.RosyBrown); } } /// <summary> /// Well-known SolidColorBrush: RoyalBlue /// </summary> public static SolidColorBrush RoyalBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.RoyalBlue); } } /// <summary> /// Well-known SolidColorBrush: SaddleBrown /// </summary> public static SolidColorBrush SaddleBrown { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.SaddleBrown); } } /// <summary> /// Well-known SolidColorBrush: Salmon /// </summary> public static SolidColorBrush Salmon { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Salmon); } } /// <summary> /// Well-known SolidColorBrush: SandyBrown /// </summary> public static SolidColorBrush SandyBrown { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.SandyBrown); } } /// <summary> /// Well-known SolidColorBrush: SeaGreen /// </summary> public static SolidColorBrush SeaGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.SeaGreen); } } /// <summary> /// Well-known SolidColorBrush: SeaShell /// </summary> public static SolidColorBrush SeaShell { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.SeaShell); } } /// <summary> /// Well-known SolidColorBrush: Sienna /// </summary> public static SolidColorBrush Sienna { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Sienna); } } /// <summary> /// Well-known SolidColorBrush: Silver /// </summary> public static SolidColorBrush Silver { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Silver); } } /// <summary> /// Well-known SolidColorBrush: SkyBlue /// </summary> public static SolidColorBrush SkyBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.SkyBlue); } } /// <summary> /// Well-known SolidColorBrush: SlateBlue /// </summary> public static SolidColorBrush SlateBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.SlateBlue); } } /// <summary> /// Well-known SolidColorBrush: SlateGray /// </summary> public static SolidColorBrush SlateGray { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.SlateGray); } } /// <summary> /// Well-known SolidColorBrush: Snow /// </summary> public static SolidColorBrush Snow { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Snow); } } /// <summary> /// Well-known SolidColorBrush: SpringGreen /// </summary> public static SolidColorBrush SpringGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.SpringGreen); } } /// <summary> /// Well-known SolidColorBrush: SteelBlue /// </summary> public static SolidColorBrush SteelBlue { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.SteelBlue); } } /// <summary> /// Well-known SolidColorBrush: Tan /// </summary> public static SolidColorBrush Tan { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Tan); } } /// <summary> /// Well-known SolidColorBrush: Teal /// </summary> public static SolidColorBrush Teal { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Teal); } } /// <summary> /// Well-known SolidColorBrush: Thistle /// </summary> public static SolidColorBrush Thistle { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Thistle); } } /// <summary> /// Well-known SolidColorBrush: Tomato /// </summary> public static SolidColorBrush Tomato { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Tomato); } } /// <summary> /// Well-known SolidColorBrush: Transparent /// </summary> public static SolidColorBrush Transparent { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Transparent); } } /// <summary> /// Well-known SolidColorBrush: Turquoise /// </summary> public static SolidColorBrush Turquoise { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Turquoise); } } /// <summary> /// Well-known SolidColorBrush: Violet /// </summary> public static SolidColorBrush Violet { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Violet); } } /// <summary> /// Well-known SolidColorBrush: Wheat /// </summary> public static SolidColorBrush Wheat { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Wheat); } } /// <summary> /// Well-known SolidColorBrush: White /// </summary> public static SolidColorBrush White { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.White); } } /// <summary> /// Well-known SolidColorBrush: WhiteSmoke /// </summary> public static SolidColorBrush WhiteSmoke { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.WhiteSmoke); } } /// <summary> /// Well-known SolidColorBrush: Yellow /// </summary> public static SolidColorBrush Yellow { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.Yellow); } } /// <summary> /// Well-known SolidColorBrush: YellowGreen /// </summary> public static SolidColorBrush YellowGreen { get { return KnownColors.SolidColorBrushFromUint((uint)KnownColor.YellowGreen); } } #endregion static Known SolidColorBrushes } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.IO.IsolatedStorage { public static class __IsolatedStorageFile { public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetUserStoreForDomain() { return ObservableExt.Factory(() => System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForDomain()); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetUserStoreForAssembly() { return ObservableExt.Factory(() => System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForAssembly()); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetUserStoreForApplication() { return ObservableExt.Factory(() => System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication()); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetUserStoreForSite() { return ObservableExt.Factory(() => System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForSite()); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetMachineStoreForDomain() { return ObservableExt.Factory(() => System.IO.IsolatedStorage.IsolatedStorageFile.GetMachineStoreForDomain()); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetMachineStoreForAssembly() { return ObservableExt.Factory(() => System.IO.IsolatedStorage.IsolatedStorageFile.GetMachineStoreForAssembly()); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetMachineStoreForApplication() { return ObservableExt.Factory( () => System.IO.IsolatedStorage.IsolatedStorageFile.GetMachineStoreForApplication()); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetStore( IObservable<System.IO.IsolatedStorage.IsolatedStorageScope> scope, IObservable<System.Type> domainEvidenceType, IObservable<System.Type> assemblyEvidenceType) { return Observable.Zip(scope, domainEvidenceType, assemblyEvidenceType, (scopeLambda, domainEvidenceTypeLambda, assemblyEvidenceTypeLambda) => System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(scopeLambda, domainEvidenceTypeLambda, assemblyEvidenceTypeLambda)); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetStore( IObservable<System.IO.IsolatedStorage.IsolatedStorageScope> scope, IObservable<System.Object> domainIdentity, IObservable<System.Object> assemblyIdentity) { return Observable.Zip(scope, domainIdentity, assemblyIdentity, (scopeLambda, domainIdentityLambda, assemblyIdentityLambda) => System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(scopeLambda, domainIdentityLambda, assemblyIdentityLambda)); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetStore( IObservable<System.IO.IsolatedStorage.IsolatedStorageScope> scope, IObservable<System.Security.Policy.Evidence> domainEvidence, IObservable<System.Type> domainEvidenceType, IObservable<System.Security.Policy.Evidence> assemblyEvidence, IObservable<System.Type> assemblyEvidenceType) { return Observable.Zip(scope, domainEvidence, domainEvidenceType, assemblyEvidence, assemblyEvidenceType, (scopeLambda, domainEvidenceLambda, domainEvidenceTypeLambda, assemblyEvidenceLambda, assemblyEvidenceTypeLambda) => System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(scopeLambda, domainEvidenceLambda, domainEvidenceTypeLambda, assemblyEvidenceLambda, assemblyEvidenceTypeLambda)); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetStore( IObservable<System.IO.IsolatedStorage.IsolatedStorageScope> scope, IObservable<System.Type> applicationEvidenceType) { return Observable.Zip(scope, applicationEvidenceType, (scopeLambda, applicationEvidenceTypeLambda) => System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(scopeLambda, applicationEvidenceTypeLambda)); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> GetStore( IObservable<System.IO.IsolatedStorage.IsolatedStorageScope> scope, IObservable<System.Object> applicationIdentity) { return Observable.Zip(scope, applicationIdentity, (scopeLambda, applicationIdentityLambda) => System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(scopeLambda, applicationIdentityLambda)); } public static IObservable<System.Boolean> IncreaseQuotaTo( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.Int64> newQuotaSize) { return Observable.Zip(IsolatedStorageFileValue, newQuotaSize, (IsolatedStorageFileValueLambda, newQuotaSizeLambda) => IsolatedStorageFileValueLambda.IncreaseQuotaTo(newQuotaSizeLambda)); } public static IObservable<System.Reactive.Unit> DeleteFile( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> file) { return ObservableExt.ZipExecute(IsolatedStorageFileValue, file, (IsolatedStorageFileValueLambda, fileLambda) => IsolatedStorageFileValueLambda.DeleteFile(fileLambda)); } public static IObservable<System.Boolean> FileExists( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> path) { return Observable.Zip(IsolatedStorageFileValue, path, (IsolatedStorageFileValueLambda, pathLambda) => IsolatedStorageFileValueLambda.FileExists(pathLambda)); } public static IObservable<System.Boolean> DirectoryExists( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> path) { return Observable.Zip(IsolatedStorageFileValue, path, (IsolatedStorageFileValueLambda, pathLambda) => IsolatedStorageFileValueLambda.DirectoryExists(pathLambda)); } public static IObservable<System.Reactive.Unit> CreateDirectory( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> dir) { return ObservableExt.ZipExecute(IsolatedStorageFileValue, dir, (IsolatedStorageFileValueLambda, dirLambda) => IsolatedStorageFileValueLambda.CreateDirectory(dirLambda)); } public static IObservable<System.DateTimeOffset> GetCreationTime( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> path) { return Observable.Zip(IsolatedStorageFileValue, path, (IsolatedStorageFileValueLambda, pathLambda) => IsolatedStorageFileValueLambda.GetCreationTime(pathLambda)); } public static IObservable<System.DateTimeOffset> GetLastAccessTime( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> path) { return Observable.Zip(IsolatedStorageFileValue, path, (IsolatedStorageFileValueLambda, pathLambda) => IsolatedStorageFileValueLambda.GetLastAccessTime(pathLambda)); } public static IObservable<System.DateTimeOffset> GetLastWriteTime( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> path) { return Observable.Zip(IsolatedStorageFileValue, path, (IsolatedStorageFileValueLambda, pathLambda) => IsolatedStorageFileValueLambda.GetLastWriteTime(pathLambda)); } public static IObservable<System.Reactive.Unit> CopyFile( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> sourceFileName, IObservable<System.String> destinationFileName) { return ObservableExt.ZipExecute(IsolatedStorageFileValue, sourceFileName, destinationFileName, (IsolatedStorageFileValueLambda, sourceFileNameLambda, destinationFileNameLambda) => IsolatedStorageFileValueLambda.CopyFile(sourceFileNameLambda, destinationFileNameLambda)); } public static IObservable<System.Reactive.Unit> CopyFile( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> sourceFileName, IObservable<System.String> destinationFileName, IObservable<System.Boolean> overwrite) { return ObservableExt.ZipExecute(IsolatedStorageFileValue, sourceFileName, destinationFileName, overwrite, (IsolatedStorageFileValueLambda, sourceFileNameLambda, destinationFileNameLambda, overwriteLambda) => IsolatedStorageFileValueLambda.CopyFile(sourceFileNameLambda, destinationFileNameLambda, overwriteLambda)); } public static IObservable<System.Reactive.Unit> MoveFile( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> sourceFileName, IObservable<System.String> destinationFileName) { return ObservableExt.ZipExecute(IsolatedStorageFileValue, sourceFileName, destinationFileName, (IsolatedStorageFileValueLambda, sourceFileNameLambda, destinationFileNameLambda) => IsolatedStorageFileValueLambda.MoveFile(sourceFileNameLambda, destinationFileNameLambda)); } public static IObservable<System.Reactive.Unit> MoveDirectory( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> sourceDirectoryName, IObservable<System.String> destinationDirectoryName) { return ObservableExt.ZipExecute(IsolatedStorageFileValue, sourceDirectoryName, destinationDirectoryName, (IsolatedStorageFileValueLambda, sourceDirectoryNameLambda, destinationDirectoryNameLambda) => IsolatedStorageFileValueLambda.MoveDirectory(sourceDirectoryNameLambda, destinationDirectoryNameLambda)); } public static IObservable<System.Reactive.Unit> DeleteDirectory( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> dir) { return ObservableExt.ZipExecute(IsolatedStorageFileValue, dir, (IsolatedStorageFileValueLambda, dirLambda) => IsolatedStorageFileValueLambda.DeleteDirectory(dirLambda)); } public static IObservable<System.String[]> GetFileNames( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue) { return Observable.Select(IsolatedStorageFileValue, (IsolatedStorageFileValueLambda) => IsolatedStorageFileValueLambda.GetFileNames()); } public static IObservable<System.String[]> GetFileNames( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> searchPattern) { return Observable.Zip(IsolatedStorageFileValue, searchPattern, (IsolatedStorageFileValueLambda, searchPatternLambda) => IsolatedStorageFileValueLambda.GetFileNames(searchPatternLambda)); } public static IObservable<System.String[]> GetDirectoryNames( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue) { return Observable.Select(IsolatedStorageFileValue, (IsolatedStorageFileValueLambda) => IsolatedStorageFileValueLambda.GetDirectoryNames()); } public static IObservable<System.String[]> GetDirectoryNames( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> searchPattern) { return Observable.Zip(IsolatedStorageFileValue, searchPattern, (IsolatedStorageFileValueLambda, searchPatternLambda) => IsolatedStorageFileValueLambda.GetDirectoryNames(searchPatternLambda)); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> OpenFile( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> path, IObservable<System.IO.FileMode> mode) { return Observable.Zip(IsolatedStorageFileValue, path, mode, (IsolatedStorageFileValueLambda, pathLambda, modeLambda) => IsolatedStorageFileValueLambda.OpenFile(pathLambda, modeLambda)); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> OpenFile( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> path, IObservable<System.IO.FileMode> mode, IObservable<System.IO.FileAccess> access) { return Observable.Zip(IsolatedStorageFileValue, path, mode, access, (IsolatedStorageFileValueLambda, pathLambda, modeLambda, accessLambda) => IsolatedStorageFileValueLambda.OpenFile(pathLambda, modeLambda, accessLambda)); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> OpenFile( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> path, IObservable<System.IO.FileMode> mode, IObservable<System.IO.FileAccess> access, IObservable<System.IO.FileShare> share) { return Observable.Zip(IsolatedStorageFileValue, path, mode, access, share, (IsolatedStorageFileValueLambda, pathLambda, modeLambda, accessLambda, shareLambda) => IsolatedStorageFileValueLambda.OpenFile(pathLambda, modeLambda, accessLambda, shareLambda)); } public static IObservable<System.IO.IsolatedStorage.IsolatedStorageFileStream> CreateFile( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue, IObservable<System.String> path) { return Observable.Zip(IsolatedStorageFileValue, path, (IsolatedStorageFileValueLambda, pathLambda) => IsolatedStorageFileValueLambda.CreateFile(pathLambda)); } public static IObservable<System.Reactive.Unit> Remove( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue) { return Observable.Do(IsolatedStorageFileValue, (IsolatedStorageFileValueLambda) => IsolatedStorageFileValueLambda.Remove()).ToUnit(); } public static IObservable<System.Reactive.Unit> Close( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue) { return Observable.Do(IsolatedStorageFileValue, (IsolatedStorageFileValueLambda) => IsolatedStorageFileValueLambda.Close()).ToUnit(); } public static IObservable<System.Reactive.Unit> Dispose( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue) { return Observable.Do(IsolatedStorageFileValue, (IsolatedStorageFileValueLambda) => IsolatedStorageFileValueLambda.Dispose()).ToUnit(); } public static IObservable<System.Reactive.Unit> Remove( IObservable<System.IO.IsolatedStorage.IsolatedStorageScope> scope) { return Observable.Do(scope, (scopeLambda) => System.IO.IsolatedStorage.IsolatedStorageFile.Remove(scopeLambda)) .ToUnit(); } public static IObservable<System.Collections.IEnumerator> GetEnumerator( IObservable<System.IO.IsolatedStorage.IsolatedStorageScope> scope) { return Observable.Select(scope, (scopeLambda) => System.IO.IsolatedStorage.IsolatedStorageFile.GetEnumerator(scopeLambda)); } public static IObservable<System.Int64> get_UsedSize( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue) { return Observable.Select(IsolatedStorageFileValue, (IsolatedStorageFileValueLambda) => IsolatedStorageFileValueLambda.UsedSize); } public static IObservable<System.UInt64> get_CurrentSize( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue) { return Observable.Select(IsolatedStorageFileValue, (IsolatedStorageFileValueLambda) => IsolatedStorageFileValueLambda.CurrentSize); } public static IObservable<System.Int64> get_AvailableFreeSpace( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue) { return Observable.Select(IsolatedStorageFileValue, (IsolatedStorageFileValueLambda) => IsolatedStorageFileValueLambda.AvailableFreeSpace); } public static IObservable<System.Int64> get_Quota( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue) { return Observable.Select(IsolatedStorageFileValue, (IsolatedStorageFileValueLambda) => IsolatedStorageFileValueLambda.Quota); } public static IObservable<System.Boolean> get_IsEnabled() { return ObservableExt.Factory(() => System.IO.IsolatedStorage.IsolatedStorageFile.IsEnabled); } public static IObservable<System.UInt64> get_MaximumSize( this IObservable<System.IO.IsolatedStorage.IsolatedStorageFile> IsolatedStorageFileValue) { return Observable.Select(IsolatedStorageFileValue, (IsolatedStorageFileValueLambda) => IsolatedStorageFileValueLambda.MaximumSize); } } }
#region License /* * WsStream.cs * * The MIT License * * Copyright (c) 2010-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using WebSocketSharp.Net; using WebSocketSharp.Net.Security; namespace WebSocketSharp { internal class WsStream : IDisposable { #region Private Const Fields private const int _handshakeLimitLen = 8192; private const int _handshakeTimeout = 90000; #endregion #region Private Fields private object _forWrite; private Stream _innerStream; private bool _secure; #endregion #region Private Constructors private WsStream (Stream innerStream, bool secure) { _innerStream = innerStream; _secure = secure; _forWrite = new object (); } #endregion #region Internal Constructors internal WsStream (NetworkStream innerStream) : this (innerStream, false) { } internal WsStream (SslStream innerStream) : this (innerStream, true) { } #endregion #region Public Properties public bool DataAvailable { get { return _secure ? ((SslStream) _innerStream).DataAvailable : ((NetworkStream) _innerStream).DataAvailable; } } public bool IsSecure { get { return _secure; } } #endregion #region Internal Methods internal static WsStream CreateClientStream ( TcpClient client, bool secure, string host, System.Net.Security.RemoteCertificateValidationCallback validationCallback ) { var netStream = client.GetStream (); if (secure) { if (validationCallback == null) validationCallback = (sender, certificate, chain, sslPolicyErrors) => true; var sslStream = new SslStream (netStream, false, validationCallback); sslStream.AuthenticateAsClient (host); return new WsStream (sslStream); } return new WsStream (netStream); } internal static WsStream CreateServerStream ( TcpClient client, X509Certificate cert, bool secure) { var netStream = client.GetStream (); if (secure) { var sslStream = new SslStream (netStream, false); sslStream.AuthenticateAsServer (cert); return new WsStream (sslStream); } return new WsStream (netStream); } internal static WsStream CreateServerStream (HttpListenerContext context) { var conn = context.Connection; return new WsStream (conn.Stream, conn.IsSecure); } internal bool Write (byte [] data) { lock (_forWrite) { try { _innerStream.Write (data, 0, data.Length); return true; } catch { return false; } } } #endregion #region Public Methods public void Close () { _innerStream.Close (); } public void Dispose () { _innerStream.Dispose (); } public WsFrame ReadFrame () { return WsFrame.Parse (_innerStream, true); } public void ReadFrameAsync (Action<WsFrame> completed, Action<Exception> error) { WsFrame.ParseAsync (_innerStream, true, completed, error); } public string [] ReadHandshake () { var read = false; var exception = false; var buffer = new List<byte> (); Action<int> add = i => buffer.Add ((byte) i); var timeout = false; var timer = new Timer ( state => { timeout = true; _innerStream.Close (); }, null, _handshakeTimeout, -1); try { while (buffer.Count < _handshakeLimitLen) { if (_innerStream.ReadByte ().EqualsWith ('\r', add) && _innerStream.ReadByte ().EqualsWith ('\n', add) && _innerStream.ReadByte ().EqualsWith ('\r', add) && _innerStream.ReadByte ().EqualsWith ('\n', add)) { read = true; break; } } } catch { exception = true; } finally { timer.Change (-1, -1); timer.Dispose (); } var reason = timeout ? "A timeout has occurred while receiving a handshake." : exception ? "An exception has occurred while receiving a handshake." : !read ? "A handshake length is greater than the limit length." : null; if (reason != null) throw new WebSocketException (reason); return Encoding.UTF8.GetString (buffer.ToArray ()) .Replace ("\r\n", "\n") .Replace ("\n ", " ") .Replace ("\n\t", " ") .TrimEnd ('\n') .Split ('\n'); } public bool WriteFrame (WsFrame frame) { return Write (frame.ToByteArray ()); } public bool WriteHandshake (HandshakeBase handshake) { return Write (handshake.ToByteArray ()); } #endregion } }
using System; using System.Linq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.Persistence.Repositories { [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture] public class TaskRepositoryTest : BaseDatabaseFactoryTest { [Test] public void Can_Delete() { var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new TaskRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var created = DateTime.Now; var task = new Task(new TaskType("asdfasdf")) { AssigneeUserId = 0, Closed = false, Comment = "hello world", EntityId = -1, OwnerUserId = 0 }; repo.AddOrUpdate(task); unitOfWork.Commit(); repo.Delete(task); unitOfWork.Commit(); task = repo.Get(task.Id); Assert.IsNull(task); } } [Test] public void Can_Add() { var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new TaskRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var created = DateTime.Now; repo.AddOrUpdate(new Task(new TaskType("asdfasdf")) { AssigneeUserId = 0, Closed = false, Comment = "hello world", EntityId = -1, OwnerUserId = 0 }); unitOfWork.Commit(); var found = repo.GetAll().ToArray(); Assert.AreEqual(1, found.Count()); Assert.AreEqual(0, found.First().AssigneeUserId); Assert.AreEqual(false, found.First().Closed); Assert.AreEqual("hello world", found.First().Comment); Assert.GreaterOrEqual(found.First().CreateDate.TruncateTo(DateTimeExtensions.DateTruncate.Second), created.TruncateTo(DateTimeExtensions.DateTruncate.Second)); Assert.AreEqual(-1, found.First().EntityId); Assert.AreEqual(0, found.First().OwnerUserId); Assert.AreEqual(true, found.First().HasIdentity); Assert.AreEqual(true, found.First().TaskType.HasIdentity); } } [Test] public void Can_Update() { var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new TaskRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var task = new Task(new TaskType("asdfasdf")) { AssigneeUserId = 0, Closed = false, Comment = "hello world", EntityId = -1, OwnerUserId = 0 }; repo.AddOrUpdate(task); unitOfWork.Commit(); //re-get task = repo.Get(task.Id); task.Comment = "blah"; task.Closed = true; repo.AddOrUpdate(task); unitOfWork.Commit(); //re-get task = repo.Get(task.Id); Assert.AreEqual(true, task.Closed); Assert.AreEqual("blah", task.Comment); } } [Test] public void Get_By_Id() { var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new TaskRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var task = new Task(new TaskType("asdfasdf")) { AssigneeUserId = 0, Closed = false, Comment = "hello world", EntityId = -1, OwnerUserId = 0 }; repo.AddOrUpdate(task); unitOfWork.Commit(); //re-get task = repo.Get(task.Id); Assert.IsNotNull(task); } } [Test] public void Get_All() { CreateTestData(false, 20); var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new TaskRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var found = repo.GetAll().ToArray(); Assert.AreEqual(20, found.Count()); } } [Test] public void Get_All_With_Closed() { CreateTestData(false, 10); CreateTestData(true, 5); var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new TaskRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var found = repo.GetTasks(includeClosed: true).ToArray(); Assert.AreEqual(15, found.Count()); } } [Test] public void Get_All_With_Node_Id() { CreateTestData(false, 10, -20); CreateTestData(false, 5, -21); var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new TaskRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var found = repo.GetTasks(itemId:-20).ToArray(); Assert.AreEqual(10, found.Count()); } } [Test] public void Get_All_Without_Closed() { CreateTestData(false, 10); CreateTestData(true, 5); var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new TaskRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var found = repo.GetTasks(includeClosed: false); Assert.AreEqual(10, found.Count()); } } private void CreateTestData(bool closed, int count, int entityId = -1) { var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new TaskRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { for (int i = 0; i < count; i++) { repo.AddOrUpdate(new Task(new TaskType("asdfasdf")) { AssigneeUserId = 0, Closed = closed, Comment = "hello world " + i, EntityId = entityId, OwnerUserId = 0 }); unitOfWork.Commit(); } } } } }
using Newtonsoft.Json; 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; namespace FailureTroubleshooting.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. /// Processed in order, stopping when the factory successfully returns a non- <see /// langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code> /// SampleObjectFactories.Insert(0, func) /// </code>to provide an override and /// <code> /// SampleObjectFactories.Add(func) /// </code>to provide a fallback. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection"> /// The value indicating whether the sample is for a request or for a response. /// </param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an // HttpResponseMessage. Here we cannot rely on formatters because we don't know what's // in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection"> /// The value indicating whether the sample is for a request or for a response. /// </param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, // controllerName, actionName and parameterNames. If not found, try to get the sample // provided for the specified mediaType, sampleDirection, controllerName and actionName // regardless of the parameterNames. If still not found, try to get the sample provided // for the specified mediaType and type. Finally, try to get the sample provided for the // specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. First, it will look at /// the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one /// using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see /// cref="ObjectGenerator"/>) and other factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the /// <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see /// cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection"> /// The value indicating whether the sample is for a request or a response. /// </param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public class SqlNotificationTest : IDisposable { // Misc constants private const int CALLBACK_TIMEOUT = 5000; // milliseconds // Database schema private readonly string _tableName = "dbo.[SQLDEP_" + Guid.NewGuid().ToString() + "]"; private readonly string _queueName = "SQLDEP_" + Guid.NewGuid().ToString(); private readonly string _serviceName = "SQLDEP_" + Guid.NewGuid().ToString(); private readonly string _schemaQueue; // Connection information used by all tests private readonly string _startConnectionString; private readonly string _execConnectionString; public SqlNotificationTest() { _startConnectionString = DataTestUtility.TcpConnStr; _execConnectionString = DataTestUtility.TcpConnStr; var startBuilder = new SqlConnectionStringBuilder(_startConnectionString); if (startBuilder.IntegratedSecurity) { _schemaQueue = string.Format("[{0}]", _queueName); } else { _schemaQueue = string.Format("[{0}].[{1}]", startBuilder.UserID, _queueName); } Setup(); } public void Dispose() { Cleanup(); } #region StartStop_Tests [CheckConnStrSetupFact] public void Test_DoubleStart_SameConnStr() { Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener."); Assert.False(SqlDependency.Start(_startConnectionString), "Expected failure when trying to start listener."); Assert.False(SqlDependency.Stop(_startConnectionString), "Expected failure when trying to completely stop listener."); Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener."); } [CheckConnStrSetupFact] public void Test_DoubleStart_DifferentConnStr() { SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(_startConnectionString); // just change something that doesn't impact the dependency dispatcher if (cb.ShouldSerialize("connect timeout")) cb.ConnectTimeout = cb.ConnectTimeout + 1; else cb.ConnectTimeout = 50; Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener."); try { DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => SqlDependency.Start(cb.ToString())); } finally { Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener."); Assert.False(SqlDependency.Stop(cb.ToString()), "Expected failure when trying to completely stop listener."); } } [CheckConnStrSetupFact] public void Test_Start_DifferentDB() { SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(_startConnectionString) { InitialCatalog = "tempdb" }; string altDatabaseConnectionString = cb.ToString(); Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener."); Assert.True(SqlDependency.Start(altDatabaseConnectionString), "Failed to start listener."); Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener."); Assert.True(SqlDependency.Stop(altDatabaseConnectionString), "Failed to stop listener."); } #endregion #region SqlDependency_Tests [CheckConnStrSetupFact] public void Test_SingleDependency_NoStart() { using (SqlConnection conn = new SqlConnection(_execConnectionString)) using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn)) { conn.Open(); SqlDependency dep = new SqlDependency(cmd); dep.OnChange += delegate (object o, SqlNotificationEventArgs args) { Console.WriteLine("4 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source); }; DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => cmd.ExecuteReader()); } } [CheckConnStrSetupFact] public void Test_SingleDependency_Stopped() { SqlDependency.Start(_startConnectionString); SqlDependency.Stop(_startConnectionString); using (SqlConnection conn = new SqlConnection(_execConnectionString)) using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn)) { conn.Open(); SqlDependency dep = new SqlDependency(cmd); dep.OnChange += delegate (object o, SqlNotificationEventArgs args) { // Delegate won't be called, since notifications were stoppped Console.WriteLine("5 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source); }; DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => cmd.ExecuteReader()); } } [CheckConnStrSetupFact] public void Test_SingleDependency_AllDefaults_SqlAuth() { Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener."); try { // create a new event every time to avoid mixing notification callbacks ManualResetEvent notificationReceived = new ManualResetEvent(false); ManualResetEvent updateCompleted = new ManualResetEvent(false); using (SqlConnection conn = new SqlConnection(_execConnectionString)) using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn)) { conn.Open(); SqlDependency dep = new SqlDependency(cmd); dep.OnChange += delegate (object o, SqlNotificationEventArgs arg) { Assert.True(updateCompleted.WaitOne(CALLBACK_TIMEOUT, false), "Received notification, but update did not complete."); DataTestUtility.AssertEqualsWithDescription(SqlNotificationType.Change, arg.Type, "Unexpected Type value."); DataTestUtility.AssertEqualsWithDescription(SqlNotificationInfo.Update, arg.Info, "Unexpected Info value."); DataTestUtility.AssertEqualsWithDescription(SqlNotificationSource.Data, arg.Source, "Unexpected Source value."); notificationReceived.Set(); }; cmd.ExecuteReader(); } int count = RunSQL("UPDATE " + _tableName + " SET c=" + Environment.TickCount); DataTestUtility.AssertEqualsWithDescription(1, count, "Unexpected count value."); updateCompleted.Set(); Assert.True(notificationReceived.WaitOne(CALLBACK_TIMEOUT, false), "Notification not received within the timeout period"); } finally { Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener."); } } [CheckConnStrSetupFact] public void Test_SingleDependency_CustomQueue_SqlAuth() { Assert.True(SqlDependency.Start(_startConnectionString, _queueName), "Failed to start listener."); try { // create a new event every time to avoid mixing notification callbacks ManualResetEvent notificationReceived = new ManualResetEvent(false); ManualResetEvent updateCompleted = new ManualResetEvent(false); using (SqlConnection conn = new SqlConnection(_execConnectionString)) using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn)) { conn.Open(); SqlDependency dep = new SqlDependency(cmd, "service=" + _serviceName + ";local database=msdb", 0); dep.OnChange += delegate (object o, SqlNotificationEventArgs args) { Assert.True(updateCompleted.WaitOne(CALLBACK_TIMEOUT, false), "Received notification, but update did not complete."); Console.WriteLine("7 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source); notificationReceived.Set(); }; cmd.ExecuteReader(); } int count = RunSQL("UPDATE " + _tableName + " SET c=" + Environment.TickCount); DataTestUtility.AssertEqualsWithDescription(1, count, "Unexpected count value."); updateCompleted.Set(); Assert.False(notificationReceived.WaitOne(CALLBACK_TIMEOUT, false), "Notification should not be received."); } finally { Assert.True(SqlDependency.Stop(_startConnectionString, _queueName), "Failed to stop listener."); } } /// <summary> /// SqlDependecy premature timeout /// </summary> [CheckConnStrSetupFact] public void Test_SingleDependency_Timeout() { Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener."); try { // with resolution of 15 seconds, SqlDependency should fire timeout notification only after 45 seconds, leave 5 seconds gap from both sides. const int SqlDependencyTimerResolution = 15; // seconds const int testTimeSeconds = SqlDependencyTimerResolution * 3 - 5; const int minTimeoutEventInterval = testTimeSeconds - 1; const int maxTimeoutEventInterval = testTimeSeconds + SqlDependencyTimerResolution + 1; // create a new event every time to avoid mixing notification callbacks ManualResetEvent notificationReceived = new ManualResetEvent(false); DateTime startUtcTime; using (SqlConnection conn = new SqlConnection(_execConnectionString)) using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn)) { conn.Open(); // create SqlDependency with timeout SqlDependency dep = new SqlDependency(cmd, null, testTimeSeconds); dep.OnChange += delegate (object o, SqlNotificationEventArgs arg) { // notification of Timeout can arrive either from server or from client timer. Handle both situations here: SqlNotificationInfo info = arg.Info; if (info == SqlNotificationInfo.Unknown) { // server timed out before the client, replace it with Error to produce consistent output for trun info = SqlNotificationInfo.Error; } DataTestUtility.AssertEqualsWithDescription(SqlNotificationType.Change, arg.Type, "Unexpected Type value."); DataTestUtility.AssertEqualsWithDescription(SqlNotificationInfo.Error, arg.Info, "Unexpected Info value."); DataTestUtility.AssertEqualsWithDescription(SqlNotificationSource.Timeout, arg.Source, "Unexpected Source value."); notificationReceived.Set(); }; cmd.ExecuteReader(); startUtcTime = DateTime.UtcNow; } Assert.True( notificationReceived.WaitOne(TimeSpan.FromSeconds(maxTimeoutEventInterval), false), string.Format("Notification not received within the maximum timeout period of {0} seconds", maxTimeoutEventInterval)); // notification received in time, check that it is not too early TimeSpan notificationTime = DateTime.UtcNow - startUtcTime; Assert.True( notificationTime >= TimeSpan.FromSeconds(minTimeoutEventInterval), string.Format( "Notification was not expected before {0} seconds: received after {1} seconds", minTimeoutEventInterval, notificationTime.TotalSeconds)); } finally { Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener."); } } #endregion #region Utility_Methods private static string[] CreateSqlSetupStatements(string tableName, string queueName, string serviceName) { return new string[] { string.Format("CREATE TABLE {0}(a INT NOT NULL, b NVARCHAR(10), c INT NOT NULL)", tableName), string.Format("INSERT INTO {0} (a, b, c) VALUES (1, 'foo', 0)", tableName), string.Format("CREATE QUEUE {0}", queueName), string.Format("CREATE SERVICE [{0}] ON QUEUE {1} ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification])", serviceName, queueName) }; } private static string[] CreateSqlCleanupStatements(string tableName, string queueName, string serviceName) { return new string[] { string.Format("DROP TABLE {0}", tableName), string.Format("DROP SERVICE [{0}]", serviceName), string.Format("DROP QUEUE {0}", queueName) }; } private void Setup() { RunSQL(CreateSqlSetupStatements(_tableName, _schemaQueue, _serviceName)); } private void Cleanup() { RunSQL(CreateSqlCleanupStatements(_tableName, _schemaQueue, _serviceName)); } private int RunSQL(params string[] stmts) { int count = -1; using (SqlConnection conn = new SqlConnection(_execConnectionString)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); foreach (string stmt in stmts) { cmd.CommandText = stmt; int tmp = cmd.ExecuteNonQuery(); count = ((0 <= tmp) ? ((0 <= count) ? count + tmp : tmp) : count); } } return count; } #endregion } }
#region Copyright (c) 2004 Ian Davis and James Carlyle /*------------------------------------------------------------------------------ COPYRIGHT AND PERMISSION NOTICE Copyright (c) 2004 Ian Davis and James Carlyle 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 namespace SemPlan.Spiral.Utility { using SemPlan.Spiral.Core; using System; using System.Collections; using System.IO; // This class is being extracted from the enclosing class public class MemoryTripleStore : TripleStore { private Hashtable itsNamedResources; private Hashtable itsResourceDenotations; private Hashtable itsResourceStatements; private StatementHandler itsStatementHandler; private bool itsVerbose; public MemoryTripleStore() { itsNamedResources = new Hashtable(3000); itsResourceDenotations = new Hashtable(3000); itsStatementHandler = new StatementHandler(Add); itsResourceStatements = new Hashtable(1000); } public void Dispose() { itsNamedResources.Clear(); itsNamedResources = null; itsResourceDenotations.Clear(); itsResourceDenotations = null; itsResourceStatements.Clear(); itsResourceStatements = null; } public bool Verbose { get { return itsVerbose; } set { itsVerbose = value; } } public int NodeCount { get { return itsNamedResources.Count; } } public int ResourceCount { get { return itsResourceDenotations.Count; } } public int StatementCount { get { return itsResourceStatements.Count; } } //~ public IList Nodes { //~ get { //~ ArrayList nodeList = new ArrayList(); //~ nodeList.AddRange( itsNamedResources.Keys ); //~ return nodeList; //~ } //~ } public ResourceMap ResourceMap{ get { return this; } } public IList Resources { get { return ReferencedResources; } } public IList ReferencedResources { get { ArrayList resourceList = new ArrayList(); resourceList.AddRange( itsResourceDenotations.Keys ); return resourceList; } } public void Clear() { itsNamedResources = new Hashtable(); itsResourceDenotations = new Hashtable(); itsResourceStatements = new Hashtable(); itsStatementHandler = new StatementHandler(Add); } public void AddDenotation(GraphMember member, Resource theResource) { itsNamedResources[ member ] = theResource; if ( HasNodeDenoting( theResource )) { ((ArrayList)itsResourceDenotations[ theResource ]).Add( member ); } else { ArrayList nodeList = new ArrayList(); nodeList.Add( member ); itsResourceDenotations[ theResource ] = nodeList; } } public void AddDenotations(IList members, Resource theResource) { foreach (GraphMember member in members) { itsNamedResources[ member ] = theResource; } if ( HasNodeDenoting( theResource )) { ((ArrayList)itsResourceDenotations[ theResource ]).AddRange( members ); } else { ArrayList nodeList = new ArrayList(); nodeList.AddRange( members ); itsResourceDenotations[ theResource ] = nodeList; } } public void SetDenotations(IList members, Resource theResource) { foreach (GraphMember member in members) { itsNamedResources[ member ] = theResource; } ArrayList nodeList = new ArrayList(); nodeList.AddRange( members ); itsResourceDenotations[ theResource ] = nodeList; } public bool HasResourceDenotedBy(GraphMember theMember) { return itsNamedResources.ContainsKey(theMember); } public bool HasNodeDenoting(Resource theResource) { return itsResourceDenotations.ContainsKey(theResource); } public bool HasDenotation(GraphMember theMember, Resource theResource) { return itsNamedResources[theMember].Equals( theResource ); } public IList GetNodesDenoting(Resource theResource) { ArrayList nodeList = new ArrayList(); if ( HasNodeDenoting( theResource )) { nodeList.AddRange((ArrayList)itsResourceDenotations[ theResource ]); } return nodeList; } public GraphMember GetBestDenotingNode(Resource theResource) { Node theNode = null; if ( HasNodeDenoting( theResource )) { foreach (Node node in (ArrayList)itsResourceDenotations[ theResource ]) { if (node is BlankNode) { if (theNode == null) { theNode = node; } } else { return node; } } } if ( theNode == null) { BlankNode newNode = new BlankNode(); AddDenotation( newNode, theResource ); return newNode; } else { return theNode; } } /// <returns>A resource denoted by the subject if the subject is known, otherwise a new resource</returns> public virtual Resource GetResourceDenotedBy(GraphMember theMember) { if (itsNamedResources.ContainsKey(theMember) ) { return (Resource)itsNamedResources[theMember]; } else { Resource resource = MakeNewResourceForNode( theMember); AddDenotation( theMember, resource ); return resource; } } public virtual IDictionary GetResourcesDenotedBy(ICollection nodeList ) { Hashtable resourcesIndexedByNode = new Hashtable(); foreach (GraphMember node in nodeList) { if (itsNamedResources.ContainsKey(node) ) { resourcesIndexedByNode[node] = itsNamedResources[node]; } } return resourcesIndexedByNode; } public Resource MakeNewResourceForNode(GraphMember theMember) { if (theMember.IsSelfDenoting()) { return new Resource( theMember ); } else { return new Resource(); } } public GraphMember MakeNameForResource( Resource theResource) { if (theResource.Value is GraphMember) { return (GraphMember)theResource.Value; } else { return new BlankNode(); } } public void Add(Statement statement) { Resource theSubject; if ( HasResourceDenotedBy( statement.GetSubject() ) ) { theSubject = GetResourceDenotedBy( statement.GetSubject() ); } else { theSubject = MakeNewResourceForNode( statement.GetSubject() ); AddDenotation( statement.GetSubject(), theSubject ); } Resource thePredicate; if ( HasResourceDenotedBy( statement.GetPredicate() ) ) { thePredicate = GetResourceDenotedBy( statement.GetPredicate() ); } else { thePredicate = MakeNewResourceForNode( statement.GetPredicate() ); AddDenotation( statement.GetPredicate(), thePredicate ); } Resource theObject; if ( HasResourceDenotedBy( statement.GetObject() ) ) { theObject = GetResourceDenotedBy( statement.GetObject() ); } else { theObject = MakeNewResourceForNode( statement.GetObject() ); AddDenotation( statement.GetObject(), theObject ); } ResourceStatement resourceStatement = new ResourceStatement( theSubject, thePredicate, theObject ); Add( resourceStatement ); } public void Add(Resource theSubject, Arc thePredicateArc, Resource theObject) { Resource thePredicate; if ( HasResourceDenotedBy( thePredicateArc ) ) { thePredicate = GetResourceDenotedBy( thePredicateArc ); } else { thePredicate = MakeNewResourceForNode( thePredicateArc ); AddDenotation( thePredicateArc, thePredicate ); } Add( new ResourceStatement( theSubject, thePredicate, theObject ) ); } public void Add(ResourceStatement resourceStatement) { if ( ! itsResourceStatements.ContainsKey( resourceStatement ) ) { if (! HasNodeDenoting( resourceStatement.GetSubject() ) ) { AddDenotation( MakeNameForResource(resourceStatement.GetSubject()), resourceStatement.GetSubject() ); } if (! HasNodeDenoting( resourceStatement.GetPredicate() ) ) { AddDenotation( MakeNameForResource(resourceStatement.GetPredicate()), resourceStatement.GetPredicate() ); } if (! HasNodeDenoting( resourceStatement.GetObject() ) ) { AddDenotation( MakeNameForResource(resourceStatement.GetObject()), resourceStatement.GetObject() ); } itsResourceStatements[ resourceStatement ] = resourceStatement; } } public void Remove(ResourceStatement resourceStatement) { itsResourceStatements.Remove( resourceStatement ); } public IEnumerator GetStatementEnumerator() { return itsResourceStatements.Keys.GetEnumerator(); } public bool IsEmpty() { return (itsResourceStatements.Count == 0); } public void Dump() { Console.WriteLine( "Triples:"); Console.WriteLine( ToString() ); Console.WriteLine(" itsNamedResources:"); foreach (Node node in itsNamedResources.Keys) { Console.WriteLine(" Node {0} maps to Resource {1}", node, itsNamedResources[node]); } } public override string ToString() { StringWriter stringWriter = new StringWriter(); NTripleWriter writer = new NTripleWriter(stringWriter); Write(writer); return stringWriter.ToString(); } public object Clone() { MemoryTripleStore theClone = new MemoryTripleStore(); theClone.itsNamedResources = (Hashtable)itsNamedResources.Clone(); theClone.itsResourceDenotations = (Hashtable)itsResourceDenotations.Clone(); theClone.itsResourceStatements = (Hashtable)itsResourceStatements.Clone(); return theClone; } public void Write(RdfWriter writer) { writer.StartOutput(); IEnumerator statementEnum = GetStatementEnumerator(); while (statementEnum.MoveNext()) { ResourceStatement statement = (ResourceStatement)statementEnum.Current; writer.StartSubject(); GetBestDenotingNode(statement.GetSubject()).Write(writer); writer.StartPredicate(); GetBestDenotingNode(statement.GetPredicate()).Write(writer); writer.StartObject(); GetBestDenotingNode(statement.GetObject()).Write(writer); writer.EndObject(); writer.EndPredicate(); writer.EndSubject(); } writer.EndOutput(); } public StatementHandler GetStatementHandler() { return itsStatementHandler; } public bool Contains(Statement statement) { if ( ! HasResourceDenotedBy( statement.GetSubject()) ) { return false; } if ( ! HasResourceDenotedBy( statement.GetPredicate()) ) { return false; } if ( ! HasResourceDenotedBy( statement.GetObject() ) ) { return false; } Resource theSubject = GetResourceDenotedBy( statement.GetSubject() ); Resource thePredicate = GetResourceDenotedBy( statement.GetPredicate() ); Resource theObject = GetResourceDenotedBy( statement.GetObject() ); ResourceStatement testStatement = new ResourceStatement( theSubject, thePredicate, theObject); return Contains( testStatement ); } public bool Contains(ResourceStatement resourceStatement) { return itsResourceStatements.ContainsKey( resourceStatement ); } public void Merge(ResourceStatementCollection statements, ResourceMap map) { if (this == statements) return; Hashtable equivalentResources = new Hashtable(); foreach (Resource resource in statements.ReferencedResources) { Resource internalResource = resource; foreach (GraphMember member in map.GetNodesDenoting( resource ) ) { if ( HasResourceDenotedBy( member ) ) { internalResource = GetResourceDenotedBy( member ); equivalentResources[ resource ] = internalResource; break; } // Must be a new resource // Remember this for when we're Adding statements // TODO: move this outside the loop equivalentResources[ resource ] = resource; } foreach (GraphMember member in map.GetNodesDenoting( resource ) ) { AddDenotation( member, internalResource ); } } IEnumerator statementEnumerator = statements.GetStatementEnumerator(); while (statementEnumerator.MoveNext()) { ResourceStatement statement = (ResourceStatement)statementEnumerator.Current; ResourceStatement internalStatement = new ResourceStatement( (Resource)equivalentResources[ statement.GetSubject() ] , (Resource)equivalentResources[ statement.GetPredicate() ] , (Resource)equivalentResources[ statement.GetObject() ] ); Add( internalStatement ); } } public void Add(TripleStore other) { if (this == other) return; Merge( other, other ); } public IEnumerator Solve(Query query) { return new BacktrackingQuerySolver( query, this); } public void Evaluate(Rule rule) { SimpleRuleProcessor ruleProcessor = new SimpleRuleProcessor(); ruleProcessor.Process( rule, this ); } public void Add(ResourceDescription description) { Merge( description, description.ResourceMap ); } /// <returns>A bounded description generated according to the specified strategy.</returns> public virtual ResourceDescription GetDescriptionOf(Resource theResource, BoundingStrategy strategy) { return strategy.GetDescriptionOf( theResource, this ); } /// <returns>A bounded description generated according to the specified strategy.</returns> public virtual ResourceDescription GetDescriptionOf(Node theNode, BoundingStrategy strategy) { return GetDescriptionOf( GetResourceDenotedBy(theNode), strategy ); } } }
using GameTimer; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using System; using System.Threading.Tasks; namespace MenuBuddy { /// <summary> /// A screen is a single layer that has update and draw logic, and which /// can be combined with other layers to build up a complex menu system. /// For instance the main menu, the options menu, the "are you sure you /// want to quit" message box, and the main game itself are all implemented /// as screens. /// </summary> public abstract class Screen : IScreen, IDisposable { #region Properties /// <summary> /// Checks whether this game is active and can respond to user input. /// </summary> private bool OtherWindowHasFocus { get; set; } /// <summary> /// Whether or not this screen is currently covered by another screen /// </summary> private bool CurrentlyCovered { get; set; } /// <summary> /// Whether or not screens underneath this one should tranisition off /// </summary> public virtual bool CoverOtherScreens { get; set; } /// <summary> /// Whether or not this screen should transition off when covered by other screens /// </summary> public virtual bool CoveredByOtherScreens { get; set; } /// <summary> /// There are two possible reasons why a screen might be transitioning off. /// It could be temporarily going away to make room for another /// screen that is on top of it, or it could be going away for good. /// This property indicates whether the screen is exiting for real: /// if set, the screen will automatically remove itself as soon as the /// transition finishes. /// </summary> public virtual bool IsExiting { get { return _isExiting; } protected set { bool fireEvent = !_isExiting && value; _isExiting = value; if (fireEvent && (Exiting != null)) { Exiting(this, EventArgs.Empty); } } } private bool _isExiting = false; public bool IsActive { get { return !OtherWindowHasFocus && //the window is not covered (!CoveredByOtherScreens || !CurrentlyCovered) && //the screen is not covered or don't care (TransitionState == TransitionState.TransitionOn || TransitionState == TransitionState.Active); //the transition is correct state } } public bool HasFocus { get { return !OtherWindowHasFocus && //the window is not covered !CurrentlyCovered && //the screen is not covered (TransitionState == TransitionState.TransitionOn || TransitionState == TransitionState.Active); //the transition is correct state } } /// <summary> /// Gets the manager that this screen belongs to. /// </summary> public ScreenManager ScreenManager { get; set; } private bool OwnsContent { get; set; } public ContentManager Content { get; private set; } /// <summary> /// Gets the index of the player who is currently controlling this screen, /// or null if it is accepting input from any player. This is used to lock /// the game to a specific player profile. The main menu responds to input /// from any connected gamepad, but whichever player makes a selection from /// this menu is given control over all subsequent screens, so other gamepads /// are inactive until the controlling player returns to the main menu. /// </summary> public int? ControllingPlayer { get; set; } /// <summary> /// Gets or sets the name of this screen /// </summary> public virtual string ScreenName { get; set; } /// <summary> /// Event that gets called when the screen is exiting /// </summary> public event EventHandler Exiting; public GameClock Time { get; private set; } /// <summary> /// Object used to aid in transitioning on and off /// </summary> public IScreenTransition Transition { get; set; } public TransitionState TransitionState { get { return Transition?.State ?? TransitionState.Hidden; } } /// <summary> /// The style of this screen. /// Inherits from the ScreenManager style /// </summary> public StyleSheet Style { get; private set; } /// <summary> /// Set the layer of a screen to change it's location in the ScreenStack /// </summary> public int Layer { get; set; } /// <summary> /// Used by the ScreenStack to sort screens. Don't touch! /// </summary> public int SubLayer { get; set; } public bool FinishedLoading { get; protected set; } #endregion #region Initialization /// <summary> /// Initializes a new instance of the <see cref="MenuBuddy.GameScreen"/> class. /// </summary> protected Screen(string screenName = "", ContentManager content = null) { OwnsContent = content == null; Content = content; CoverOtherScreens = false; CoveredByOtherScreens = false; CurrentlyCovered = false; OtherWindowHasFocus = false; IsExiting = false; ScreenName = screenName; Transition = new ScreenTransition(); Time = new GameClock(); Time.Start(); Layer = int.MaxValue; FinishedLoading = true; } /// <summary> /// Load graphics content for the screen. /// </summary> public virtual Task LoadContent() { if (null != ScreenManager && null == Content) { var defaultGame = ScreenManager.Game as DefaultGame; Content = new ContentManager(defaultGame.Services, defaultGame.ContentRootDirectory); } return Task.CompletedTask; } /// <summary> /// Unload content for the screen. /// </summary> public virtual void UnloadContent() { if (OwnsContent) { Content?.Dispose(); } Content = null; Transition = null; Exiting = null; } #endregion #region Update and Draw /// <summary> /// Allows the screen to run logic, such as updating the transition position. /// Unlike HandleInput, this method is called regardless of whether the screen /// is active, hidden, or in the middle of a transition. /// </summary> /// <param name="gameTime"></param> /// <param name="otherWindowHasFocus"></param> /// <param name="covered"></param> public virtual void Update(GameTime gameTime, bool otherWindowHasFocus, bool covered) { //Grab the parameters that were passed in OtherWindowHasFocus = otherWindowHasFocus; CurrentlyCovered = covered; Time.Update(gameTime); var transitionResult = UpdateTransition(Transition, Time); if (IsExiting) { if (!transitionResult) { // When the transition finishes, remove the screen. ScreenManager.RemoveScreen(this); } } } public bool UpdateTransition(IScreenTransition screenTransition, GameClock gameTime) { var transitionResult = false; if (IsExiting) { // If the screen is going away to die, it should transition off. transitionResult = screenTransition.Update(gameTime, false); screenTransition.State = TransitionState.TransitionOff; } else if (CurrentlyCovered && CoveredByOtherScreens) { // If the screen is covered by another, it should transition off. transitionResult = screenTransition.Update(gameTime, false); if (transitionResult) { // Still busy transitioning. screenTransition.State = TransitionState.TransitionOff; } else { // Transition finished! screenTransition.State = TransitionState.Hidden; } } else { // Otherwise the screen should transition on and become active. transitionResult = screenTransition.Update(gameTime, true); if (transitionResult) { // Still busy transitioning. screenTransition.State = TransitionState.TransitionOn; } else { // Transition finished! screenTransition.State = TransitionState.Active; } } return transitionResult; } /// <summary> /// This is called when the screen should draw itself. /// </summary> public virtual void Draw(GameTime gameTime) { } /// <summary> /// Fade the background behind this screen /// </summary> protected void FadeBackground() { //gray out the screens under this one FadeBackground(.66f); } /// <summary> /// Fade the background behind this screen /// </summary> protected void FadeBackground(float alpha) { //gray out the screens under this one ScreenManager.DrawHelper.FadeBackground(Transition.Alpha * alpha); } #endregion #region Public Methods /// <summary> /// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which /// instantly kills the screen, this method respects the transition timings /// and will give the screen a chance to gradually transition off. /// </summary> public virtual void ExitScreen() { //flag that it should transition off and then exit. IsExiting = true; } public override string ToString() { return ScreenName; } public virtual void Dispose() { UnloadContent(); //just double check that this is getting called if (null != Content) { throw new Exception($"Error: UnloadContent was not called in \"{ScreenName}\""); } } public virtual bool OnBackButton() { return false; } #endregion } }
// TarArchive.cs // // Copyright (C) 2001 Mike Krueger // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; using System.Text; namespace ICSharpCode.SharpZipLib.Silverlight.Tar { /// <summary> /// Used to advise clients of 'events' while processing archives /// </summary> public delegate void ProgressMessageHandler(TarArchive archive, TarEntry entry, string message); /// <summary> /// The TarArchive class implements the concept of a /// 'Tape Archive'. A tar archive is a series of entries, each of /// which represents a file system object. Each entry in /// the archive consists of a header block followed by 0 or more data blocks. /// Directory entries consist only of the header block, and are followed by entries /// for the directory's contents. File entries consist of a /// header followed by the number of blocks needed to /// contain the file's contents. All entries are written on /// block boundaries. Blocks are 512 bytes long. /// /// TarArchives are instantiated in either read or write mode, /// based upon whether they are instantiated with an InputStream /// or an OutputStream. Once instantiated TarArchives read/write /// mode can not be changed. /// /// There is currently no support for random access to tar archives. /// However, it seems that subclassing TarArchive, and using the /// TarBuffer.CurrentRecord and TarBuffer.CurrentBlock /// properties, this would be rather trivial. /// </summary> public class TarArchive : IDisposable { /// <summary> /// Get/set the ascii file translation flag. If ascii file translation /// is true, then the file is checked to see if it a binary file or not. /// If the flag is true and the test indicates it is ascii text /// file, it will be translated. The translation converts the local /// operating system's concept of line ends into the UNIX line end, /// '\n', which is the defacto standard for a TAR archive. This makes /// text files compatible with UNIX. /// </summary> public bool AsciiTranslate { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return _asciiTranslate; } set { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } _asciiTranslate = value; } } /// <summary> /// PathPrefix is added to entry names as they are written if the value is not null. /// A slash character is appended after PathPrefix /// </summary> public string PathPrefix { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return pathPrefix; } set { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } pathPrefix = value; } } /// <summary> /// RootPath is removed from entry names if it is found at the /// beginning of the name. /// </summary> public string RootPath { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return rootPath; } set { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } rootPath = value; } } /// <summary> /// Get or set a value indicating if overrides defined by <see cref="SetUserInfo">SetUserInfo</see> should be applied. /// </summary> /// <remarks>If overrides are not applied then the values as set in each header will be used.</remarks> public bool ApplyUserInfoOverrides { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return _applyUserInfoOverrides; } set { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } _applyUserInfoOverrides = value; } } /// <summary> /// Get the archive user id. /// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail /// on how to allow setting values on a per entry basis. /// </summary> /// <returns> /// The current user id. /// </returns> public int UserId { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return _userId; } } /// <summary> /// Get the archive user name. /// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail /// on how to allow setting values on a per entry basis. /// </summary> /// <returns> /// The current user name. /// </returns> public string UserName { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return _userName; } } /// <summary> /// Get the archive group id. /// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail /// on how to allow setting values on a per entry basis. /// </summary> /// <returns> /// The current group id. /// </returns> public int GroupId { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return _groupId; } } /// <summary> /// Get the archive group name. /// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail /// on how to allow setting values on a per entry basis. /// </summary> /// <returns> /// The current group name. /// </returns> public string GroupName { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } return _groupName; } } /// <summary> /// Get the archive's record size. Tar archives are composed of /// a series of RECORDS each containing a number of BLOCKS. /// This allowed tar archives to match the IO characteristics of /// the physical device being used. Archives are expected /// to be properly "blocked". /// </summary> /// <returns> /// The record size this archive is using. /// </returns> public int RecordSize { get { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } if (tarIn != null) { return tarIn.RecordSize; } if (tarOut != null) { return tarOut.RecordSize; } return TarBuffer.DefaultRecordSize; } } #region IDisposable Members void IDisposable.Dispose() { Close(); } #endregion /// <summary> /// Client hook allowing detailed information to be reported during processing /// </summary> public event ProgressMessageHandler ProgressMessageEvent; /// <summary> /// Raises the ProgressMessage event /// </summary> /// <param name="entry">The <see cref="TarEntry">TarEntry</see> for this event</param> /// <param name="message">message for this event. Null is no message</param> protected virtual void OnProgressMessageEvent(TarEntry entry, string message) { if (ProgressMessageEvent != null) { ProgressMessageEvent(this, entry, message); } } /// <summary> /// Set the flag that determines whether existing files are /// kept, or overwritten during extraction. /// </summary> /// <param name="keepOldFiles"> /// If true, do not overwrite existing files. /// </param> public void SetKeepOldFiles(bool keepOldFiles) { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } _keepOldFiles = keepOldFiles; } /// <summary> /// Set the ascii file translation flag. /// </summary> /// <param name= "asciiTranslate"> /// If true, translate ascii text files. /// </param> [Obsolete("Use the AsciiTranslate property")] public void SetAsciiTranslation(bool asciiTranslate) { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } _asciiTranslate = asciiTranslate; } /// <summary> /// Set user and group information that will be used to fill in the /// tar archive's entry headers. This information based on that available /// for the linux operating system, which is not always available on other /// operating systems. TarArchive allows the programmer to specify values /// to be used in their place. /// <see cref="ApplyUserInfoOverrides"/> is set to true by this call. /// </summary> /// <param name="userId"> /// The user id to use in the headers. /// </param> /// <param name="userName"> /// The user name to use in the headers. /// </param> /// <param name="groupId"> /// The group id to use in the headers. /// </param> /// <param name="groupName"> /// The group name to use in the headers. /// </param> public void SetUserInfo(int userId, string userName, int groupId, string groupName) { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } _userId = userId; _userName = userName; _groupId = groupId; _groupName = groupName; _applyUserInfoOverrides = true; } /// <summary> /// Close the archive. /// </summary> [Obsolete("Use Close instead")] public void CloseArchive() { Close(); } /// <summary> /// Perform the "list" command for the archive contents. /// /// NOTE That this method uses the <see cref="ProgressMessageEvent"> progress event</see> to actually list /// the contents. If the progress display event is not set, nothing will be listed! /// </summary> public void ListContents() { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } while (true) { var entry = tarIn.GetNextEntry(); if (entry == null) { break; } OnProgressMessageEvent(entry, null); } } /// <summary> /// Perform the "extract" command and extract the contents of the archive. /// </summary> /// <param name="destinationDirectory"> /// The destination directory into which to extract. /// </param> public void ExtractContents(string destinationDirectory) { if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } while (true) { var entry = tarIn.GetNextEntry(); if (entry == null) { break; } ExtractEntry(destinationDirectory, entry); } } /// <summary> /// Extract an entry from the archive. This method assumes that the /// tarIn stream has been properly set with a call to GetNextEntry(). /// </summary> /// <param name="destDir"> /// The destination directory into which to extract. /// </param> /// <param name="entry"> /// The TarEntry returned by tarIn.GetNextEntry(). /// </param> private void ExtractEntry(string destDir, TarEntry entry) { OnProgressMessageEvent(entry, null); var name = entry.Name; if (Path.IsPathRooted(name)) { // NOTE: // for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt name = name.Substring(Path.GetPathRoot(name).Length); } name = name.Replace('/', Path.DirectorySeparatorChar); var destFile = Path.Combine(destDir, name); if (entry.IsDirectory) { EnsureDirectoryExists(destFile); } else { var parentDirectory = Path.GetDirectoryName(destFile); EnsureDirectoryExists(parentDirectory); var process = true; var fileInfo = new FileInfo(destFile); if (fileInfo.Exists) { if (_keepOldFiles) { OnProgressMessageEvent(entry, "Destination file already exists"); process = false; } else if ((fileInfo.Attributes & FileAttributes.ReadOnly) != 0) { OnProgressMessageEvent(entry, "Destination file already exists, and is read-only"); process = false; } } if (process) { var asciiTrans = false; Stream outputStream = File.Create(destFile); if (_asciiTranslate) { asciiTrans = !IsBinary(destFile); } StreamWriter outw = null; if (asciiTrans) { outw = new StreamWriter(outputStream); } var rdbuf = new byte[32*1024]; while (true) { var numRead = tarIn.Read(rdbuf, 0, rdbuf.Length); if (numRead <= 0) { break; } if (asciiTrans) { for (int off = 0, b = 0; b < numRead; ++b) { if (rdbuf[b] == 10) { var s = Encoding.UTF8.GetString(rdbuf, off, (b - off)); outw.WriteLine(s); off = b + 1; } } } else { outputStream.Write(rdbuf, 0, numRead); } } if (asciiTrans) { outw.Close(); } else { outputStream.Close(); } } } } /// <summary> /// Write an entry to the archive. This method will call the putNextEntry /// and then write the contents of the entry, and finally call closeEntry() /// for entries that are files. For directories, it will call putNextEntry(), /// and then, if the recurse flag is true, process each entry that is a /// child of the directory. /// </summary> /// <param name="sourceEntry"> /// The TarEntry representing the entry to write to the archive. /// </param> /// <param name="recurse"> /// If true, process the children of directory entries. /// </param> public void WriteEntry(TarEntry sourceEntry, bool recurse) { if (sourceEntry == null) { throw new ArgumentNullException("sourceEntry"); } if (isDisposed) { throw new ObjectDisposedException("TarArchive"); } try { if (recurse) { TarHeader.SetValueDefaults(sourceEntry.UserId, sourceEntry.UserName, sourceEntry.GroupId, sourceEntry.GroupName); } InternalWriteEntry(sourceEntry, recurse); } finally { if (recurse) { TarHeader.RestoreSetValues(); } } } /// <summary> /// Write an entry to the archive. This method will call the putNextEntry /// and then write the contents of the entry, and finally call closeEntry() /// for entries that are files. For directories, it will call putNextEntry(), /// and then, if the recurse flag is true, process each entry that is a /// child of the directory. /// </summary> /// <param name="sourceEntry"> /// The TarEntry representing the entry to write to the archive. /// </param> /// <param name="recurse"> /// If true, process the children of directory entries. /// </param> private void InternalWriteEntry(TarEntry sourceEntry, bool recurse) { string tempFileName = null; var entryFilename = sourceEntry.File; var entry = (TarEntry) sourceEntry.Clone(); if (_applyUserInfoOverrides) { entry.GroupId = _groupId; entry.GroupName = _groupName; entry.UserId = _userId; entry.UserName = _userName; } OnProgressMessageEvent(entry, null); if (_asciiTranslate && !entry.IsDirectory) { var asciiTrans = !IsBinary(entryFilename); if (asciiTrans) { tempFileName = Path.GetTempFileName(); using (var inStream = File.OpenText(entryFilename)) { using (Stream outStream = File.Create(tempFileName)) { while (true) { var line = inStream.ReadLine(); if (line == null) { break; } var data = Encoding.UTF8.GetBytes(line); outStream.Write(data, 0, data.Length); outStream.WriteByte((byte) '\n'); } outStream.Flush(); } } entry.Size = new FileInfo(tempFileName).Length; entryFilename = tempFileName; } } string newName = null; if (rootPath != null) { if (entry.Name.StartsWith(rootPath)) { newName = entry.Name.Substring(rootPath.Length + 1); } } if (pathPrefix != null) { newName = (newName == null) ? string.Format("{0}/{1}", pathPrefix, entry.Name) : pathPrefix + "/" + newName; } if (newName != null) { entry.Name = newName; } tarOut.PutNextEntry(entry); if (entry.IsDirectory) { if (recurse) { var list = entry.GetDirectoryEntries(); for (var i = 0; i < list.Length; ++i) { InternalWriteEntry(list[i], recurse); } } } else { using (Stream inputStream = File.OpenRead(entryFilename)) { var localBuffer = new byte[32*1024]; while (true) { var numRead = inputStream.Read(localBuffer, 0, localBuffer.Length); if (numRead <= 0) { break; } tarOut.Write(localBuffer, 0, numRead); } } if (!string.IsNullOrEmpty(tempFileName)) { File.Delete(tempFileName); } tarOut.CloseEntry(); } } /// <summary> /// Releases the unmanaged resources used by the FileStream and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; /// false to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (!isDisposed) { isDisposed = true; if (disposing) { if (tarOut != null) { tarOut.Flush(); tarOut.Close(); } if (tarIn != null) { tarIn.Close(); } } } } /// <summary> /// Closes the archive and releases any associated resources. /// </summary> public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Ensures that resources are freed and other cleanup operations are performed /// when the garbage collector reclaims the <see cref="TarArchive"/>. /// </summary> ~TarArchive() { Dispose(false); } private static void EnsureDirectoryExists(string directoryName) { if (!Directory.Exists(directoryName)) { try { Directory.CreateDirectory(directoryName); } catch (Exception e) { throw new TarException("Exception creating directory '" + directoryName + "', " + e.Message, e); } } } // TODO: TarArchive - Is there a better way to test for a text file? // It no longer reads entire files into memory but is still a weak test! // This assumes that byte values 0-7, 14-31 or 255 are binary // and that all non text files contain one of these values private static bool IsBinary(string filename) { using (var fs = File.OpenRead(filename)) { var sampleSize = Math.Min(4096, (int) fs.Length); var content = new byte[sampleSize]; var bytesRead = fs.Read(content, 0, sampleSize); for (var i = 0; i < bytesRead; ++i) { var b = content[i]; if ((b < 8) || ((b > 13) && (b < 32)) || (b == 255)) { return true; } } } return false; } #region Instance Fields private readonly TarInputStream tarIn; private readonly TarOutputStream tarOut; private bool _applyUserInfoOverrides; private bool _asciiTranslate; private int _groupId; private string _groupName = string.Empty; private bool isDisposed; private bool _keepOldFiles; private string pathPrefix; private string rootPath; private int _userId; private string _userName = string.Empty; #endregion #region Constructors /// <summary> /// Constructor for a default <see cref="TarArchive"/>. /// </summary> protected TarArchive() { } /// <summary> /// Initalise a TarArchive for input. /// </summary> /// <param name="stream">The <see cref="TarInputStream"/> to use for input.</param> protected TarArchive(TarInputStream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } tarIn = stream; } /// <summary> /// Initialise a TarArchive for output. /// </summary> /// <param name="stream">The <see cref="TarOutputStream"/> to use for output.</param> protected TarArchive(TarOutputStream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } tarOut = stream; } #endregion #region Static factory methods /// <summary> /// The InputStream based constructors create a TarArchive for the /// purposes of extracting or listing a tar archive. Thus, use /// these constructors when you wish to extract files from or list /// the contents of an existing tar archive. /// </summary> /// <param name="inputStream">The stream to retrieve archive data from.</param> /// <returns>Returns a new <see cref="TarArchive"/> suitable for reading from.</returns> public static TarArchive CreateInputTarArchive(Stream inputStream) { if (inputStream == null) { throw new ArgumentNullException("inputStream"); } return CreateInputTarArchive(inputStream, TarBuffer.DefaultBlockFactor); } /// <summary> /// Create TarArchive for reading setting block factor /// </summary> /// <param name="inputStream">Stream for tar archive contents</param> /// <param name="blockFactor">The blocking factor to apply</param> /// <returns>Returns a <see cref="TarArchive"/> suitable for reading.</returns> public static TarArchive CreateInputTarArchive(Stream inputStream, int blockFactor) { if (inputStream == null) { throw new ArgumentNullException("inputStream"); } return new TarArchive(new TarInputStream(inputStream, blockFactor)); } /// <summary> /// Create a TarArchive for writing to, using the default blocking factor /// </summary> /// <param name="outputStream">The <see cref="Stream"/> to write to</param> /// <returns>Returns a <see cref="TarArchive"/> suitable for writing.</returns> public static TarArchive CreateOutputTarArchive(Stream outputStream) { if (outputStream == null) { throw new ArgumentNullException("outputStream"); } return CreateOutputTarArchive(outputStream, TarBuffer.DefaultBlockFactor); } /// <summary> /// Create a TarArchive for writing to /// </summary> /// <param name="outputStream">The stream to write to</param> /// <param name="blockFactor">The blocking factor to use for buffering.</param> /// <returns>Returns a <see cref="TarArchive"/> suitable for writing.</returns> public static TarArchive CreateOutputTarArchive(Stream outputStream, int blockFactor) { if (outputStream == null) { throw new ArgumentNullException("outputStream"); } return new TarArchive(new TarOutputStream(outputStream, blockFactor)); } #endregion } } /* The original Java file had this header: ** Authored by Timothy Gerard Endres ** <mailto:time@gjt.org> <http://www.trustice.com> ** ** This work has been placed into the public domain. ** You may use this work in any way and for any purpose you wish. ** ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR ** REDISTRIBUTION OF THIS SOFTWARE. ** */
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Text.RegularExpressions; using AutoRest.Core.Model; using AutoRest.Core.Utilities; using AutoRest.Extensions; using Newtonsoft.Json; namespace AutoRest.CSharp.Model { public class MethodCs : Method { public MethodCs() { } public bool IsCustomBaseUri => CodeModel.Extensions.ContainsKey(SwaggerExtensions.ParameterizedHostExtension); public SyncMethodsGenerationMode SyncMethods { get; set; } /// <summary> /// Get the predicate to determine of the http operation status code indicates failure /// </summary> public string FailureStatusCodePredicate { get { if (Responses.Any()) { List<string> predicates = new List<string>(); foreach (var responseStatus in Responses.Keys) { predicates.Add(string.Format(CultureInfo.InvariantCulture, "(int)_statusCode != {0}", GetStatusCodeReference(responseStatus))); } return string.Join(" && ", predicates); } return "!_httpResponse.IsSuccessStatusCode"; } } /// <summary> /// Generate the method parameter declaration for async methods and extensions /// </summary> public virtual string GetAsyncMethodParameterDeclaration() { return this.GetAsyncMethodParameterDeclaration(false); } /// <summary> /// Generate the method parameter declaration for sync methods and extensions /// </summary> /// <param name="addCustomHeaderParameters">If true add the customHeader to the parameters</param> /// <returns>Generated string of parameters</returns> public virtual string GetSyncMethodParameterDeclaration(bool addCustomHeaderParameters) { List<string> declarations = new List<string>(); foreach (var parameter in LocalParameters) { string format = (parameter.IsRequired ? "{0} {1}" : "{0} {1} = {2}"); string defaultValue = $"default({parameter.ModelTypeName})"; if (!string.IsNullOrEmpty(parameter.DefaultValue) && parameter.ModelType is PrimaryType) { defaultValue = parameter.DefaultValue; } declarations.Add(string.Format(CultureInfo.InvariantCulture, format, parameter.ModelTypeName, parameter.Name, defaultValue)); } if (addCustomHeaderParameters) { declarations.Add("System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null"); } return string.Join(", ", declarations); } /// <summary> /// Generate the method parameter declaration for async methods and extensions /// </summary> /// <param name="addCustomHeaderParameters">If true add the customHeader to the parameters</param> /// <returns>Generated string of parameters</returns> public virtual string GetAsyncMethodParameterDeclaration(bool addCustomHeaderParameters) { var declarations = this.GetSyncMethodParameterDeclaration(addCustomHeaderParameters); if (!string.IsNullOrEmpty(declarations)) { declarations += ", "; } declarations += "System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)"; return declarations; } /// <summary> /// Arguments for invoking the method from a synchronous extension method /// </summary> public string SyncMethodInvocationArgs => string.Join(", ", LocalParameters.Select(each => each.Name)); /// <summary> /// Get the invocation args for an invocation with an async method /// </summary> public string GetAsyncMethodInvocationArgs(string customHeaderReference, string cancellationTokenReference = "cancellationToken") => string.Join(", ", LocalParameters.Select(each => (string)each.Name).Concat(new[] { customHeaderReference, cancellationTokenReference })); /// <summary> /// Get the parameters that are actually method parameters in the order they appear in the method signature /// exclude global parameters /// </summary> [JsonIgnore] public IEnumerable<ParameterCs> LocalParameters { get { return Parameters.Where(parameter => parameter != null && !parameter.IsClientProperty && !string.IsNullOrWhiteSpace(parameter.Name) && !parameter.IsConstant) .OrderBy(item => !item.IsRequired).Cast<ParameterCs>(); } } /// <summary> /// Get the return type name for the underlying interface method /// </summary> public virtual string OperationResponseReturnTypeString { get { if (ReturnType.Body != null && ReturnType.Headers != null) { return $"Microsoft.Rest.HttpOperationResponse<{ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head)},{ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head)}>"; } if (ReturnType.Body != null) { return $"Microsoft.Rest.HttpOperationResponse<{ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head)}>"; } if (ReturnType.Headers != null) { return $"Microsoft.Rest.HttpOperationHeaderResponse<{ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head)}>"; } return "Microsoft.Rest.HttpOperationResponse"; } } /// <summary> /// Get the return type for the async extension method /// </summary> public virtual string TaskExtensionReturnTypeString { get { if (ReturnType.Body != null) { return string.Format(CultureInfo.InvariantCulture, "System.Threading.Tasks.Task<{0}>", ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head)); } else if (ReturnType.Headers != null) { return string.Format(CultureInfo.InvariantCulture, "System.Threading.Tasks.Task<{0}>", ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head)); } else { return "System.Threading.Tasks.Task"; } } } /// <summary> /// Get the type for operation exception /// </summary> public virtual string OperationExceptionTypeString { get { if (this.DefaultResponse.Body is CompositeType) { CompositeType type = this.DefaultResponse.Body as CompositeType; if (type.Extensions.ContainsKey(SwaggerExtensions.NameOverrideExtension)) { var ext = type.Extensions[SwaggerExtensions.NameOverrideExtension] as Newtonsoft.Json.Linq.JContainer; if (ext != null && ext["name"] != null) { return ext["name"].ToString(); } } return type.Name + "Exception"; } else { return "Microsoft.Rest.HttpOperationException"; } } } /// <summary> /// Get the expression for exception initialization with message. /// </summary> public virtual string InitializeExceptionWithMessage { get { return string.Empty; } } /// <summary> /// Get the expression for exception initialization with message. /// </summary> public virtual string InitializeException { get { return string.Empty; } } /// <summary> /// Gets the expression for response body initialization. /// </summary> public virtual string InitializeResponseBody { get { return string.Empty; } } /// <summary> /// Gets the expression for default header setting. /// </summary> public virtual string SetDefaultHeaders { get { return string.Empty; } } /// <summary> /// Get the type name for the method's return type /// </summary> public virtual string ReturnTypeString { get { if (ReturnType.Body != null) { return ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head); } if (ReturnType.Headers != null) { return ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head); } else { return "void"; } } } /// <summary> /// Get the method's request body (or null if there is no request body) /// </summary> [JsonIgnore] public ParameterCs RequestBody => Body as ParameterCs; /// <summary> /// Generate a reference to the ServiceClient /// </summary> [JsonIgnore] public string ClientReference => Group.IsNullOrEmpty() ? "this" : "this.Client"; /// <summary> /// Returns serialization settings reference. /// </summary> /// <param name="serializationType"></param> /// <returns></returns> public string GetSerializationSettingsReference(IModelType serializationType) { if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.Date)) { return "new Microsoft.Rest.Serialization.DateJsonConverter()"; } else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { return "new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()"; } else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.Base64Url)) { return "new Microsoft.Rest.Serialization.Base64UrlJsonConverter()"; } else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.UnixTime)) { return "new Microsoft.Rest.Serialization.UnixTimeJsonConverter()"; } return ClientReference + ".SerializationSettings"; } /// <summary> /// Returns deserialization settings reference. /// </summary> /// <param name="deserializationType"></param> /// <returns></returns> public string GetDeserializationSettingsReference(IModelType deserializationType) { if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Date)) { return "new Microsoft.Rest.Serialization.DateJsonConverter()"; } else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Base64Url)) { return "new Microsoft.Rest.Serialization.Base64UrlJsonConverter()"; } else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.UnixTime)) { return "new Microsoft.Rest.Serialization.UnixTimeJsonConverter()"; } return ClientReference + ".DeserializationSettings"; } public string GetExtensionParameters(string methodParameters) { string operationsParameter = "this I" + MethodGroup.TypeName + " operations"; return string.IsNullOrWhiteSpace(methodParameters) ? operationsParameter : operationsParameter + ", " + methodParameters; } public static string GetStatusCodeReference(HttpStatusCode code) { return ((int)code).ToString(CultureInfo.InvariantCulture); } /// <summary> /// Generate code to build the URL from a url expression and method parameters /// </summary> /// <param name="variableName">The variable to store the url in.</param> /// <returns></returns> public virtual string BuildUrl(string variableName) { var builder = new IndentedStringBuilder(); foreach (var pathParameter in this.LogicalParameters.Where(p => p.Location == ParameterLocation.Path)) { string replaceString = "{0} = {0}.Replace(\"{{{1}}}\", System.Uri.EscapeDataString({2}));"; if (pathParameter.SkipUrlEncoding()) { replaceString = "{0} = {0}.Replace(\"{{{1}}}\", {2});"; } var urlPathName = pathParameter.SerializedName; if (pathParameter.ModelType is SequenceType) { builder.AppendLine(replaceString, variableName, urlPathName, pathParameter.GetFormattedReferenceValue(ClientReference)); } else { builder.AppendLine(replaceString, variableName, urlPathName, pathParameter.ModelType.ToString(ClientReference, pathParameter.Name)); } } if (this.LogicalParameters.Any(p => p.Location == ParameterLocation.Query)) { builder.AppendLine("System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();"); foreach (var queryParameter in this.LogicalParameters.Where(p => p.Location == ParameterLocation.Query)) { var replaceString = "_queryParameters.Add(string.Format(\"{0}={{0}}\", System.Uri.EscapeDataString({1})));"; if ((queryParameter as ParameterCs).IsNullable()) { builder.AppendLine("if ({0} != null)", queryParameter.Name) .AppendLine("{").Indent(); } if (queryParameter.SkipUrlEncoding()) { replaceString = "_queryParameters.Add(string.Format(\"{0}={{0}}\", {1}));"; } if (queryParameter.CollectionFormat == CollectionFormat.Multi) { builder.AppendLine("if ({0}.Count == 0)", queryParameter.Name) .AppendLine("{").Indent() .AppendLine(replaceString, queryParameter.SerializedName, "string.Empty").Outdent() .AppendLine("}") .AppendLine("else") .AppendLine("{").Indent() .AppendLine("foreach (var _item in {0})", queryParameter.Name) .AppendLine("{").Indent() .AppendLine(replaceString, queryParameter.SerializedName, "_item ?? string.Empty").Outdent() .AppendLine("}").Outdent() .AppendLine("}").Outdent(); } else { builder.AppendLine(replaceString, queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue(ClientReference)); } if ((queryParameter as ParameterCs).IsNullable()) { builder.Outdent() .AppendLine("}"); } } builder.AppendLine("if (_queryParameters.Count > 0)") .AppendLine("{").Indent(); if (this.Extensions.ContainsKey("nextLinkMethod") && (bool)this.Extensions["nextLinkMethod"]) { builder.AppendLine("{0} += ({0}.Contains(\"?\") ? \"&\" : \"?\") + string.Join(\"&\", _queryParameters);", variableName); } else { builder.AppendLine("{0} += \"?\" + string.Join(\"&\", _queryParameters);", variableName); } builder.Outdent().AppendLine("}"); } return builder.ToString(); } /// <summary> /// Generates input mapping code block. /// </summary> /// <returns></returns> public virtual string BuildInputMappings() { var builder = new IndentedStringBuilder(); foreach (var transformation in InputParameterTransformation) { var compositeOutputParameter = transformation.OutputParameter.ModelType as CompositeType; if (transformation.OutputParameter.IsRequired && compositeOutputParameter != null) { builder.AppendLine("{0} {1} = new {0}();", transformation.OutputParameter.ModelTypeName, transformation.OutputParameter.Name); } else { builder.AppendLine("{0} {1} = default({0});", transformation.OutputParameter.ModelTypeName, transformation.OutputParameter.Name); } var nullCheck = BuildNullCheckExpression(transformation); if (!string.IsNullOrEmpty(nullCheck)) { builder.AppendLine("if ({0})", nullCheck) .AppendLine("{").Indent(); } if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) && compositeOutputParameter != null && !transformation.OutputParameter.IsRequired) { builder.AppendLine("{0} = new {1}();", transformation.OutputParameter.Name, transformation.OutputParameter.ModelType.Name); } foreach (var mapping in transformation.ParameterMappings) { builder.AppendLine("{0};", mapping.CreateCode(transformation.OutputParameter)); } if (!string.IsNullOrEmpty(nullCheck)) { builder.Outdent() .AppendLine("}"); } } return builder.ToString(); } private static string BuildNullCheckExpression(ParameterTransformation transformation) { if (transformation == null) { throw new ArgumentNullException("transformation"); } return string.Join(" || ", transformation.ParameterMappings .Where(m => m.InputParameter.IsNullable()) .Select(m => m.InputParameter.Name + " != null")); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Avalonia.Controls.Diagnostics; using Avalonia.Controls.Generators; using Avalonia.Controls.Platform; using Avalonia.Controls.Primitives; using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.Controls.Templates; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Interactivity; using Avalonia.Layout; using Avalonia.Styling; #nullable enable namespace Avalonia.Controls { /// <summary> /// A control context menu. /// </summary> public class ContextMenu : MenuBase, ISetterValue, IPopupHostProvider { /// <summary> /// Defines the <see cref="HorizontalOffset"/> property. /// </summary> public static readonly StyledProperty<double> HorizontalOffsetProperty = Popup.HorizontalOffsetProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="VerticalOffset"/> property. /// </summary> public static readonly StyledProperty<double> VerticalOffsetProperty = Popup.VerticalOffsetProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementAnchor"/> property. /// </summary> public static readonly StyledProperty<PopupAnchor> PlacementAnchorProperty = Popup.PlacementAnchorProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementConstraintAdjustment"/> property. /// </summary> public static readonly StyledProperty<PopupPositionerConstraintAdjustment> PlacementConstraintAdjustmentProperty = Popup.PlacementConstraintAdjustmentProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementGravity"/> property. /// </summary> public static readonly StyledProperty<PopupGravity> PlacementGravityProperty = Popup.PlacementGravityProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementMode"/> property. /// </summary> public static readonly StyledProperty<PlacementMode> PlacementModeProperty = Popup.PlacementModeProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementRect"/> property. /// </summary> public static readonly StyledProperty<Rect?> PlacementRectProperty = AvaloniaProperty.Register<Popup, Rect?>(nameof(PlacementRect)); /// <summary> /// Defines the <see cref="WindowManagerAddShadowHint"/> property. /// </summary> public static readonly StyledProperty<bool> WindowManagerAddShadowHintProperty = Popup.WindowManagerAddShadowHintProperty.AddOwner<ContextMenu>(); /// <summary> /// Defines the <see cref="PlacementTarget"/> property. /// </summary> public static readonly StyledProperty<Control?> PlacementTargetProperty = Popup.PlacementTargetProperty.AddOwner<ContextMenu>(); private static readonly ITemplate<IPanel> DefaultPanel = new FuncTemplate<IPanel>(() => new StackPanel { Orientation = Orientation.Vertical }); private Popup? _popup; private List<Control>? _attachedControls; private IInputElement? _previousFocus; private Action<IPopupHost?>? _popupHostChangedHandler; /// <summary> /// Initializes a new instance of the <see cref="ContextMenu"/> class. /// </summary> public ContextMenu() : this(new DefaultMenuInteractionHandler(true)) { } /// <summary> /// Initializes a new instance of the <see cref="ContextMenu"/> class. /// </summary> /// <param name="interactionHandler">The menu interaction handler.</param> public ContextMenu(IMenuInteractionHandler interactionHandler) : base(interactionHandler) { } /// <summary> /// Initializes static members of the <see cref="ContextMenu"/> class. /// </summary> static ContextMenu() { ItemsPanelProperty.OverrideDefaultValue<ContextMenu>(DefaultPanel); PlacementModeProperty.OverrideDefaultValue<ContextMenu>(PlacementMode.Pointer); ContextMenuProperty.Changed.Subscribe(ContextMenuChanged); } /// <summary> /// Gets or sets the Horizontal offset of the context menu in relation to the <see cref="PlacementTarget"/>. /// </summary> public double HorizontalOffset { get { return GetValue(HorizontalOffsetProperty); } set { SetValue(HorizontalOffsetProperty, value); } } /// <summary> /// Gets or sets the Vertical offset of the context menu in relation to the <see cref="PlacementTarget"/>. /// </summary> public double VerticalOffset { get { return GetValue(VerticalOffsetProperty); } set { SetValue(VerticalOffsetProperty, value); } } /// <summary> /// Gets or sets the anchor point on the <see cref="PlacementRect"/> when <see cref="PlacementMode"/> /// is <see cref="PlacementMode.AnchorAndGravity"/>. /// </summary> public PopupAnchor PlacementAnchor { get { return GetValue(PlacementAnchorProperty); } set { SetValue(PlacementAnchorProperty, value); } } /// <summary> /// Gets or sets a value describing how the context menu position will be adjusted if the /// unadjusted position would result in the context menu being partly constrained. /// </summary> public PopupPositionerConstraintAdjustment PlacementConstraintAdjustment { get { return GetValue(PlacementConstraintAdjustmentProperty); } set { SetValue(PlacementConstraintAdjustmentProperty, value); } } /// <summary> /// Gets or sets a value which defines in what direction the context menu should open /// when <see cref="PlacementMode"/> is <see cref="PlacementMode.AnchorAndGravity"/>. /// </summary> public PopupGravity PlacementGravity { get { return GetValue(PlacementGravityProperty); } set { SetValue(PlacementGravityProperty, value); } } /// <summary> /// Gets or sets the placement mode of the context menu in relation to the<see cref="PlacementTarget"/>. /// </summary> public PlacementMode PlacementMode { get { return GetValue(PlacementModeProperty); } set { SetValue(PlacementModeProperty, value); } } public bool WindowManagerAddShadowHint { get { return GetValue(WindowManagerAddShadowHintProperty); } set { SetValue(WindowManagerAddShadowHintProperty, value); } } /// <summary> /// Gets or sets the the anchor rectangle within the parent that the context menu will be placed /// relative to when <see cref="PlacementMode"/> is <see cref="PlacementMode.AnchorAndGravity"/>. /// </summary> /// <remarks> /// The placement rect defines a rectangle relative to <see cref="PlacementTarget"/> around /// which the popup will be opened, with <see cref="PlacementAnchor"/> determining which edge /// of the placement target is used. /// /// If unset, the anchor rectangle will be the bounds of the <see cref="PlacementTarget"/>. /// </remarks> public Rect? PlacementRect { get { return GetValue(PlacementRectProperty); } set { SetValue(PlacementRectProperty, value); } } /// <summary> /// Gets or sets the control that is used to determine the popup's position. /// </summary> public Control? PlacementTarget { get { return GetValue(PlacementTargetProperty); } set { SetValue(PlacementTargetProperty, value); } } /// <summary> /// Occurs when the value of the /// <see cref="P:Avalonia.Controls.ContextMenu.IsOpen" /> /// property is changing from false to true. /// </summary> public event CancelEventHandler? ContextMenuOpening; /// <summary> /// Occurs when the value of the /// <see cref="P:Avalonia.Controls.ContextMenu.IsOpen" /> /// property is changing from true to false. /// </summary> public event CancelEventHandler? ContextMenuClosing; /// <summary> /// Called when the <see cref="Control.ContextMenu"/> property changes on a control. /// </summary> /// <param name="e">The event args.</param> private static void ContextMenuChanged(AvaloniaPropertyChangedEventArgs e) { var control = (Control)e.Sender; if (e.OldValue is ContextMenu oldMenu) { control.ContextRequested -= ControlContextRequested; control.DetachedFromVisualTree -= ControlDetachedFromVisualTree; oldMenu._attachedControls?.Remove(control); ((ISetLogicalParent?)oldMenu._popup)?.SetParent(null); } if (e.NewValue is ContextMenu newMenu) { newMenu._attachedControls ??= new List<Control>(); newMenu._attachedControls.Add(control); control.ContextRequested += ControlContextRequested; control.DetachedFromVisualTree += ControlDetachedFromVisualTree; } } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); if (change.Property == WindowManagerAddShadowHintProperty && _popup != null) { _popup.WindowManagerAddShadowHint = change.NewValue.GetValueOrDefault<bool>(); } } /// <summary> /// Opens the menu. /// </summary> public override void Open() => Open(null); /// <summary> /// Opens a context menu on the specified control. /// </summary> /// <param name="control">The control.</param> public void Open(Control? control) { if (control is null && (_attachedControls is null || _attachedControls.Count == 0)) { throw new ArgumentNullException(nameof(control)); } if (control is object && _attachedControls is object && !_attachedControls.Contains(control)) { throw new ArgumentException( "Cannot show ContentMenu on a different control to the one it is attached to.", nameof(control)); } control ??= _attachedControls![0]; Open(control, PlacementTarget ?? control, false); } /// <summary> /// Closes the menu. /// </summary> public override void Close() { if (!IsOpen) { return; } if (_popup != null && _popup.IsVisible) { _popup.IsOpen = false; } } void ISetterValue.Initialize(ISetter setter) { // ContextMenu can be assigned to the ContextMenu property in a setter. This overrides // the behavior defined in Control which requires controls to be wrapped in a <template>. if (!(setter is Setter s && s.Property == ContextMenuProperty)) { throw new InvalidOperationException( "Cannot use a control as a Setter value. Wrap the control in a <Template>."); } } IPopupHost? IPopupHostProvider.PopupHost => _popup?.Host; event Action<IPopupHost?>? IPopupHostProvider.PopupHostChanged { add => _popupHostChangedHandler += value; remove => _popupHostChangedHandler -= value; } protected override IItemContainerGenerator CreateItemContainerGenerator() { return new MenuItemContainerGenerator(this); } private void Open(Control control, Control placementTarget, bool requestedByPointer) { if (IsOpen) { return; } if (_popup == null) { _popup = new Popup { IsLightDismissEnabled = true, OverlayDismissEventPassThrough = true, }; _popup.Opened += PopupOpened; _popup.Closed += PopupClosed; _popup.Closing += PopupClosing; _popup.KeyUp += PopupKeyUp; } if (_popup.Parent != control) { ((ISetLogicalParent)_popup).SetParent(null); ((ISetLogicalParent)_popup).SetParent(control); } _popup.PlacementMode = !requestedByPointer && PlacementMode == PlacementMode.Pointer ? PlacementMode.Bottom : PlacementMode; _popup.PlacementTarget = placementTarget; _popup.HorizontalOffset = HorizontalOffset; _popup.VerticalOffset = VerticalOffset; _popup.PlacementAnchor = PlacementAnchor; _popup.PlacementConstraintAdjustment = PlacementConstraintAdjustment; _popup.PlacementGravity = PlacementGravity; _popup.PlacementRect = PlacementRect; _popup.WindowManagerAddShadowHint = WindowManagerAddShadowHint; _popup.Child = this; IsOpen = true; _popup.IsOpen = true; RaiseEvent(new RoutedEventArgs { RoutedEvent = MenuOpenedEvent, Source = this, }); } private void PopupOpened(object sender, EventArgs e) { _previousFocus = FocusManager.Instance?.Current; Focus(); _popupHostChangedHandler?.Invoke(_popup!.Host); } private void PopupClosing(object sender, CancelEventArgs e) { e.Cancel = CancelClosing(); } private void PopupClosed(object sender, EventArgs e) { foreach (var i in LogicalChildren) { if (i is MenuItem menuItem) { menuItem.IsSubMenuOpen = false; } } SelectedIndex = -1; IsOpen = false; if (_attachedControls is null || _attachedControls.Count == 0) { ((ISetLogicalParent)_popup!).SetParent(null); } // HACK: Reset the focus when the popup is closed. We need to fix this so it's automatic. FocusManager.Instance?.Focus(_previousFocus); RaiseEvent(new RoutedEventArgs { RoutedEvent = MenuClosedEvent, Source = this, }); _popupHostChangedHandler?.Invoke(null); } private void PopupKeyUp(object sender, KeyEventArgs e) { if (IsOpen) { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); if (keymap.OpenContextMenu.Any(k => k.Matches(e)) && !CancelClosing()) { Close(); e.Handled = true; } } } private static void ControlContextRequested(object sender, ContextRequestedEventArgs e) { if (sender is Control control && control.ContextMenu is ContextMenu contextMenu && !e.Handled && !contextMenu.CancelOpening()) { var requestedByPointer = e.TryGetPosition(null, out _); contextMenu.Open(control, e.Source as Control ?? control, requestedByPointer); e.Handled = true; } } private static void ControlDetachedFromVisualTree(object sender, VisualTreeAttachmentEventArgs e) { if (sender is Control control && control.ContextMenu is ContextMenu contextMenu) { contextMenu.Close(); } } private bool CancelClosing() { var eventArgs = new CancelEventArgs(); ContextMenuClosing?.Invoke(this, eventArgs); return eventArgs.Cancel; } private bool CancelOpening() { var eventArgs = new CancelEventArgs(); ContextMenuOpening?.Invoke(this, eventArgs); return eventArgs.Cancel; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Timetable Labels Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class THTNDataSet : EduHubDataSet<THTN> { /// <inheritdoc /> public override string Name { get { return "THTN"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal THTNDataSet(EduHubContext Context) : base(Context) { Index_LW_DATE = new Lazy<NullDictionary<DateTime?, IReadOnlyList<THTN>>>(() => this.ToGroupedNullDictionary(i => i.LW_DATE)); Index_QKEY = new Lazy<Dictionary<string, IReadOnlyList<THTN>>>(() => this.ToGroupedDictionary(i => i.QKEY)); Index_TID = new Lazy<Dictionary<int, THTN>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="THTN" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="THTN" /> fields for each CSV column header</returns> internal override Action<THTN, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<THTN, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "QKEY": mapper[i] = (e, v) => e.QKEY = v; break; case "LABEL_NUMBER": mapper[i] = (e, v) => e.LABEL_NUMBER = v == null ? (short?)null : short.Parse(v); break; case "LABEL_TYPE": mapper[i] = (e, v) => e.LABEL_TYPE = v; break; case "LABEL_NAME": mapper[i] = (e, v) => e.LABEL_NAME = v; break; case "LABEL_COLOUR": mapper[i] = (e, v) => e.LABEL_COLOUR = v == null ? (int?)null : int.Parse(v); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="THTN" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="THTN" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="THTN" /> entities</param> /// <returns>A merged <see cref="IEnumerable{THTN}"/> of entities</returns> internal override IEnumerable<THTN> ApplyDeltaEntities(IEnumerable<THTN> Entities, List<THTN> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.QKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.QKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<DateTime?, IReadOnlyList<THTN>>> Index_LW_DATE; private Lazy<Dictionary<string, IReadOnlyList<THTN>>> Index_QKEY; private Lazy<Dictionary<int, THTN>> Index_TID; #endregion #region Index Methods /// <summary> /// Find THTN by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find THTN</param> /// <returns>List of related THTN entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<THTN> FindByLW_DATE(DateTime? LW_DATE) { return Index_LW_DATE.Value[LW_DATE]; } /// <summary> /// Attempt to find THTN by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find THTN</param> /// <param name="Value">List of related THTN entities</param> /// <returns>True if the list of related THTN entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByLW_DATE(DateTime? LW_DATE, out IReadOnlyList<THTN> Value) { return Index_LW_DATE.Value.TryGetValue(LW_DATE, out Value); } /// <summary> /// Attempt to find THTN by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find THTN</param> /// <returns>List of related THTN entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<THTN> TryFindByLW_DATE(DateTime? LW_DATE) { IReadOnlyList<THTN> value; if (Index_LW_DATE.Value.TryGetValue(LW_DATE, out value)) { return value; } else { return null; } } /// <summary> /// Find THTN by QKEY field /// </summary> /// <param name="QKEY">QKEY value used to find THTN</param> /// <returns>List of related THTN entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<THTN> FindByQKEY(string QKEY) { return Index_QKEY.Value[QKEY]; } /// <summary> /// Attempt to find THTN by QKEY field /// </summary> /// <param name="QKEY">QKEY value used to find THTN</param> /// <param name="Value">List of related THTN entities</param> /// <returns>True if the list of related THTN entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByQKEY(string QKEY, out IReadOnlyList<THTN> Value) { return Index_QKEY.Value.TryGetValue(QKEY, out Value); } /// <summary> /// Attempt to find THTN by QKEY field /// </summary> /// <param name="QKEY">QKEY value used to find THTN</param> /// <returns>List of related THTN entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<THTN> TryFindByQKEY(string QKEY) { IReadOnlyList<THTN> value; if (Index_QKEY.Value.TryGetValue(QKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find THTN by TID field /// </summary> /// <param name="TID">TID value used to find THTN</param> /// <returns>Related THTN entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public THTN FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find THTN by TID field /// </summary> /// <param name="TID">TID value used to find THTN</param> /// <param name="Value">Related THTN entity</param> /// <returns>True if the related THTN entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out THTN Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find THTN by TID field /// </summary> /// <param name="TID">TID value used to find THTN</param> /// <returns>Related THTN entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public THTN TryFindByTID(int TID) { THTN value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a THTN table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[THTN]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[THTN]( [TID] int IDENTITY NOT NULL, [QKEY] varchar(8) NOT NULL, [LABEL_NUMBER] smallint NULL, [LABEL_TYPE] varchar(1) NULL, [LABEL_NAME] varchar(20) NULL, [LABEL_COLOUR] int NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [THTN_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE NONCLUSTERED INDEX [THTN_Index_LW_DATE] ON [dbo].[THTN] ( [LW_DATE] ASC ); CREATE CLUSTERED INDEX [THTN_Index_QKEY] ON [dbo].[THTN] ( [QKEY] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTN]') AND name = N'THTN_Index_LW_DATE') ALTER INDEX [THTN_Index_LW_DATE] ON [dbo].[THTN] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTN]') AND name = N'THTN_Index_TID') ALTER INDEX [THTN_Index_TID] ON [dbo].[THTN] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTN]') AND name = N'THTN_Index_LW_DATE') ALTER INDEX [THTN_Index_LW_DATE] ON [dbo].[THTN] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTN]') AND name = N'THTN_Index_TID') ALTER INDEX [THTN_Index_TID] ON [dbo].[THTN] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="THTN"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="THTN"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<THTN> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[THTN] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the THTN data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the THTN data set</returns> public override EduHubDataSetDataReader<THTN> GetDataSetDataReader() { return new THTNDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the THTN data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the THTN data set</returns> public override EduHubDataSetDataReader<THTN> GetDataSetDataReader(List<THTN> Entities) { return new THTNDataReader(new EduHubDataSetLoadedReader<THTN>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class THTNDataReader : EduHubDataSetDataReader<THTN> { public THTNDataReader(IEduHubDataSetReader<THTN> Reader) : base (Reader) { } public override int FieldCount { get { return 9; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // QKEY return Current.QKEY; case 2: // LABEL_NUMBER return Current.LABEL_NUMBER; case 3: // LABEL_TYPE return Current.LABEL_TYPE; case 4: // LABEL_NAME return Current.LABEL_NAME; case 5: // LABEL_COLOUR return Current.LABEL_COLOUR; case 6: // LW_DATE return Current.LW_DATE; case 7: // LW_TIME return Current.LW_TIME; case 8: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // LABEL_NUMBER return Current.LABEL_NUMBER == null; case 3: // LABEL_TYPE return Current.LABEL_TYPE == null; case 4: // LABEL_NAME return Current.LABEL_NAME == null; case 5: // LABEL_COLOUR return Current.LABEL_COLOUR == null; case 6: // LW_DATE return Current.LW_DATE == null; case 7: // LW_TIME return Current.LW_TIME == null; case 8: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // QKEY return "QKEY"; case 2: // LABEL_NUMBER return "LABEL_NUMBER"; case 3: // LABEL_TYPE return "LABEL_TYPE"; case 4: // LABEL_NAME return "LABEL_NAME"; case 5: // LABEL_COLOUR return "LABEL_COLOUR"; case 6: // LW_DATE return "LW_DATE"; case 7: // LW_TIME return "LW_TIME"; case 8: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "QKEY": return 1; case "LABEL_NUMBER": return 2; case "LABEL_TYPE": return 3; case "LABEL_NAME": return 4; case "LABEL_COLOUR": return 5; case "LW_DATE": return 6; case "LW_TIME": return 7; case "LW_USER": return 8; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
/* insert license info here */ using System; using System.Collections; namespace Business.Data.AutoAnalizador { /// <summary> /// Generated by MyGeneration using the NHibernate Object Mapping template /// </summary> [Serializable] public sealed class ProtocoloEnvio: Business.BaseDataAccess { #region Private Members private bool m_isChanged; private int m_idtempprotocoloenvio; private int m_idmuestra; private string m_numeroprotocolo; private string m_tipomuestra; private string m_iditem; private string m_paciente; private string m_anionacimiento; private string m_sexo; private string m_sectorsolicitante; private string m_medicosolicitante; private string m_urgente; private string m_equipo; #endregion #region Default ( Empty ) Class Constuctor /// <summary> /// default constructor /// </summary> public ProtocoloEnvio() { m_idtempprotocoloenvio = 0; m_idmuestra = 0; m_numeroprotocolo = String.Empty; m_tipomuestra = String.Empty; m_iditem = String.Empty; m_paciente = String.Empty; m_anionacimiento = String.Empty; m_sexo = String.Empty; m_sectorsolicitante = String.Empty; m_medicosolicitante = String.Empty; m_urgente = String.Empty; m_equipo = String.Empty; } #endregion // End of Default ( Empty ) Class Constuctor #region Required Fields Only Constructor /// <summary> /// required (not null) fields only constructor /// </summary> public ProtocoloEnvio( int idmuestra, string numeroprotocolo, string tipomuestra, string iditem, string paciente, string anionacimiento, string sexo, string sectorsolicitante, string medicosolicitante, string urgente, string equipo) : this() { m_idmuestra = idmuestra; m_numeroprotocolo = numeroprotocolo; m_tipomuestra = tipomuestra; m_iditem = iditem; m_paciente = paciente; m_anionacimiento = anionacimiento; m_sexo = sexo; m_sectorsolicitante = sectorsolicitante; m_medicosolicitante = medicosolicitante; m_urgente = urgente; m_equipo = equipo; } #endregion // End Required Fields Only Constructor #region Public Properties /// <summary> /// /// </summary> public int IdTempProtocoloEnvio { get { return m_idtempprotocoloenvio; } set { m_isChanged |= ( m_idtempprotocoloenvio != value ); m_idtempprotocoloenvio = value; } } /// <summary> /// /// </summary> /// public int IdMuestra { get { return m_idmuestra; } set { m_isChanged |= (m_idmuestra != value); m_idmuestra = value; } } public string NumeroProtocolo { get { return m_numeroprotocolo; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for NumeroProtocolo", value, "null"); if( value.Length > 50) throw new ArgumentOutOfRangeException("Invalid value for NumeroProtocolo", value, value.ToString()); m_isChanged |= (m_numeroprotocolo != value); m_numeroprotocolo = value; } } /// <summary> /// /// </summary> public string TipoMuestra { get { return m_tipomuestra; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for TipoMuestra", value, "null"); if( value.Length > 50) throw new ArgumentOutOfRangeException("Invalid value for TipoMuestra", value, value.ToString()); m_isChanged |= (m_tipomuestra != value); m_tipomuestra = value; } } /// <summary> /// /// </summary> public string Iditem { get { return m_iditem; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for Iditem", value, "null"); if( value.Length > 500) throw new ArgumentOutOfRangeException("Invalid value for Iditem", value, value.ToString()); m_isChanged |= (m_iditem != value); m_iditem = value; } } /// <summary> /// /// </summary> public string Paciente { get { return m_paciente; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for Paciente", value, "null"); if( value.Length > 200) throw new ArgumentOutOfRangeException("Invalid value for Paciente", value, value.ToString()); m_isChanged |= (m_paciente != value); m_paciente = value; } } /// <summary> /// /// </summary> public string AnioNacimiento { get { return m_anionacimiento; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for AnioNacimiento", value, "null"); if( value.Length > 8) throw new ArgumentOutOfRangeException("Invalid value for AnioNacimiento", value, value.ToString()); m_isChanged |= (m_anionacimiento != value); m_anionacimiento = value; } } /// <summary> /// /// </summary> public string Sexo { get { return m_sexo; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for Sexo", value, "null"); if( value.Length > 1) throw new ArgumentOutOfRangeException("Invalid value for Sexo", value, value.ToString()); m_isChanged |= (m_sexo != value); m_sexo = value; } } /// <summary> /// /// </summary> public string SectorSolicitante { get { return m_sectorsolicitante; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for SectorSolicitante", value, "null"); if( value.Length > 150) throw new ArgumentOutOfRangeException("Invalid value for SectorSolicitante", value, value.ToString()); m_isChanged |= (m_sectorsolicitante != value); m_sectorsolicitante = value; } } /// <summary> /// /// </summary> public string MedicoSolicitante { get { return m_medicosolicitante; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for MedicoSolicitante", value, "null"); if( value.Length > 150) throw new ArgumentOutOfRangeException("Invalid value for MedicoSolicitante", value, value.ToString()); m_isChanged |= (m_medicosolicitante != value); m_medicosolicitante = value; } } /// <summary> /// /// </summary> public string Urgente { get { return m_urgente; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for Urgente", value, "null"); if( value.Length > 50) throw new ArgumentOutOfRangeException("Invalid value for Urgente", value, value.ToString()); m_isChanged |= (m_urgente != value); m_urgente = value; } } public string Equipo { get { return m_equipo; } set { if (value == null) throw new ArgumentOutOfRangeException("Null value not allowed for Paciente", value, "null"); if (value.Length > 50) throw new ArgumentOutOfRangeException("Invalid value for Paciente", value, value.ToString()); m_isChanged |= (m_equipo != value); m_equipo = 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 Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Reflection; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A class that represents a script that you can run. /// /// Create a script using a language specific script class such as CSharpScript or VisualBasicScript. /// </summary> public abstract class Script { internal readonly ScriptCompiler Compiler; internal readonly ScriptBuilder Builder; private Compilation _lazyCompilation; internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) { Debug.Assert(code != null); Debug.Assert(options != null); Debug.Assert(compiler != null); Debug.Assert(builder != null); Compiler = compiler; Builder = builder; Previous = previousOpt; Code = code; Options = options; GlobalsType = globalsTypeOpt; } internal static Script<T> CreateInitialScript<T>(ScriptCompiler compiler, string codeOpt, ScriptOptions optionsOpt, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoaderOpt) { return new Script<T>(compiler, new ScriptBuilder(assemblyLoaderOpt ?? new InteractiveAssemblyLoader()), codeOpt ?? "", optionsOpt ?? ScriptOptions.Default, globalsTypeOpt, previousOpt: null); } /// <summary> /// A script that will run first when this script is run. /// Any declarations made in the previous script can be referenced in this script. /// The end state from running this script includes all declarations made by both scripts. /// </summary> public Script Previous { get; } /// <summary> /// The options used by this script. /// </summary> public ScriptOptions Options { get; } /// <summary> /// The source code of the script. /// </summary> public string Code { get; } /// <summary> /// The type of an object whose members can be accessed by the script as global variables. /// </summary> public Type GlobalsType { get; } /// <summary> /// The expected return type of the script. /// </summary> public abstract Type ReturnType { get; } /// <summary> /// Creates a new version of this script with the specified options. /// </summary> public Script WithOptions(ScriptOptions options) => WithOptionsInternal(options); internal abstract Script WithOptionsInternal(ScriptOptions options); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<object> ContinueWith(string code, ScriptOptions options = null) => ContinueWith<object>(code, options); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<TResult> ContinueWith<TResult>(string code, ScriptOptions options = null) => new Script<TResult>(Compiler, Builder, code ?? "", options ?? InheritOptions(Options), GlobalsType, this); private static ScriptOptions InheritOptions(ScriptOptions previous) { // don't inherit references or imports, they have already been applied: return previous. WithReferences(ImmutableArray<MetadataReference>.Empty). WithImports(ImmutableArray<string>.Empty); } /// <summary> /// Get's the <see cref="Compilation"/> that represents the semantics of the script. /// </summary> public Compilation GetCompilation() { if (_lazyCompilation == null) { var compilation = Compiler.CreateSubmission(this); Interlocked.CompareExchange(ref _lazyCompilation, compilation, null); } return _lazyCompilation; } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> internal Task<object> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonEvaluateAsync(globals, cancellationToken); internal abstract Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonRunAsync(globals, cancellationToken); internal abstract Task<ScriptState> CommonRunAsync(object globals, CancellationToken cancellationToken); /// <summary> /// Continue script execution from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> internal Task<ScriptState> ContinueAsync(ScriptState previousState, CancellationToken cancellationToken = default(CancellationToken)) => CommonContinueAsync(previousState, cancellationToken); internal abstract Task<ScriptState> CommonContinueAsync(ScriptState previousState, CancellationToken cancellationToken); /// <summary> /// Forces the script through the compilation step. /// If not called directly, the compilation step will occur on the first call to Run. /// </summary> public ImmutableArray<Diagnostic> Compile(CancellationToken cancellationToken = default(CancellationToken)) => CommonCompile(cancellationToken); internal abstract ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken); internal abstract Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken); // Apply recursive alias <host> to the host assembly reference, so that we hide its namespaces and global types behind it. internal static readonly MetadataReferenceProperties HostAssemblyReferenceProperties = MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("<host>")).WithRecursiveAliases(true); /// <summary> /// Gets the references that need to be assigned to the compilation. /// This can be different than the list of references defined by the <see cref="ScriptOptions"/> instance. /// </summary> internal ImmutableArray<MetadataReference> GetReferencesForCompilation( CommonMessageProvider messageProvider, DiagnosticBag diagnostics, MetadataReference languageRuntimeReferenceOpt = null) { var resolver = Options.MetadataResolver; var references = ArrayBuilder<MetadataReference>.GetInstance(); try { if (Previous == null) { var corLib = MetadataReference.CreateFromAssemblyInternal(typeof(object).GetTypeInfo().Assembly); references.Add(corLib); if (GlobalsType != null) { var globalsAssembly = GlobalsType.GetTypeInfo().Assembly; // If the assembly doesn't have metadata (it's an in-memory or dynamic assembly), // the host has to add reference to the metadata where globals type is located explicitly. if (MetadataReference.HasMetadata(globalsAssembly)) { references.Add(MetadataReference.CreateFromAssemblyInternal(globalsAssembly, HostAssemblyReferenceProperties)); } } if (languageRuntimeReferenceOpt != null) { references.Add(languageRuntimeReferenceOpt); } } // add new references: foreach (var reference in Options.MetadataReferences) { var unresolved = reference as UnresolvedMetadataReference; if (unresolved != null) { var resolved = resolver.ResolveReference(unresolved.Reference, null, unresolved.Properties); if (resolved.IsDefault) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MetadataFileNotFound, Location.None, unresolved.Reference)); } else { references.AddRange(resolved); } } else { references.Add(reference); } } return references.ToImmutable(); } finally { references.Free(); } } // TODO: remove internal bool HasReturnValue() { return GetCompilation().HasSubmissionResult(); } } public sealed class Script<T> : Script { private ImmutableArray<Func<object[], Task>> _lazyPrecedingExecutors; private Func<object[], Task<T>> _lazyExecutor; internal Script(ScriptCompiler compiler, ScriptBuilder builder, string code, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) : base(compiler, builder, code, options, globalsTypeOpt, previousOpt) { } public override Type ReturnType => typeof(T); public new Script<T> WithOptions(ScriptOptions options) { return (options == Options) ? this : new Script<T>(Compiler, Builder, Code, options, GlobalsType, Previous); } internal override Script WithOptionsInternal(ScriptOptions options) => WithOptions(options); internal override ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken) { // TODO: avoid throwing exception, report all diagnostics https://github.com/dotnet/roslyn/issues/5949 try { GetPrecedingExecutors(cancellationToken); GetExecutor(cancellationToken); return ImmutableArray.CreateRange(GetCompilation().GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Warning)); } catch (CompilationErrorException e) { return ImmutableArray.CreateRange(e.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning)); } } internal override Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken) => GetExecutor(cancellationToken); internal override Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken) => EvaluateAsync(globals, cancellationToken).CastAsync<T, object>(); internal override Task<ScriptState> CommonRunAsync(object globals, CancellationToken cancellationToken) => RunAsync(globals, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); internal override Task<ScriptState> CommonContinueAsync(ScriptState previousState, CancellationToken cancellationToken) => ContinueAsync(previousState, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private Func<object[], Task<T>> GetExecutor(CancellationToken cancellationToken) { if (_lazyExecutor == null) { Interlocked.CompareExchange(ref _lazyExecutor, Builder.CreateExecutor<T>(Compiler, GetCompilation(), cancellationToken), null); } return _lazyExecutor; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> GetPrecedingExecutors(CancellationToken cancellationToken) { if (_lazyPrecedingExecutors.IsDefault) { var preceding = TryGetPrecedingExecutors(null, cancellationToken); Debug.Assert(!preceding.IsDefault); InterlockedOperations.Initialize(ref _lazyPrecedingExecutors, preceding); } return _lazyPrecedingExecutors; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> TryGetPrecedingExecutors(Script lastExecutedScriptInChainOpt, CancellationToken cancellationToken) { Script script = Previous; if (script == lastExecutedScriptInChainOpt) { return ImmutableArray<Func<object[], Task>>.Empty; } var scriptsReversed = ArrayBuilder<Script>.GetInstance(); while (script != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Add(script); script = script.Previous; } if (lastExecutedScriptInChainOpt != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Free(); return default(ImmutableArray<Func<object[], Task>>); } var executors = ArrayBuilder<Func<object[], Task>>.GetInstance(scriptsReversed.Count); // We need to build executors in the order in which they are chained, // so that assemblies created for the submissions are loaded in the correct order. for (int i = scriptsReversed.Count - 1; i >= 0; i--) { executors.Add(scriptsReversed[i].CommonGetExecutor(cancellationToken)); } return executors.ToImmutableAndFree(); } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> internal new Task<T> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => RunAsync(globals, cancellationToken).GetEvaluationResultAsync(); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="CompilationErrorException">Compilation has errors.</exception> /// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match <see cref="Script.GlobalsType"/>.</exception> public new Task<ScriptState<T>> RunAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor construction may throw; // do so synchronously so that the exception is not wrapped in the task. ValidateGlobals(globals, GlobalsType); var executionState = ScriptExecutionState.Create(globals); var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); return RunSubmissionsAsync(executionState, precedingExecutors, currentExecutor, cancellationToken); } /// <summary> /// Creates a delegate that will run this script from the beginning when invoked. /// </summary> /// <remarks> /// The delegate doesn't hold on this script or its compilation. /// </remarks> public ScriptRunner<T> CreateDelegate(CancellationToken cancellationToken = default(CancellationToken)) { var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); var globalsType = GlobalsType; return (globals, token) => { ValidateGlobals(globals, globalsType); return ScriptExecutionState.Create(globals).RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, token); }; } /// <summary> /// Continue script execution from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="ArgumentNullException"><paramref name="previousState"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="previousState"/> is not a previous execution state of this script.</exception> internal new Task<ScriptState<T>> ContinueAsync(ScriptState previousState, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor construction may throw; // do so synchronously so that the exception is not wrapped in the task. if (previousState == null) { throw new ArgumentNullException(nameof(previousState)); } if (previousState.Script == this) { // this state is already the output of running this script. return Task.FromResult((ScriptState<T>)previousState); } var precedingExecutors = TryGetPrecedingExecutors(previousState.Script, cancellationToken); if (precedingExecutors.IsDefault) { throw new ArgumentException(ScriptingResources.StartingStateIncompatible, nameof(previousState)); } var currentExecutor = GetExecutor(cancellationToken); ScriptExecutionState newExecutionState = previousState.ExecutionState.FreezeAndClone(); return RunSubmissionsAsync(newExecutionState, precedingExecutors, currentExecutor, cancellationToken); } private async Task<ScriptState<T>> RunSubmissionsAsync(ScriptExecutionState executionState, ImmutableArray<Func<object[], Task>> precedingExecutors, Func<object[], Task> currentExecutor, CancellationToken cancellationToken) { var result = await executionState.RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, cancellationToken).ConfigureAwait(continueOnCapturedContext: true); return new ScriptState<T>(executionState, result, this); } private static void ValidateGlobals(object globals, Type globalsType) { if (globalsType != null) { if (globals == null) { throw new ArgumentException(ScriptingResources.ScriptRequiresGlobalVariables, nameof(globals)); } var runtimeType = globals.GetType().GetTypeInfo(); var globalsTypeInfo = globalsType.GetTypeInfo(); if (!globalsTypeInfo.IsAssignableFrom(runtimeType)) { throw new ArgumentException(string.Format(ScriptingResources.GlobalsNotAssignable, runtimeType, globalsTypeInfo), nameof(globals)); } } else if (globals != null) { throw new ArgumentException(ScriptingResources.GlobalVariablesWithoutGlobalType, nameof(globals)); } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using Microsoft.PythonTools.Analysis.Values; using Microsoft.PythonTools.Parsing.Ast; namespace Microsoft.PythonTools.Analysis.Analyzer { internal class DDG : PythonWalker { internal AnalysisUnit _unit; internal ExpressionEvaluator _eval; private SuiteStatement _curSuite; public readonly HashSet<ProjectEntry> AnalyzedEntries = new HashSet<ProjectEntry>(); public void Analyze(Deque<AnalysisUnit> queue, CancellationToken cancel, Action<int> reportQueueSize = null, int reportQueueInterval = 1) { if (cancel.IsCancellationRequested) { return; } try { // Including a marker at the end of the queue allows us to see in // the log how frequently the queue empties. var endOfQueueMarker = new AnalysisUnit(null, null); int queueCountAtStart = queue.Count; int reportInterval = reportQueueInterval - 1; if (queueCountAtStart > 0) { queue.Append(endOfQueueMarker); } while (queue.Count > 0 && !cancel.IsCancellationRequested) { _unit = queue.PopLeft(); if (_unit == endOfQueueMarker) { AnalysisLog.EndOfQueue(queueCountAtStart, queue.Count); if (reportInterval < 0 && reportQueueSize != null) { reportQueueSize(queue.Count); } queueCountAtStart = queue.Count; if (queueCountAtStart > 0) { queue.Append(endOfQueueMarker); } continue; } AnalysisLog.Dequeue(queue, _unit); if (reportInterval == 0 && reportQueueSize != null) { reportQueueSize(queue.Count); reportInterval = reportQueueInterval - 1; } else if (reportInterval > 0) { reportInterval -= 1; } _unit.IsInQueue = false; SetCurrentUnit(_unit); AnalyzedEntries.Add(_unit.ProjectEntry); _unit.Analyze(this, cancel); } if (reportQueueSize != null) { reportQueueSize(0); } if (cancel.IsCancellationRequested) { AnalysisLog.Cancelled(queue); } } finally { AnalysisLog.Flush(); AnalyzedEntries.Remove(null); } } public void SetCurrentUnit(AnalysisUnit unit) { _eval = new ExpressionEvaluator(unit); _unit = unit; } public InterpreterScope Scope { get { return _eval.Scope; } set { _eval.Scope = value; } } public ModuleInfo GlobalScope { get { return _unit.DeclaringModule; } } public PythonAnalyzer ProjectState { get { return _unit.ProjectState; } } public override bool Walk(PythonAst node) { ModuleReference existingRef; Debug.Assert(node == _unit.Ast); if (!ProjectState.Modules.TryImport(_unit.DeclaringModule.Name, out existingRef)) { // publish our module ref now so that we don't collect dependencies as we'll be fully processed if (existingRef == null) { ProjectState.Modules[_unit.DeclaringModule.Name] = new ModuleReference(_unit.DeclaringModule); } else { existingRef.Module = _unit.DeclaringModule; } } return base.Walk(node); } /// <summary> /// Gets the function which we are processing code for currently or /// null if we are not inside of a function body. /// </summary> public FunctionScope CurrentFunction { get { return CurrentContainer<FunctionScope>(); } } public ClassScope CurrentClass { get { return CurrentContainer<ClassScope>(); } } private T CurrentContainer<T>() where T : InterpreterScope { return Scope.EnumerateTowardsGlobal.OfType<T>().FirstOrDefault(); } public override bool Walk(AssignmentStatement node) { var valueType = _eval.Evaluate(node.Right); // For self assignments (e.g. "fob = fob"), include values from // outer scopes, otherwise such assignments will always be unknown // because we use the unassigned variable for the RHS. var ne = node.Right as NameExpression; InterpreterScope oldScope; if (ne != null && (oldScope = _eval.Scope).OuterScope != null && node.Left.OfType<NameExpression>().Any(n => n.Name == ne.Name)) { try { _eval.Scope = _eval.Scope.OuterScope; valueType = valueType.Union(_eval.Evaluate(node.Right)); } finally { _eval.Scope = oldScope; } } foreach (var left in node.Left) { _eval.AssignTo(node, left, valueType); } return false; } public override bool Walk(AugmentedAssignStatement node) { var right = _eval.Evaluate(node.Right); foreach (var x in _eval.Evaluate(node.Left)) { x.AugmentAssign(node, _unit, right); } return false; } public override bool Walk(GlobalStatement node) { foreach (var name in node.Names) { GlobalScope.Scope.GetVariable(name, _unit, name.Name); } return false; } public override bool Walk(NonlocalStatement node) { if (Scope.OuterScope != null) { foreach (var name in node.Names) { Scope.OuterScope.GetVariable(name, _unit, name.Name); } } return false; } public override bool Walk(ClassDefinition node) { return false; } public override bool Walk(ExpressionStatement node) { _eval.Evaluate(node.Expression); return false; } public override bool Walk(ForStatement node) { if (node.List != null) { var list = _eval.Evaluate(node.List); _eval.AssignTo( node, node.Left, node.IsAsync ? list.GetAsyncEnumeratorTypes(node, _unit) : list.GetEnumeratorTypes(node, _unit) ); } if (node.Body != null) { node.Body.Walk(this); } if (node.Else != null) { node.Else.Walk(this); } return false; } private void WalkFromImportWorker(NameExpression node, IModule userMod, string impName, string newName) { var saveName = (newName == null) ? impName : newName; bool addRef = node.Name != "*"; var variable = Scope.CreateVariable(node, _unit, saveName, false); bool added = false; if (userMod != null) { added = variable.AddTypes(_unit, userMod.GetModuleMember(node, _unit, impName, addRef, Scope, saveName)); } if (addRef) { variable.AddAssignment(node, _unit); } if (added) { // anyone who read from the module will now need to get the new values GlobalScope.ModuleDefinition.EnqueueDependents(); } } public override bool Walk(FromImportStatement node) { IModule userMod = null; ModuleReference modRef; var modName = node.Root.MakeString(); if (TryImportModule(modName, node.ForceAbsolute, out modRef)) { modRef.AddReference(_unit.DeclaringModule); Debug.Assert(modRef.Module != null); userMod = modRef.Module; } var asNames = node.AsNames ?? node.Names; int len = Math.Min(node.Names.Count, asNames.Count); for (int i = 0; i < len; i++) { var nameNode = asNames[i] ?? node.Names[i]; var impName = node.Names[i].Name; var newName = asNames[i] != null ? asNames[i].Name : null; if (impName == null) { // incomplete import statement continue; } else if (impName == "*") { // Handle "import *" if (userMod != null) { foreach (var varName in userMod.GetModuleMemberNames(GlobalScope.InterpreterContext)) { if (!varName.StartsWith("_")) { WalkFromImportWorker(nameNode, userMod, varName, null); } } userMod.Imported(_unit); } } else { WalkFromImportWorker(nameNode, userMod, impName, newName); } } return true; } private bool TryImportModule(string modName, bool forceAbsolute, out ModuleReference moduleRef) { if (ProjectState.Limits.CrossModule != null && ProjectState.ModulesByFilename.Count > ProjectState.Limits.CrossModule) { // too many modules loaded, disable cross module analysis by blocking // scripts from seeing other modules. moduleRef = null; return false; } foreach (var name in PythonAnalyzer.ResolvePotentialModuleNames(_unit.ProjectEntry, modName, forceAbsolute)) { foreach (var part in ModulePath.GetParents(name, includeFullName: false)) { ModuleReference parentRef; if (ProjectState.Modules.TryImport(part, out parentRef)) { var bi = parentRef.Module as BuiltinModule; if (bi == null) { break; } bi.Imported(_unit); } } if (ProjectState.Modules.TryImport(name, out moduleRef)) { return true; } } _unit.DeclaringModule.AddUnresolvedModule(modName, forceAbsolute); moduleRef = null; return false; } internal List<AnalysisValue> LookupBaseMethods(string name, IEnumerable<IAnalysisSet> bases, Node node, AnalysisUnit unit) { var result = new List<AnalysisValue>(); foreach (var b in bases) { foreach (var curType in b) { BuiltinClassInfo klass = curType as BuiltinClassInfo; if (klass != null) { var value = klass.GetMember(node, unit, name); if (value != null) { result.AddRange(value); } } } } return result; } public override bool Walk(FunctionDefinition node) { InterpreterScope funcScope; if (_unit.Scope.TryGetNodeScope(node, out funcScope)) { var function = ((FunctionScope)funcScope).Function; var analysisUnit = (FunctionAnalysisUnit)((FunctionScope)funcScope).Function.AnalysisUnit; var curClass = Scope as ClassScope; if (curClass != null) { var bases = LookupBaseMethods( analysisUnit.Ast.Name, curClass.Class.Mro, analysisUnit.Ast, analysisUnit ); foreach (var method in bases.OfType<BuiltinMethodInfo>()) { foreach (var overload in method.Function.Overloads) { function.UpdateDefaultParameters(_unit, overload.GetParameters()); } } } } return false; } internal void WalkBody(Node node, AnalysisUnit unit) { var oldUnit = _unit; var eval = _eval; _unit = unit; _eval = new ExpressionEvaluator(unit); try { node.Walk(this); } finally { _unit = oldUnit; _eval = eval; } } public override bool Walk(IfStatement node) { foreach (var test in node.Tests) { _eval.Evaluate(test.Test); var prevScope = Scope; TryPushIsInstanceScope(test, test.Test); test.Body.Walk(this); Scope = prevScope; } if (node.ElseStatement != null) { node.ElseStatement.Walk(this); } return false; } public override bool Walk(ImportStatement node) { int len = Math.Min(node.Names.Count, node.AsNames.Count); for (int i = 0; i < len; i++) { var curName = node.Names[i]; var asName = node.AsNames[i]; string importing, saveName; Node nameNode; if (curName.Names.Count == 0) { continue; } else if (curName.Names.Count > 1) { // import fob.oar if (asName != null) { // import fob.oar as baz, baz becomes the value of the oar module importing = curName.MakeString(); saveName = asName.Name; nameNode = asName; } else { // plain import fob.oar, we bring in fob into the scope saveName = importing = curName.Names[0].Name; nameNode = curName.Names[0]; } } else { // import fob importing = curName.Names[0].Name; if (asName != null) { saveName = asName.Name; nameNode = asName; } else { saveName = importing; nameNode = curName.Names[0]; } } ModuleReference modRef; var def = Scope.CreateVariable(nameNode, _unit, saveName); if (TryImportModule(importing, node.ForceAbsolute, out modRef)) { modRef.AddReference(_unit.DeclaringModule); Debug.Assert(modRef.Module != null); if (modRef.Module != null) { modRef.Module.Imported(_unit); if (modRef.AnalysisModule != null) { def.AddTypes(_unit, modRef.AnalysisModule); } def.AddAssignment(nameNode, _unit); } } } return true; } public override bool Walk(ReturnStatement node) { var fnScope = CurrentFunction; if (node.Expression != null && fnScope != null) { var lookupRes = _eval.Evaluate(node.Expression); fnScope.AddReturnTypes(node, _unit, lookupRes); } return true; } public override bool Walk(WithStatement node) { foreach (var item in node.Items) { var ctxMgr = _eval.Evaluate(item.ContextManager); var enter = ctxMgr.GetMember(node, _unit, node.IsAsync ? "__aenter__" : "__enter__"); var exit = ctxMgr.GetMember(node, _unit, node.IsAsync ? "__aexit__" : "__exit__"); var ctxt = enter.Call(node, _unit, ExpressionEvaluator.EmptySets, ExpressionEvaluator.EmptyNames); var exitRes = exit.Call(node, _unit, ExpressionEvaluator.EmptySets, ExpressionEvaluator.EmptyNames); if (node.IsAsync) { ctxt = ctxt.Await(node, _unit); exitRes.Await(node, _unit); } if (item.Variable != null) { _eval.AssignTo(node, item.Variable, ctxt); } } return true; } public override bool Walk(PrintStatement node) { foreach (var expr in node.Expressions) { _eval.Evaluate(expr); } return false; } public override bool Walk(AssertStatement node) { TryPushIsInstanceScope(node, node.Test); _eval.EvaluateMaybeNull(node.Test); _eval.EvaluateMaybeNull(node.Message); return false; } private void TryPushIsInstanceScope(Node node, Expression test) { InterpreterScope newScope; if (Scope.TryGetNodeScope(node, out newScope)) { var outerScope = Scope; var isInstanceScope = (IsInstanceScope)newScope; // magic assert isinstance statement alters the type information for a node var namesAndExpressions = OverviewWalker.GetIsInstanceNamesAndExpressions(test); foreach (var nameAndExpr in namesAndExpressions) { var name = nameAndExpr.Key; var type = nameAndExpr.Value; var typeObj = _eval.EvaluateMaybeNull(type); isInstanceScope.CreateTypedVariable(name, _unit, name.Name, typeObj); } // push the scope, it will be popped when we leave the current SuiteStatement. Scope = newScope; } } public override bool Walk(SuiteStatement node) { var prevSuite = _curSuite; var prevScope = Scope; _curSuite = node; if (node.Statements != null) { foreach (var statement in node.Statements) { statement.Walk(this); } } Scope = prevScope; _curSuite = prevSuite; return false; } public override bool Walk(DelStatement node) { foreach (var expr in node.Expressions) { DeleteExpression(expr); } return false; } private void DeleteExpression(Expression expr) { NameExpression name = expr as NameExpression; if (name != null) { var var = Scope.CreateVariable(name, _unit, name.Name); return; } IndexExpression index = expr as IndexExpression; if (index != null) { var values = _eval.Evaluate(index.Target); var indexValues = _eval.Evaluate(index.Index); foreach (var value in values) { value.DeleteIndex(index, _unit, indexValues); } return; } MemberExpression member = expr as MemberExpression; if (member != null) { if (!string.IsNullOrEmpty(member.Name)) { var values = _eval.Evaluate(member.Target); foreach (var value in values) { value.DeleteMember(member, _unit, member.Name); } } return; } ParenthesisExpression paren = expr as ParenthesisExpression; if (paren != null) { DeleteExpression(paren.Expression); return; } SequenceExpression seq = expr as SequenceExpression; if (seq != null) { foreach (var item in seq.Items) { DeleteExpression(item); } return; } } public override bool Walk(RaiseStatement node) { _eval.EvaluateMaybeNull(node.Value); _eval.EvaluateMaybeNull(node.Traceback); _eval.EvaluateMaybeNull(node.ExceptType); _eval.EvaluateMaybeNull(node.Cause); return false; } public override bool Walk(WhileStatement node) { _eval.Evaluate(node.Test); node.Body.Walk(this); if (node.ElseStatement != null) { node.ElseStatement.Walk(this); } return false; } public override bool Walk(TryStatement node) { node.Body.Walk(this); if (node.Handlers != null) { foreach (var handler in node.Handlers) { var test = AnalysisSet.Empty; if (handler.Test != null) { var testTypes = _eval.Evaluate(handler.Test); if (handler.Target != null) { foreach (var type in testTypes) { ClassInfo klass = type as ClassInfo; if (klass != null) { test = test.Union(klass.Instance.SelfSet); } BuiltinClassInfo builtinClass = type as BuiltinClassInfo; if (builtinClass != null) { test = test.Union(builtinClass.Instance.SelfSet); } } _eval.AssignTo(handler, handler.Target, test); } } handler.Body.Walk(this); } } if (node.Finally != null) { node.Finally.Walk(this); } if (node.Else != null) { node.Else.Walk(this); } return false; } public override bool Walk(ExecStatement node) { if (node.Code != null) { _eval.Evaluate(node.Code); } if (node.Locals != null) { _eval.Evaluate(node.Locals); } if (node.Globals != null) { _eval.Evaluate(node.Globals); } return false; } } }
using System; namespace NQuery.Demo { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { TD.SandDock.DockContainer dockContainer1; this.documentBrowserDockableWindow = new TD.SandDock.DockableWindow(); this.noBrowserLabel = new System.Windows.Forms.Label(); this.propertiesDockableWindow = new TD.SandDock.DockableWindow(); this.propertyGrid = new VisualStudioPropertyGrid(); this.sandDockManager = new TD.SandDock.SandDockManager(); this.menuStrip = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newQueryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.importTestDefinitionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exportTestDefinitionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.documentBrowserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.propertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.welcomePageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.queryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.executeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.explainToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripSeparator(); this.listMembersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.parameterInfoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.completeWordToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.addinsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip = new System.Windows.Forms.ToolStrip(); this.newQueryToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.cutToolStripButton = new System.Windows.Forms.ToolStripButton(); this.copyToolStripButton = new System.Windows.Forms.ToolStripButton(); this.pasteToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.undoToolStripButton = new System.Windows.Forms.ToolStripButton(); this.redoToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.propertiesToolStripButton = new System.Windows.Forms.ToolStripButton(); this.documentBrowserToolStripButton = new System.Windows.Forms.ToolStripButton(); this.welcomePageToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.executeToolStripButton = new System.Windows.Forms.ToolStripButton(); this.explainQueryToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.saveResultsToolStripButton = new System.Windows.Forms.ToolStripButton(); dockContainer1 = new TD.SandDock.DockContainer(); dockContainer1.SuspendLayout(); this.documentBrowserDockableWindow.SuspendLayout(); this.propertiesDockableWindow.SuspendLayout(); this.menuStrip.SuspendLayout(); this.toolStrip.SuspendLayout(); this.SuspendLayout(); // // dockContainer1 // dockContainer1.Controls.Add(this.documentBrowserDockableWindow); dockContainer1.Controls.Add(this.propertiesDockableWindow); dockContainer1.Dock = System.Windows.Forms.DockStyle.Right; dockContainer1.LayoutSystem = new TD.SandDock.SplitLayoutSystem(new System.Drawing.SizeF(250, 517), System.Windows.Forms.Orientation.Horizontal, new TD.SandDock.LayoutSystemBase[] { ((TD.SandDock.LayoutSystemBase)(new TD.SandDock.ControlLayoutSystem(new System.Drawing.SizeF(250, 243), new TD.SandDock.DockControl[] { ((TD.SandDock.DockControl)(this.documentBrowserDockableWindow))}, this.documentBrowserDockableWindow))), ((TD.SandDock.LayoutSystemBase)(new TD.SandDock.ControlLayoutSystem(new System.Drawing.SizeF(250, 271), new TD.SandDock.DockControl[] { ((TD.SandDock.DockControl)(this.propertiesDockableWindow))}, this.propertiesDockableWindow)))}); dockContainer1.Location = new System.Drawing.Point(538, 49); dockContainer1.Manager = this.sandDockManager; dockContainer1.Name = "dockContainer1"; dockContainer1.Size = new System.Drawing.Size(254, 517); dockContainer1.TabIndex = 24; // // documentBrowserDockableWindow // this.documentBrowserDockableWindow.BorderStyle = TD.SandDock.Rendering.BorderStyle.Flat; this.documentBrowserDockableWindow.Controls.Add(this.noBrowserLabel); this.documentBrowserDockableWindow.Guid = new System.Guid("b4875f5d-da25-4046-a14a-239ae8ab87b2"); this.documentBrowserDockableWindow.Location = new System.Drawing.Point(4, 18); this.documentBrowserDockableWindow.Name = "documentBrowserDockableWindow"; this.documentBrowserDockableWindow.Size = new System.Drawing.Size(250, 201); this.documentBrowserDockableWindow.TabImage = global::NQuery.Demo.Properties.Resources.Browser; this.documentBrowserDockableWindow.TabIndex = 0; this.documentBrowserDockableWindow.Text = "Document Browser"; // // noBrowserLabel // this.noBrowserLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.noBrowserLabel.Location = new System.Drawing.Point(16, 21); this.noBrowserLabel.Name = "noBrowserLabel"; this.noBrowserLabel.Size = new System.Drawing.Size(221, 162); this.noBrowserLabel.TabIndex = 0; this.noBrowserLabel.Text = "There are no items to show for the selected document."; this.noBrowserLabel.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // propertiesDockableWindow // this.propertiesDockableWindow.Controls.Add(this.propertyGrid); this.propertiesDockableWindow.Guid = new System.Guid("86a69ab1-973d-4313-b8e8-f72667a53005"); this.propertiesDockableWindow.Location = new System.Drawing.Point(4, 265); this.propertiesDockableWindow.Name = "propertiesDockableWindow"; this.propertiesDockableWindow.Size = new System.Drawing.Size(250, 228); this.propertiesDockableWindow.TabImage = global::NQuery.Demo.Properties.Resources.Properties; this.propertiesDockableWindow.TabIndex = 1; this.propertiesDockableWindow.Text = "Properties"; // // propertyGrid // this.propertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.propertyGrid.HelpVisible = false; this.propertyGrid.Location = new System.Drawing.Point(0, 0); this.propertyGrid.Name = "propertyGrid"; this.propertyGrid.Size = new System.Drawing.Size(250, 228); this.propertyGrid.TabIndex = 6; // // sandDockManager // this.sandDockManager.DockSystemContainer = this; this.sandDockManager.OwnerForm = this; this.sandDockManager.ActiveTabbedDocumentChanged += new System.EventHandler(this.sandDockManager_ActiveTabbedDocumentChanged); // // menuStrip // this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, this.viewToolStripMenuItem, this.queryToolStripMenuItem, this.toolsToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; this.menuStrip.Size = new System.Drawing.Size(792, 24); this.menuStrip.TabIndex = 5; this.menuStrip.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newQueryToolStripMenuItem, this.toolStripMenuItem1, this.closeToolStripMenuItem, this.toolStripSeparator2, this.importTestDefinitionToolStripMenuItem, this.exportTestDefinitionToolStripMenuItem, this.toolStripMenuItem5, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "&File"; // // newQueryToolStripMenuItem // this.newQueryToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.New; this.newQueryToolStripMenuItem.Name = "newQueryToolStripMenuItem"; this.newQueryToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newQueryToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.newQueryToolStripMenuItem.Text = "New Query..."; this.newQueryToolStripMenuItem.Click += new System.EventHandler(this.newQueryToolStripMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(198, 6); // // closeToolStripMenuItem // this.closeToolStripMenuItem.Name = "closeToolStripMenuItem"; this.closeToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F4))); this.closeToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.closeToolStripMenuItem.Text = "&Close"; this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeToolStripMenuItem_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(198, 6); // // importTestDefinitionToolStripMenuItem // this.importTestDefinitionToolStripMenuItem.Name = "importTestDefinitionToolStripMenuItem"; this.importTestDefinitionToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.importTestDefinitionToolStripMenuItem.Text = "Import Test Definition..."; this.importTestDefinitionToolStripMenuItem.Click += new System.EventHandler(this.importTestDefinitionToolStripMenuItem_Click); // // exportTestDefinitionToolStripMenuItem // this.exportTestDefinitionToolStripMenuItem.Name = "exportTestDefinitionToolStripMenuItem"; this.exportTestDefinitionToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.exportTestDefinitionToolStripMenuItem.Text = "Export Test Definition..."; this.exportTestDefinitionToolStripMenuItem.Click += new System.EventHandler(this.exportTestDefinitionToolStripMenuItem_Click); // // toolStripMenuItem5 // this.toolStripMenuItem5.Name = "toolStripMenuItem5"; this.toolStripMenuItem5.Size = new System.Drawing.Size(198, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.exitToolStripMenuItem.Text = "E&xit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // editToolStripMenuItem // this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.undoToolStripMenuItem, this.redoToolStripMenuItem, this.toolStripSeparator4, this.cutToolStripMenuItem, this.copyToolStripMenuItem, this.pasteToolStripMenuItem, this.deleteToolStripMenuItem, this.toolStripSeparator5, this.selectAllToolStripMenuItem}); this.editToolStripMenuItem.Name = "editToolStripMenuItem"; this.editToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.editToolStripMenuItem.Text = "&Edit"; // // undoToolStripMenuItem // this.undoToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.Undo; this.undoToolStripMenuItem.Name = "undoToolStripMenuItem"; this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z))); this.undoToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.undoToolStripMenuItem.Text = "&Undo"; this.undoToolStripMenuItem.Click += new System.EventHandler(this.undoToolStripMenuItem_Click); // // redoToolStripMenuItem // this.redoToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.Redo; this.redoToolStripMenuItem.Name = "redoToolStripMenuItem"; this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y))); this.redoToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.redoToolStripMenuItem.Text = "&Redo"; this.redoToolStripMenuItem.Click += new System.EventHandler(this.redoToolStripMenuItem_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(164, 6); // // cutToolStripMenuItem // this.cutToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.Cut; this.cutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.cutToolStripMenuItem.Name = "cutToolStripMenuItem"; this.cutToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); this.cutToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.cutToolStripMenuItem.Text = "Cu&t"; this.cutToolStripMenuItem.Click += new System.EventHandler(this.cutToolStripMenuItem_Click); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.Copy; this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C))); this.copyToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.copyToolStripMenuItem.Text = "&Copy"; this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click); // // pasteToolStripMenuItem // this.pasteToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.Paste; this.pasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem"; this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V))); this.pasteToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.pasteToolStripMenuItem.Text = "&Paste"; this.pasteToolStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click); // // deleteToolStripMenuItem // this.deleteToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.Delete; this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem"; this.deleteToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.deleteToolStripMenuItem.Text = "&Delete"; this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripMenuItem_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(164, 6); // // selectAllToolStripMenuItem // this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem"; this.selectAllToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A))); this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.selectAllToolStripMenuItem.Text = "Select &All"; this.selectAllToolStripMenuItem.Click += new System.EventHandler(this.selectAllToolStripMenuItem_Click); // // viewToolStripMenuItem // this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.documentBrowserToolStripMenuItem, this.propertiesToolStripMenuItem, this.toolStripMenuItem2, this.welcomePageToolStripMenuItem}); this.viewToolStripMenuItem.Name = "viewToolStripMenuItem"; this.viewToolStripMenuItem.Size = new System.Drawing.Size(41, 20); this.viewToolStripMenuItem.Text = "&View"; // // documentBrowserToolStripMenuItem // this.documentBrowserToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.Browser; this.documentBrowserToolStripMenuItem.Name = "documentBrowserToolStripMenuItem"; this.documentBrowserToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.documentBrowserToolStripMenuItem.Text = "Document Browser"; this.documentBrowserToolStripMenuItem.Click += new System.EventHandler(this.documentBrowserToolStripMenuItem_Click); // // propertiesToolStripMenuItem // this.propertiesToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.Properties; this.propertiesToolStripMenuItem.Name = "propertiesToolStripMenuItem"; this.propertiesToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F4; this.propertiesToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.propertiesToolStripMenuItem.Text = "Properties"; this.propertiesToolStripMenuItem.Click += new System.EventHandler(this.propertiesToolStripMenuItem_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(172, 6); // // welcomePageToolStripMenuItem // this.welcomePageToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.WelcomeDocument; this.welcomePageToolStripMenuItem.Name = "welcomePageToolStripMenuItem"; this.welcomePageToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.welcomePageToolStripMenuItem.Text = "Welcome Page"; this.welcomePageToolStripMenuItem.Click += new System.EventHandler(this.welcomePageToolStripMenuItem_Click); // // queryToolStripMenuItem // this.queryToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.executeToolStripMenuItem, this.explainToolStripMenuItem, this.toolStripMenuItem7, this.listMembersToolStripMenuItem, this.parameterInfoToolStripMenuItem, this.completeWordToolStripMenuItem}); this.queryToolStripMenuItem.Name = "queryToolStripMenuItem"; this.queryToolStripMenuItem.Size = new System.Drawing.Size(49, 20); this.queryToolStripMenuItem.Text = "&Query"; // // executeToolStripMenuItem // this.executeToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.Execute; this.executeToolStripMenuItem.Name = "executeToolStripMenuItem"; this.executeToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F5; this.executeToolStripMenuItem.Size = new System.Drawing.Size(249, 22); this.executeToolStripMenuItem.Text = "&Execute"; this.executeToolStripMenuItem.Click += new System.EventHandler(this.executeToolStripMenuItem_Click); // // explainToolStripMenuItem // this.explainToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.EstimatePlan; this.explainToolStripMenuItem.Name = "explainToolStripMenuItem"; this.explainToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.L))); this.explainToolStripMenuItem.Size = new System.Drawing.Size(249, 22); this.explainToolStripMenuItem.Text = "Explain"; this.explainToolStripMenuItem.Click += new System.EventHandler(this.explainToolStripMenuItem_Click); // // toolStripMenuItem7 // this.toolStripMenuItem7.Name = "toolStripMenuItem7"; this.toolStripMenuItem7.Size = new System.Drawing.Size(246, 6); // // listMembersToolStripMenuItem // this.listMembersToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.ListMembers; this.listMembersToolStripMenuItem.Name = "listMembersToolStripMenuItem"; this.listMembersToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+J"; this.listMembersToolStripMenuItem.Size = new System.Drawing.Size(249, 22); this.listMembersToolStripMenuItem.Text = "List Members"; this.listMembersToolStripMenuItem.Click += new System.EventHandler(this.listMembersToolStripMenuItem_Click); // // parameterInfoToolStripMenuItem // this.parameterInfoToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.ParameterInfo; this.parameterInfoToolStripMenuItem.Name = "parameterInfoToolStripMenuItem"; this.parameterInfoToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Shift+Space"; this.parameterInfoToolStripMenuItem.Size = new System.Drawing.Size(249, 22); this.parameterInfoToolStripMenuItem.Text = "Parameter Info"; this.parameterInfoToolStripMenuItem.Click += new System.EventHandler(this.parameterInfoToolStripMenuItem_Click); // completeWordToolStripMenuItem // this.completeWordToolStripMenuItem.Image = global::NQuery.Demo.Properties.Resources.CompleteWord; this.completeWordToolStripMenuItem.Name = "completeWordToolStripMenuItem"; this.completeWordToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+Space"; this.completeWordToolStripMenuItem.Size = new System.Drawing.Size(249, 22); this.completeWordToolStripMenuItem.Text = "Complete Word"; this.completeWordToolStripMenuItem.Click += new System.EventHandler(this.completeWordToolStripMenuItem_Click); // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.addinsToolStripMenuItem}); this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; this.toolsToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.toolsToolStripMenuItem.Text = "&Tools"; // // addinsToolStripMenuItem // this.addinsToolStripMenuItem.Name = "addinsToolStripMenuItem"; this.addinsToolStripMenuItem.Size = new System.Drawing.Size(133, 22); this.addinsToolStripMenuItem.Text = "Add-ins..."; this.addinsToolStripMenuItem.Click += new System.EventHandler(this.addinsToolStripMenuItem_Click); // // toolStrip // this.toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newQueryToolStripButton, this.toolStripSeparator3, this.cutToolStripButton, this.copyToolStripButton, this.pasteToolStripButton, this.toolStripSeparator8, this.undoToolStripButton, this.redoToolStripButton, this.toolStripSeparator6, this.propertiesToolStripButton, this.documentBrowserToolStripButton, this.welcomePageToolStripButton, this.toolStripSeparator7, this.executeToolStripButton, this.explainQueryToolStripButton, this.toolStripSeparator1, this.saveResultsToolStripButton}); this.toolStrip.Location = new System.Drawing.Point(0, 24); this.toolStrip.Name = "toolStrip"; this.toolStrip.Size = new System.Drawing.Size(792, 25); this.toolStrip.TabIndex = 23; this.toolStrip.Text = "toolStrip1"; // // newQueryToolStripButton // this.newQueryToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.newQueryToolStripButton.Image = global::NQuery.Demo.Properties.Resources.New; this.newQueryToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.newQueryToolStripButton.Name = "newQueryToolStripButton"; this.newQueryToolStripButton.Size = new System.Drawing.Size(23, 22); this.newQueryToolStripButton.Text = "New Query"; this.newQueryToolStripButton.Click += new System.EventHandler(this.newQueryToolStripButton_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25); // // cutToolStripButton // this.cutToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.cutToolStripButton.Image = global::NQuery.Demo.Properties.Resources.Cut; this.cutToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.cutToolStripButton.Name = "cutToolStripButton"; this.cutToolStripButton.Size = new System.Drawing.Size(23, 22); this.cutToolStripButton.Text = "Cut"; this.cutToolStripButton.Click += new System.EventHandler(this.cutToolStripButton_Click); // // copyToolStripButton // this.copyToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.copyToolStripButton.Image = global::NQuery.Demo.Properties.Resources.Copy; this.copyToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.copyToolStripButton.Name = "copyToolStripButton"; this.copyToolStripButton.Size = new System.Drawing.Size(23, 22); this.copyToolStripButton.Text = "Copy"; this.copyToolStripButton.Click += new System.EventHandler(this.copyToolStripButton_Click); // // pasteToolStripButton // this.pasteToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.pasteToolStripButton.Image = global::NQuery.Demo.Properties.Resources.Paste; this.pasteToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.pasteToolStripButton.Name = "pasteToolStripButton"; this.pasteToolStripButton.Size = new System.Drawing.Size(23, 22); this.pasteToolStripButton.Text = "Paste"; this.pasteToolStripButton.Click += new System.EventHandler(this.pasteToolStripButton_Click); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; this.toolStripSeparator8.Size = new System.Drawing.Size(6, 25); // // undoToolStripButton // this.undoToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.undoToolStripButton.Image = global::NQuery.Demo.Properties.Resources.Undo; this.undoToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.undoToolStripButton.Name = "undoToolStripButton"; this.undoToolStripButton.Size = new System.Drawing.Size(23, 22); this.undoToolStripButton.Text = "Undo"; this.undoToolStripButton.Click += new System.EventHandler(this.undoToolStripButton_Click); // // redoToolStripButton // this.redoToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.redoToolStripButton.Image = global::NQuery.Demo.Properties.Resources.Redo; this.redoToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.redoToolStripButton.Name = "redoToolStripButton"; this.redoToolStripButton.Size = new System.Drawing.Size(23, 22); this.redoToolStripButton.Text = "Redo"; this.redoToolStripButton.Click += new System.EventHandler(this.redoToolStripButton_Click); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25); // // propertiesToolStripButton // this.propertiesToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.propertiesToolStripButton.Image = global::NQuery.Demo.Properties.Resources.Properties; this.propertiesToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.propertiesToolStripButton.Name = "propertiesToolStripButton"; this.propertiesToolStripButton.Size = new System.Drawing.Size(23, 22); this.propertiesToolStripButton.Text = "Properties"; this.propertiesToolStripButton.Click += new System.EventHandler(this.propertiesToolStripButton_Click); // // documentBrowserToolStripButton // this.documentBrowserToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.documentBrowserToolStripButton.Image = global::NQuery.Demo.Properties.Resources.Browser; this.documentBrowserToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.documentBrowserToolStripButton.Name = "documentBrowserToolStripButton"; this.documentBrowserToolStripButton.Size = new System.Drawing.Size(23, 22); this.documentBrowserToolStripButton.Text = "Document Browser"; this.documentBrowserToolStripButton.Click += new System.EventHandler(this.documentBrowserToolStripButton_Click); // // welcomePageToolStripButton // this.welcomePageToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.welcomePageToolStripButton.Image = global::NQuery.Demo.Properties.Resources.WelcomeDocument; this.welcomePageToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.welcomePageToolStripButton.Name = "welcomePageToolStripButton"; this.welcomePageToolStripButton.Size = new System.Drawing.Size(23, 22); this.welcomePageToolStripButton.Text = "Welcome Page"; this.welcomePageToolStripButton.Click += new System.EventHandler(this.welcomePageToolStripButton_Click); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25); // // executeToolStripButton // this.executeToolStripButton.Image = global::NQuery.Demo.Properties.Resources.Execute; this.executeToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.executeToolStripButton.Name = "executeToolStripButton"; this.executeToolStripButton.Size = new System.Drawing.Size(66, 22); this.executeToolStripButton.Text = "Execute"; this.executeToolStripButton.Click += new System.EventHandler(this.executeToolStripButton_Click); // // explainQueryToolStripButton // this.explainQueryToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.explainQueryToolStripButton.Image = global::NQuery.Demo.Properties.Resources.EstimatePlan; this.explainQueryToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.explainQueryToolStripButton.Name = "explainQueryToolStripButton"; this.explainQueryToolStripButton.Size = new System.Drawing.Size(23, 22); this.explainQueryToolStripButton.Text = "Show execution plan"; this.explainQueryToolStripButton.Click += new System.EventHandler(this.explainQueryToolStripButton_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // saveResultsToolStripButton // this.saveResultsToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.saveResultsToolStripButton.Image = global::NQuery.Demo.Properties.Resources.SaveGrid; this.saveResultsToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.saveResultsToolStripButton.Name = "saveResultsToolStripButton"; this.saveResultsToolStripButton.Size = new System.Drawing.Size(23, 22); this.saveResultsToolStripButton.Text = "Save Results to File"; this.saveResultsToolStripButton.Click += new System.EventHandler(this.saveResultsToolStripButton_Click); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.AppWorkspace; this.ClientSize = new System.Drawing.Size(792, 566); this.Controls.Add(dockContainer1); this.Controls.Add(this.toolStrip); this.Controls.Add(this.menuStrip); this.MainMenuStrip = this.menuStrip; this.Name = "MainForm"; this.Text = "NQuery Hosting Demo"; dockContainer1.ResumeLayout(false); this.documentBrowserDockableWindow.ResumeLayout(false); this.propertiesDockableWindow.ResumeLayout(false); this.menuStrip.ResumeLayout(false); this.menuStrip.PerformLayout(); this.toolStrip.ResumeLayout(false); this.toolStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip; private VisualStudioPropertyGrid propertyGrid; private System.Windows.Forms.ToolStripMenuItem queryToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem executeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem explainToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem7; private System.Windows.Forms.ToolStripMenuItem listMembersToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem parameterInfoToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem completeWordToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newQueryToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem importTestDefinitionToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exportTestDefinitionToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem; private System.Windows.Forms.ToolStrip toolStrip; private System.Windows.Forms.ToolStripButton executeToolStripButton; private System.Windows.Forms.ToolStripButton explainQueryToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton saveResultsToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem; private System.Windows.Forms.ToolStripButton newQueryToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripButton cutToolStripButton; private System.Windows.Forms.ToolStripButton copyToolStripButton; private System.Windows.Forms.ToolStripButton pasteToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.ToolStripButton undoToolStripButton; private System.Windows.Forms.ToolStripButton redoToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem addinsToolStripMenuItem; private System.Windows.Forms.Label noBrowserLabel; private TD.SandDock.SandDockManager sandDockManager; private TD.SandDock.DockableWindow documentBrowserDockableWindow; private TD.SandDock.DockableWindow propertiesDockableWindow; private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem documentBrowserToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem propertiesToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem welcomePageToolStripMenuItem; private System.Windows.Forms.ToolStripButton propertiesToolStripButton; private System.Windows.Forms.ToolStripButton documentBrowserToolStripButton; private System.Windows.Forms.ToolStripButton welcomePageToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using NodaTime.Calendars; using NodaTime.Text; using NUnit.Framework; namespace NodaTime.Test { [TestFixture] public partial class InstantTest { private static readonly Instant one = Instant.FromUntrustedDuration(Duration.FromNanoseconds(1L)); private static readonly Instant threeMillion = Instant.FromUntrustedDuration(Duration.FromNanoseconds(3000000L)); private static readonly Instant negativeFiftyMillion = Instant.FromUntrustedDuration(Duration.FromNanoseconds(-50000000L)); [Test] // Gregorian calendar: 1957-10-04 [TestCase(2436116.31, 1957, 9, 21, 19, 26, 24, Description = "Sample from Astronomical Algorithms 2nd Edition, chapter 7")] // Gregorian calendar: 2013-01-01 [TestCase(2456293.520833, 2012, 12, 19, 0, 30, 0, Description = "Sample from Wikipedia")] [TestCase(1842713.0, 333, 1, 27, 12, 0, 0, Description = "Another sample from Astronomical Algorithms 2nd Edition, chapter 7")] [TestCase(0.0, -4712, 1, 1, 12, 0, 0, Description = "Julian epoch")] public void JulianDateConversions(double julianDate, int year, int month, int day, int hour, int minute, int second) { // When dealing with floating point binary data, if we're accurate to 50 milliseconds, that's fine... // (0.000001 days = ~86ms, as a guide to the scale involved...) Instant actual = Instant.FromJulianDate(julianDate); Instant expected = new LocalDateTime(year, month, day, hour, minute, second, CalendarSystem.Julian).InUtc().ToInstant(); Assert.AreEqual(expected.ToUnixTimeMilliseconds(), actual.ToUnixTimeMilliseconds(), 50, "Expected {0}, was {1}", expected, actual); Assert.AreEqual(julianDate, expected.ToJulianDate(), 0.000001); } [Test] public void FromUtcNoSeconds() { Instant viaUtc = DateTimeZone.Utc.AtStrictly(new LocalDateTime(2008, 4, 3, 10, 35, 0)).ToInstant(); Assert.AreEqual(viaUtc, Instant.FromUtc(2008, 4, 3, 10, 35)); } [Test] public void FromUtcWithSeconds() { Instant viaUtc = DateTimeZone.Utc.AtStrictly(new LocalDateTime(2008, 4, 3, 10, 35, 23)).ToInstant(); Assert.AreEqual(viaUtc, Instant.FromUtc(2008, 4, 3, 10, 35, 23)); } [Test] public void InUtc() { ZonedDateTime viaInstant = Instant.FromUtc(2008, 4, 3, 10, 35, 23).InUtc(); ZonedDateTime expected = DateTimeZone.Utc.AtStrictly(new LocalDateTime(2008, 4, 3, 10, 35, 23)); Assert.AreEqual(expected, viaInstant); } [Test] public void InZone() { DateTimeZone london = DateTimeZoneProviders.Tzdb["Europe/London"]; ZonedDateTime viaInstant = Instant.FromUtc(2008, 6, 10, 13, 16, 17).InZone(london); // London is UTC+1 in the Summer, so the above is 14:16:17 local. LocalDateTime local = new LocalDateTime(2008, 6, 10, 14, 16, 17); ZonedDateTime expected = london.AtStrictly(local); Assert.AreEqual(expected, viaInstant); } [Test] public void WithOffset() { // Jon talks about Noda Time at Leetspeak in Sweden on October 12th 2013, at 13:15 UTC+2 Instant instant = Instant.FromUtc(2013, 10, 12, 11, 15); Offset offset = Offset.FromHours(2); OffsetDateTime actual = instant.WithOffset(offset); OffsetDateTime expected = new OffsetDateTime(new LocalDateTime(2013, 10, 12, 13, 15), offset); Assert.AreEqual(expected, actual); } [Test] public void WithOffset_NonIsoCalendar() { // October 12th 2013 ISO is 1434-12-07 Islamic CalendarSystem calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Civil); Instant instant = Instant.FromUtc(2013, 10, 12, 11, 15); Offset offset = Offset.FromHours(2); OffsetDateTime actual = instant.WithOffset(offset, calendar); OffsetDateTime expected = new OffsetDateTime(new LocalDateTime(1434, 12, 7, 13, 15, calendar), offset); Assert.AreEqual(expected, actual); } [Test] public void FromTicksSinceUnixEpoch() { Instant instant = Instant.FromUnixTimeTicks(12345L); Assert.AreEqual(12345L, instant.ToUnixTimeTicks()); } [Test] public void FromUnixTimeMilliseconds_Valid() { Instant actual = Instant.FromUnixTimeMilliseconds(12345L); Instant expected = Instant.FromUnixTimeTicks(12345L * NodaConstants.TicksPerMillisecond); Assert.AreEqual(expected, actual); } [Test] public void FromUnixTimeMilliseconds_TooLarge() { Assert.Throws<ArgumentOutOfRangeException>(() => Instant.FromUnixTimeMilliseconds(long.MaxValue / 100)); } [Test] public void FromUnixTimeMilliseconds_TooSmall() { Assert.Throws<ArgumentOutOfRangeException>(() => Instant.FromUnixTimeMilliseconds(long.MinValue / 100)); } [Test] public void FromUnixTimeSeconds_Valid() { Instant actual = Instant.FromUnixTimeSeconds(12345L); Instant expected = Instant.FromUnixTimeTicks(12345L * NodaConstants.TicksPerSecond); Assert.AreEqual(expected, actual); } [Test] public void FromUnixTimeSeconds_TooLarge() { Assert.Throws<ArgumentOutOfRangeException>(() => Instant.FromUnixTimeSeconds(long.MaxValue / 1000000)); } [Test] public void FromUnixTimeSeconds_TooSmall() { Assert.Throws<ArgumentOutOfRangeException>(() => Instant.FromUnixTimeSeconds(long.MinValue / 1000000)); } [Test] [TestCase(-1500, -2)] [TestCase(-1001, -2)] [TestCase(-1000, -1)] [TestCase(-999, -1)] [TestCase(-500, -1)] [TestCase(0, 0)] [TestCase(500, 0)] [TestCase(999, 0)] [TestCase(1000, 1)] [TestCase(1001, 1)] [TestCase(1500, 1)] public void ToUnixTimeSeconds(long milliseconds, int expectedSeconds) { var instant = Instant.FromUnixTimeMilliseconds(milliseconds); Assert.AreEqual(expectedSeconds, instant.ToUnixTimeSeconds()); } [Test] [TestCase(-15000, -2)] [TestCase(-10001, -2)] [TestCase(-10000, -1)] [TestCase(-9999, -1)] [TestCase(-5000, -1)] [TestCase(0, 0)] [TestCase(5000, 0)] [TestCase(9999, 0)] [TestCase(10000, 1)] [TestCase(10001, 1)] [TestCase(15000, 1)] public void ToUnixTimeMilliseconds(long ticks, int expectedMilliseconds) { var instant = Instant.FromUnixTimeTicks(ticks); Assert.AreEqual(expectedMilliseconds, instant.ToUnixTimeMilliseconds()); } [Test] public void UnixConversions_ExtremeValues() { // Round down to a whole second to make round-tripping work. var max = Instant.MaxValue - Duration.FromSeconds(1) + Duration.Epsilon; Assert.AreEqual(max, Instant.FromUnixTimeSeconds(max.ToUnixTimeSeconds())); Assert.AreEqual(max, Instant.FromUnixTimeMilliseconds(max.ToUnixTimeMilliseconds())); Assert.AreEqual(max, Instant.FromUnixTimeTicks(max.ToUnixTimeTicks())); var min = Instant.MinValue; Assert.AreEqual(min, Instant.FromUnixTimeSeconds(min.ToUnixTimeSeconds())); Assert.AreEqual(min, Instant.FromUnixTimeMilliseconds(min.ToUnixTimeMilliseconds())); Assert.AreEqual(min, Instant.FromUnixTimeTicks(min.ToUnixTimeTicks())); } [Test] public void InZoneWithCalendar() { CalendarSystem copticCalendar = CalendarSystem.Coptic; DateTimeZone london = DateTimeZoneProviders.Tzdb["Europe/London"]; ZonedDateTime viaInstant = Instant.FromUtc(2004, 6, 9, 11, 10).InZone(london, copticCalendar); // Date taken from CopticCalendarSystemTest. Time will be 12:10 (London is UTC+1 in Summer) LocalDateTime local = new LocalDateTime(1720, 10, 2, 12, 10, 0, copticCalendar); ZonedDateTime expected = london.AtStrictly(local); Assert.AreEqual(expected, viaInstant); } [Test] public void Max() { Instant x = Instant.FromUnixTimeTicks(100); Instant y = Instant.FromUnixTimeTicks(200); Assert.AreEqual(y, Instant.Max(x, y)); Assert.AreEqual(y, Instant.Max(y, x)); Assert.AreEqual(x, Instant.Max(x, Instant.MinValue)); Assert.AreEqual(x, Instant.Max(Instant.MinValue, x)); Assert.AreEqual(Instant.MaxValue, Instant.Max(Instant.MaxValue, x)); Assert.AreEqual(Instant.MaxValue, Instant.Max(x, Instant.MaxValue)); } [Test] public void Min() { Instant x = Instant.FromUnixTimeTicks(100); Instant y = Instant.FromUnixTimeTicks(200); Assert.AreEqual(x, Instant.Min(x, y)); Assert.AreEqual(x, Instant.Min(y, x)); Assert.AreEqual(Instant.MinValue, Instant.Min(x, Instant.MinValue)); Assert.AreEqual(Instant.MinValue, Instant.Min(Instant.MinValue, x)); Assert.AreEqual(x, Instant.Min(Instant.MaxValue, x)); Assert.AreEqual(x, Instant.Min(x, Instant.MaxValue)); } [Test] public void ToDateTimeUtc() { Instant x = Instant.FromUtc(2011, 08, 18, 20, 53); DateTime expected = new DateTime(2011, 08, 18, 20, 53, 0, DateTimeKind.Utc); DateTime actual = x.ToDateTimeUtc(); Assert.AreEqual(expected, actual); // Kind isn't checked by Equals... Assert.AreEqual(DateTimeKind.Utc, actual.Kind); } [Test] public void ToDateTimeOffset() { Instant x = Instant.FromUtc(2011, 08, 18, 20, 53); DateTimeOffset expected = new DateTimeOffset(2011, 08, 18, 20, 53, 0, TimeSpan.Zero); Assert.AreEqual(expected, x.ToDateTimeOffset()); } [Test] public void FromDateTimeOffset() { DateTimeOffset dateTimeOffset = new DateTimeOffset(2011, 08, 18, 20, 53, 0, TimeSpan.FromHours(5)); Instant expected = Instant.FromUtc(2011, 08, 18, 15, 53); Assert.AreEqual(expected, Instant.FromDateTimeOffset(dateTimeOffset)); } [Test] public void FromDateTimeUtc_Invalid() { Assert.Throws<ArgumentException>(() => Instant.FromDateTimeUtc(new DateTime(2011, 08, 18, 20, 53, 0, DateTimeKind.Local))); Assert.Throws<ArgumentException>(() => Instant.FromDateTimeUtc(new DateTime(2011, 08, 18, 20, 53, 0, DateTimeKind.Unspecified))); } [Test] public void FromDateTimeUtc_Valid() { DateTime x = new DateTime(2011, 08, 18, 20, 53, 0, DateTimeKind.Utc); Instant expected = Instant.FromUtc(2011, 08, 18, 20, 53); Assert.AreEqual(expected, Instant.FromDateTimeUtc(x)); } /// <summary> /// Using the default constructor is equivalent to January 1st 1970, midnight, UTC, ISO Calendar /// </summary> [Test] public void DefaultConstructor() { var actual = new Instant(); Assert.AreEqual(NodaConstants.UnixEpoch, actual); } [Test] public void XmlSerialization() { var value = new LocalDateTime(2013, 4, 12, 17, 53, 23, 123, 4567).InUtc().ToInstant(); TestHelper.AssertXmlRoundtrip(value, "<value>2013-04-12T17:53:23.1234567Z</value>"); } [Test] [TestCase("<value>2013-15-12T17:53:23Z</value>", typeof(UnparsableValueException), Description = "Invalid month")] public void XmlSerialization_Invalid(string xml, Type expectedExceptionType) { TestHelper.AssertXmlInvalid<Instant>(xml, expectedExceptionType); } [Test] public void BinarySerialization() { TestHelper.AssertBinaryRoundtrip(Instant.FromUnixTimeTicks(12345L)); TestHelper.AssertBinaryRoundtrip(Instant.MinValue); TestHelper.AssertBinaryRoundtrip(Instant.MaxValue); } [Test] [TestCase(-101L, -2L)] [TestCase(-100L, -1L)] [TestCase(-99L, -1L)] [TestCase(-1L, -1L)] [TestCase(0L, 0L)] [TestCase(99L, 0L)] [TestCase(100L, 1L)] [TestCase(101L, 1L)] public void TicksTruncatesDown(long nanoseconds, long expectedTicks) { Duration nanos = Duration.FromNanoseconds(nanoseconds); Instant instant = Instant.FromUntrustedDuration(nanos); Assert.AreEqual(expectedTicks, instant.ToUnixTimeTicks()); } [Test] public void IsValid() { Assert.IsFalse(Instant.BeforeMinValue.IsValid); Assert.IsTrue(Instant.MinValue.IsValid); Assert.IsTrue(Instant.MaxValue.IsValid); Assert.IsFalse(Instant.AfterMaxValue.IsValid); } [Test] public void InvalidValues() { Assert.Greater(Instant.AfterMaxValue, Instant.MaxValue); Assert.Less(Instant.BeforeMinValue, Instant.MinValue); } [Test] public void PlusDuration_Overflow() { TestHelper.AssertOverflow(Instant.MinValue.Plus, -Duration.Epsilon); TestHelper.AssertOverflow(Instant.MaxValue.Plus, Duration.Epsilon); } [Test] public void ExtremeArithmetic() { Duration hugeAndPositive = Instant.MaxValue - Instant.MinValue; Duration hugeAndNegative = Instant.MinValue - Instant.MaxValue; Assert.AreEqual(hugeAndNegative, -hugeAndPositive); Assert.AreEqual(Instant.MaxValue, Instant.MinValue - hugeAndNegative); Assert.AreEqual(Instant.MaxValue, Instant.MinValue + hugeAndPositive); Assert.AreEqual(Instant.MinValue, Instant.MaxValue + hugeAndNegative); Assert.AreEqual(Instant.MinValue, Instant.MaxValue - hugeAndPositive); } [Test] public void PlusOffset_Overflow() { TestHelper.AssertOverflow(Instant.MinValue.Plus, Offset.FromSeconds(-1)); TestHelper.AssertOverflow(Instant.MaxValue.Plus, Offset.FromSeconds(1)); } [Test] public void FromUnixTimeMilliseconds_Range() { long smallestValid = Instant.MinValue.ToUnixTimeTicks() / NodaConstants.TicksPerMillisecond; long largestValid = Instant.MaxValue.ToUnixTimeTicks() / NodaConstants.TicksPerMillisecond; TestHelper.AssertValid(Instant.FromUnixTimeMilliseconds, smallestValid); TestHelper.AssertOutOfRange(Instant.FromUnixTimeMilliseconds, smallestValid - 1); TestHelper.AssertValid(Instant.FromUnixTimeMilliseconds, largestValid); TestHelper.AssertOutOfRange(Instant.FromUnixTimeMilliseconds, largestValid + 1); } [Test] public void FromUnixTimeSeconds_Range() { long smallestValid = Instant.MinValue.ToUnixTimeTicks() / NodaConstants.TicksPerSecond; long largestValid = Instant.MaxValue.ToUnixTimeTicks() / NodaConstants.TicksPerSecond; TestHelper.AssertValid(Instant.FromUnixTimeSeconds, smallestValid); TestHelper.AssertOutOfRange(Instant.FromUnixTimeSeconds, smallestValid - 1); TestHelper.AssertValid(Instant.FromUnixTimeSeconds, largestValid); TestHelper.AssertOutOfRange(Instant.FromUnixTimeSeconds, largestValid + 1); } [Test] public void FromTicksSinceUnixEpoch_Range() { long smallestValid = Instant.MinValue.ToUnixTimeTicks(); long largestValid = Instant.MaxValue.ToUnixTimeTicks(); TestHelper.AssertValid(Instant.FromUnixTimeTicks, smallestValid); TestHelper.AssertOutOfRange(Instant.FromUnixTimeTicks, smallestValid - 1); TestHelper.AssertValid(Instant.FromUnixTimeTicks, largestValid); TestHelper.AssertOutOfRange(Instant.FromUnixTimeTicks, largestValid + 1); } // See issue 269. [Test] public void ToDateTimeUtc_WithOverflow() { TestHelper.AssertOverflow(() => Instant.MinValue.ToDateTimeUtc()); } [Test] public void ToDateTimeOffset_WithOverflow() { TestHelper.AssertOverflow(() => Instant.MinValue.ToDateTimeOffset()); } } }
using System.Windows; using Forms = System.Windows.Forms; using System.Windows.Controls; using System; using System.Windows.Media; namespace CustomPrintScreen { public partial class MainWindow : Window { private LowLevelKeyboardListener _listener; public MainWindow() { InitializeComponent(); _listener = new LowLevelKeyboardListener(); _listener.OnKeyPressed += _listener_OnKeyPressed; _listener.HookKeyboard(); (InfoBtn.Content as Image).Width = Forms.Screen.PrimaryScreen.WorkingArea.Width * 0.016f; (SettingsBtn.Content as Image).Width = Forms.Screen.PrimaryScreen.WorkingArea.Width * 0.016f; (CloseBtn.Content as Image).Width = Forms.Screen.PrimaryScreen.WorkingArea.Width * 0.016f; Handler.mainWindow = this; } void _listener_OnKeyPressed(object sender, EventArgs e) { if (Handler.Bitmaps.Count == 0) { Handler.CreateScreens(); DrawApplication(); } _listener.UnHookKeyboard(); _listener.HookKeyboard(); } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { _listener.UnHookKeyboard(); } /// <summary> /// Function draws the application basing on the screens /// </summary> public void DrawApplication() { int ScreensAmount = Forms.Screen.AllScreens.Length; // if user has one screen and doesn't want the window to pop up if (ScreensAmount == 1 && !Settings.PopupOnOneMonitor) { // in advanced mode user will be able to crop and save if (Handler.AdvancedMode) { OpenCropWindow(0); } // other way the screen will be simply saved else { Handler.SaveScreen(0); return; } } else { for (int i = 0; i < ScreensAmount; i++) { // dump will be used for onclick events in buttons int dump = i; if (Handler.AdvancedMode) { // Structure // Every screenshot will be saved as grid's background and to the grid // will be added a stackpanel which will hold two buttons for cropping // and saving #region Create grid double ratio = Handler.Bitmaps[i].Height * 1.0d / Handler.Bitmaps[i].Width * 1.0d; Grid grid = new Grid() { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch, Width = SystemParameters.PrimaryScreenWidth * 0.9d / ScreensAmount * 1.0d, Margin = new Thickness(8, 0, 0, 0) }; grid.Height = grid.Width * ratio; grid.Background = new ImageBrush(Handler.BitmapToImageSource(Handler.Bitmaps[i])); imgs.Children.Add(grid); #endregion #region Create a StackPanel StackPanel sp = new StackPanel() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Orientation = Orientation.Horizontal }; grid.Children.Add(sp); #endregion #region Create buttons for cropping and saving and add them to StackPanel Button[] imgbuttons = new Button[2]; string[] imgspaths = new string[] { "crop.png", "save.png" }; for (int j = 0; j < 2; j++) { imgbuttons[j] = new Button() { Width = 100, Height = 100, Background = new SolidColorBrush(Color.FromArgb(130, 255, 255, 255)), Margin = new Thickness(4, 0, 0, 0), BorderThickness = new Thickness(4, 4, 4, 4), Content = new Image() { Source = Handler.LoadImage(imgspaths[j]) } }; sp.Children.Add(imgbuttons[j]); } imgbuttons[0].Click += (sender, e) => { OpenCropWindow(dump); }; imgbuttons[1].Click += (sender, e) => { Handler.SaveScreen(dump, false); }; #endregion } else { // Stucture // Every screenshot will be a buttons's content. // By pressing the button you save the image Button btn = new Button() { Margin = new Thickness(8, 0, 0, 0), BorderThickness = new Thickness(4, 4, 4, 4), Content = new Image() { Width = SystemParameters.PrimaryScreenWidth * 0.9f / ScreensAmount, Source = Handler.BitmapToImageSource(Handler.Bitmaps[i]) } }; btn.Click += (sender, e) => { Handler.SaveScreen(dump); Hide(); }; imgs.Children.Add(btn); } } Topmost = true; Show(); Activate(); } } public void HideWindow(bool clearData = false) { Hide(); if(clearData) { imgs.Children.Clear(); Handler.ClearData(); } } public void CloseWindow() { MessageBoxResult messageBoxResult = MessageBox.Show("Are you sure you want to quit the application?", "Exit Confirmation", System.Windows.MessageBoxButton.YesNo); if (messageBoxResult == MessageBoxResult.Yes) Close(); } void OpenCropWindow(int id) { Hide(); Handler.cropWindow = new CropWindow(); Handler.cropWindow.Id = id; Handler.cropWindow.Show(); } void OpenInfoWindow() { Hide(); Handler.infoWindow = new InfoWindow(); Handler.infoWindow.Show(); } void OpenSettingsWindow() { //MessageBox.Show("Not done yet"); //return; Hide(); Handler.settingsWindow = new SettingsWindow(); Handler.settingsWindow.Show(); } protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) { base.OnRenderSizeChanged(sizeInfo); //If the Height has changed then calc half of the the offset to move the form if (sizeInfo.HeightChanged == true) { this.Top += (sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height) / 2; } //If the Width has changed then calc half of the the offset to move the form if (sizeInfo.WidthChanged == true) { this.Left += (sizeInfo.PreviousSize.Width - sizeInfo.NewSize.Width) / 2; } } private void CloseBtn_Click(object sender, RoutedEventArgs e) { CloseWindow(); } private void HideBtn_Click(object sender, RoutedEventArgs e) { HideWindow(true); } private void SettingsBtn_Click(object sender, RoutedEventArgs e) { OpenSettingsWindow(); } private void InfoBtn_Click(object sender, RoutedEventArgs e) { OpenInfoWindow(); } } }
//------------------------------------------------------------------------------ // <copyright file="StylesEditorDialog.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.Design.MobileControls { using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Globalization; using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.Reflection; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.Design.MobileControls.Adapters; using System.Web.UI.Design.MobileControls.Util; using AttributeCollection = System.ComponentModel.AttributeCollection; using Control = System.Windows.Forms.Control; using Button = System.Windows.Forms.Button; using Label = System.Windows.Forms.Label; using TextBox = System.Windows.Forms.TextBox; using ListView = System.Windows.Forms.ListView; using ListBox = System.Windows.Forms.ListBox; using FontSize = System.Web.UI.MobileControls.FontSize; using Style = System.Web.UI.MobileControls.Style; [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal sealed class StylesEditorDialog : DesignerForm { private StyleSheet _styleSheet; private StyleSheet _tempStyleSheet; private StyleSheetDesigner _styleSheetDesigner; private Style _previewStyle; private Type _currentNewStyleType; private bool _firstActivate = true; private Button _btnOK; private Button _btnCancel; private Button _btnUp; private Button _btnDown; private Button _btnAdd; private Button _btnRemove; private TextBox _txtType; private TreeView _tvDefinedStyles; private ListView _lvAvailableStyles; private PropertyGrid _propertyBrowser; private MSHTMLHost _samplePreview; private ContextMenu _cntxtMenu; private MenuItem _cntxtMenuItem; private TreeNode _editCandidateNode = null; private StyleNode SelectedStyle { get { Debug.Assert(_tvDefinedStyles != null); return _tvDefinedStyles.SelectedNode as StyleNode; } set { Debug.Assert(_tvDefinedStyles != null); _tvDefinedStyles.SelectedNode = value; } } protected override string HelpTopic { get { return "net.Mobile.StylesEditorDialog"; } } /// <summary> /// Create a new StylesEditorDialog instance /// </summary> /// <internalonly/> internal StylesEditorDialog(StyleSheet stylesheet, StyleSheetDesigner styleSheetDesigner, String initialStyleName) : base (stylesheet.Site) { if(stylesheet.DuplicateStyles.Count > 0) { GenericUI.ShowErrorMessage( SR.GetString(SR.StylesEditorDialog_Title), SR.GetString(SR.StylesEditorDialog_DuplicateStyleNames) ); throw new ArgumentException( SR.GetString(SR.StylesEditorDialog_DuplicateStyleException) ); } _tempStyleSheet = new StyleSheet(); _previewStyle = new Style(); _styleSheet = stylesheet; _styleSheetDesigner = styleSheetDesigner; _tempStyleSheet.Site = _styleSheet.Site; InitializeComponent(); InitAvailableStyles(); LoadStyleItems(); if (_tvDefinedStyles.Nodes.Count > 0) { int initialIndex = 0; if (initialStyleName != null) { initialIndex = StyleIndex(initialStyleName); } SelectedStyle = (StyleNode)_tvDefinedStyles.Nodes[initialIndex]; _tvDefinedStyles.Enabled = true; UpdateTypeText(); UpdatePropertyGrid(); } UpdateButtonsEnabling(); UpdateFieldsEnabling(); } protected override void Dispose(bool disposing) { if(disposing) { if (_tvDefinedStyles != null) { foreach (StyleNode item in _tvDefinedStyles.Nodes) { item.Dispose(); } _tvDefinedStyles = null; } } base.Dispose(disposing); } private void InitializeComponent() { _btnOK = new Button(); _btnCancel = new Button(); _btnUp = new Button(); _btnDown = new Button(); _btnAdd = new Button(); _btnRemove = new Button(); _txtType = new TextBox(); _tvDefinedStyles = new TreeView(); _lvAvailableStyles = new ListView(); _samplePreview = new MSHTMLHost(); _propertyBrowser = new PropertyGrid(); _cntxtMenuItem = new MenuItem(); _cntxtMenu = new ContextMenu(); GroupLabel grplblStyleList = new GroupLabel(); grplblStyleList.SetBounds(6, 5, 432, 16); grplblStyleList.Text = SR.GetString(SR.StylesEditorDialog_StyleListGroupLabel); grplblStyleList.TabStop = false; grplblStyleList.TabIndex = 0; Label lblAvailableStyles = new Label(); lblAvailableStyles.SetBounds(14, 25, 180, 16); lblAvailableStyles.Text = SR.GetString(SR.StylesEditorDialog_AvailableStylesCaption); lblAvailableStyles.TabStop = false; lblAvailableStyles.TabIndex = 1; ColumnHeader chStyleType = new System.Windows.Forms.ColumnHeader(); ColumnHeader chStyleNamespace = new System.Windows.Forms.ColumnHeader(); chStyleType.Width = 16; chStyleType.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; chStyleNamespace.Width = 16; chStyleNamespace.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; _lvAvailableStyles.SetBounds(14, 41, 180, 95); _lvAvailableStyles.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; _lvAvailableStyles.MultiSelect = false; _lvAvailableStyles.HideSelection = false; _lvAvailableStyles.FullRowSelect = true; _lvAvailableStyles.View = System.Windows.Forms.View.Details; _lvAvailableStyles.Columns.AddRange(new System.Windows.Forms.ColumnHeader[2] {chStyleType, chStyleNamespace}); _lvAvailableStyles.SelectedIndexChanged += new EventHandler(this.OnNewStyleTypeChanged); _lvAvailableStyles.DoubleClick += new EventHandler(this.OnDoubleClick); _lvAvailableStyles.Sorting = SortOrder.Ascending; _lvAvailableStyles.TabIndex = 2; _lvAvailableStyles.TabStop = true; _btnAdd.AccessibleName = SR.GetString(SR.EditableTreeList_AddName); _btnAdd.AccessibleDescription = SR.GetString(SR.EditableTreeList_AddDescription); _btnAdd.Name = SR.GetString(SR.EditableTreeList_AddName); _btnAdd.SetBounds(198, 77, 32, 25); _btnAdd.Text = SR.GetString(SR.StylesEditorDialog_AddBtnCation); _btnAdd.Click += new EventHandler(this.OnClickAddButton); _btnAdd.TabIndex = 3; _btnAdd.TabStop = true; Label lblDefinedStyles = new Label(); lblDefinedStyles.SetBounds(234, 25, 166, 16); lblDefinedStyles.Text = SR.GetString(SR.StylesEditorDialog_DefinedStylesCaption); lblDefinedStyles.TabStop = false; lblDefinedStyles.TabIndex = 4;; _tvDefinedStyles.SetBounds(234, 41, 166, 95); _tvDefinedStyles.AfterSelect += new TreeViewEventHandler(OnStylesSelected); _tvDefinedStyles.AfterLabelEdit += new NodeLabelEditEventHandler(OnAfterLabelEdit); _tvDefinedStyles.LabelEdit = true; _tvDefinedStyles.ShowPlusMinus = false; _tvDefinedStyles.HideSelection = false; _tvDefinedStyles.Indent = 15; _tvDefinedStyles.ShowRootLines = false; _tvDefinedStyles.ShowLines = false; _tvDefinedStyles.ContextMenu = _cntxtMenu; _tvDefinedStyles.TabIndex = 5; _tvDefinedStyles.TabStop = true; _tvDefinedStyles.KeyDown += new KeyEventHandler(OnKeyDown); _tvDefinedStyles.MouseUp += new MouseEventHandler(OnListMouseUp); _tvDefinedStyles.MouseDown += new MouseEventHandler(OnListMouseDown); _btnUp.AccessibleName = SR.GetString(SR.EditableTreeList_MoveUpName); _btnUp.AccessibleDescription = SR.GetString(SR.EditableTreeList_MoveUpDescription); _btnUp.Name = SR.GetString(SR.EditableTreeList_MoveUpName); _btnUp.SetBounds(404, 41, 28, 27); _btnUp.Click += new EventHandler(this.OnClickUpButton); _btnUp.Image = GenericUI.SortUpIcon; _btnUp.TabIndex = 6; _btnUp.TabStop = true; _btnDown.AccessibleName = SR.GetString(SR.EditableTreeList_MoveDownName); _btnDown.AccessibleDescription = SR.GetString(SR.EditableTreeList_MoveDownDescription); _btnDown.Name = SR.GetString(SR.EditableTreeList_MoveDownName); _btnDown.SetBounds(404, 72, 28, 27); _btnDown.Click += new EventHandler(this.OnClickDownButton); _btnDown.Image = GenericUI.SortDownIcon; _btnDown.TabIndex = 7; _btnDown.TabStop = true; _btnRemove.AccessibleName = SR.GetString(SR.EditableTreeList_DeleteName); _btnRemove.AccessibleDescription = SR.GetString(SR.EditableTreeList_DeleteDescription); _btnRemove.Name = SR.GetString(SR.EditableTreeList_DeleteName); _btnRemove.SetBounds(404, 109, 28, 27); _btnRemove.Click += new EventHandler(this.OnClickRemoveButton); _btnRemove.Image = GenericUI.DeleteIcon; _btnRemove.TabIndex = 8; _btnRemove.TabStop = true; GroupLabel grplblStyleProperties = new GroupLabel(); grplblStyleProperties.SetBounds(6, 145, 432, 16); grplblStyleProperties.Text = SR.GetString(SR.StylesEditorDialog_StylePropertiesGroupLabel); grplblStyleProperties.TabStop = false; grplblStyleProperties.TabIndex = 9; Label lblType = new Label(); lblType.SetBounds(14, 165, 180, 16); lblType.Text = SR.GetString(SR.StylesEditorDialog_TypeCaption); lblType.TabIndex = 10; lblType.TabStop = false; _txtType.SetBounds(14, 181, 180, 16); _txtType.ReadOnly = true; _txtType.TabIndex = 11; _txtType.TabStop = true; Label lblSample = new Label(); lblSample.SetBounds(14, 213, 180, 16); lblSample.Text = SR.GetString(SR.StylesEditorDialog_SampleCaption); lblSample.TabStop = false; lblSample.TabIndex = 12; _samplePreview.SetBounds(14, 229, 180, 76); _samplePreview.TabStop = false; _samplePreview.TabIndex = 13; Label lblProperties = new Label(); lblProperties.SetBounds(234, 165, 198, 16); lblProperties.Text = SR.GetString(SR.StylesEditorDialog_PropertiesCaption); lblProperties.TabIndex = 14; lblProperties.TabStop = false; _propertyBrowser.SetBounds(234, 181, 198, 178); _propertyBrowser.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right; _propertyBrowser.ToolbarVisible = false; _propertyBrowser.HelpVisible = false; _propertyBrowser.TabIndex = 15; _propertyBrowser.TabStop = true; _propertyBrowser.PropertySort = PropertySort.Alphabetical; _propertyBrowser.PropertyValueChanged += new PropertyValueChangedEventHandler(this.OnPropertyValueChanged); _btnOK.DialogResult = DialogResult.OK; _btnOK.Location = new System.Drawing.Point(282, 370); _btnOK.Size = new System.Drawing.Size(75, 23); _btnOK.TabIndex = 16; _btnOK.Text = SR.GetString(SR.GenericDialog_OKBtnCaption); _btnOK.Click += new EventHandler(this.OnClickOKButton); _btnCancel.DialogResult = DialogResult.Cancel; _btnCancel.Location = new System.Drawing.Point(363, 370); _btnCancel.Size = new System.Drawing.Size(75, 23); _btnCancel.TabIndex = 17; _btnCancel.Text = SR.GetString(SR.GenericDialog_CancelBtnCaption); _cntxtMenuItem.Text = SR.GetString(SR.EditableTreeList_Rename); _cntxtMenu.MenuItems.Add(_cntxtMenuItem); _cntxtMenu.Popup += new EventHandler(OnPopup); _cntxtMenuItem.Click += new EventHandler(OnContextMenuItemClick); GenericUI.InitDialog(this, _styleSheet.Site); this.Text = _styleSheet.ID + " - " + SR.GetString(SR.StylesEditorDialog_Title); this.ClientSize = new Size(444, 401); this.AcceptButton = _btnOK; this.CancelButton = _btnCancel; this.Activated += new System.EventHandler(StylesEditorDialog_Activated); this.Controls.AddRange(new Control[] { grplblStyleList, lblAvailableStyles, _lvAvailableStyles, _btnAdd, lblDefinedStyles, _tvDefinedStyles, _btnUp, _btnDown, _btnRemove, grplblStyleProperties, lblType, _txtType, lblSample, _samplePreview, lblProperties, _propertyBrowser, _btnOK, _btnCancel, }); } private void InitAvailableStyles() { //int[] colMaxWidth = { _lvAvailableStyles.Columns[0].Width, _lvAvailableStyles.Columns[1].Width }; int[] colMaxWidth = { 68, 202 }; int[] colReqWidth = { 0, 0 }; // NOTE: Currently no way for third party extenders to add their // own styles. They'll need to specify complete name with tagprefix included. StringCollection mobileStyles = new StringCollection(); mobileStyles.AddRange( new String[2]{"System.Web.UI.MobileControls.PagerStyle", "System.Web.UI.MobileControls.Style"}); foreach (String mobileStyle in mobileStyles) { Type type = Type.GetType(mobileStyle, true); String[] subItems = {type.Name, type.Namespace}; ListViewItem item = new ListViewItem(subItems); _lvAvailableStyles.Items.Add(item); } ICollection styles = _styleSheet.Styles; foreach (String key in styles) { Style style = (Style) _styleSheet[key]; Type type = style.GetType(); if (!mobileStyles.Contains(type.FullName)) { String[] subItems = {type.Name, type.Namespace}; ListViewItem item = new ListViewItem(subItems); _lvAvailableStyles.Items.Add(item); // Rectangle rcLvi = lvi.GetBounds((int) ItemBoundsPortion.Label); // use a method like GetExtendPoint32 colReqWidth[0] = 68; if (colReqWidth[0] > colMaxWidth[0]) { colMaxWidth[0] = colReqWidth[0]; } // use a method like GetExtendPoint32 colReqWidth[1] = 202; if (colReqWidth[1] > colMaxWidth[1]) { colMaxWidth[1] = colReqWidth[1]; } } } _lvAvailableStyles.Columns[0].Width = colMaxWidth[0] + 4; _lvAvailableStyles.Columns[1].Width = colMaxWidth[1] + 4; Debug.Assert(_lvAvailableStyles.Items.Count > 0); _lvAvailableStyles.Sort(); _lvAvailableStyles.Items[0].Selected = true; _currentNewStyleType = Type.GetType((String) _lvAvailableStyles.Items[0].SubItems[1].Text + "." + _lvAvailableStyles.Items[0].Text, true); } private void SaveComponent() { // Clear old styles _styleSheet.Clear(); foreach (StyleNode styleNode in _tvDefinedStyles.Nodes) { _styleSheet[styleNode.RuntimeStyle.Name] = styleNode.RuntimeStyle; styleNode.RuntimeStyle.SetControl(_styleSheet); } // Delete CurrentStyle if it does not exist any more. if (_styleSheetDesigner.CurrentStyle != null && null == _styleSheet[_styleSheetDesigner.CurrentStyle.Name]) { _styleSheetDesigner.CurrentStyle = null; _styleSheetDesigner.CurrentChoice = null; } _styleSheetDesigner.OnStylesChanged(); } private void LoadStyleItems() { ICollection styles = _styleSheet.Styles; foreach (String key in styles) { Style style = (Style) _styleSheet[key]; Style newStyle = (Style) Activator.CreateInstance(style.GetType()); PropertyDescriptorCollection propDescs = TypeDescriptor.GetProperties(style); for (int i = 0; i < propDescs.Count; i++) { if (propDescs[i].Name.Equals("Font")) { foreach (PropertyDescriptor desc in TypeDescriptor.GetProperties(style.Font)) { desc.SetValue(newStyle.Font, desc.GetValue(style.Font)); } } else if (!propDescs[i].IsReadOnly) { propDescs[i].SetValue(newStyle, propDescs[i].GetValue(style)); } } _tempStyleSheet[newStyle.Name] = newStyle; newStyle.SetControl(_tempStyleSheet); StyleNode newStyleItem = new StyleNode(newStyle); _tvDefinedStyles.Nodes.Add(newStyleItem); } } private void UpdateButtonsEnabling() { if (SelectedStyle == null) { _btnUp.Enabled = false; _btnDown.Enabled = false; } else { _btnUp.Enabled = (SelectedStyle.Index > 0); _btnDown.Enabled = (SelectedStyle.Index < _tvDefinedStyles.Nodes.Count - 1); } _btnRemove.Enabled = (SelectedStyle != null); } private void UpdateFieldsEnabling() { _propertyBrowser.Enabled = _tvDefinedStyles.Enabled = (SelectedStyle != null); } private String AutoIDStyle() { String newStyleID = _currentNewStyleType.Name; int i = 1; while (StyleIndex(newStyleID + i.ToString(CultureInfo.InvariantCulture)) >= 0) { i++; } return newStyleID + i.ToString(CultureInfo.InvariantCulture); } private int StyleIndex(String name) { int index = 0; foreach (StyleNode styleNode in _tvDefinedStyles.Nodes) { if (String.Compare(name, styleNode.RuntimeStyle.Name, StringComparison.OrdinalIgnoreCase) == 0) { return index; } index++; } return -1; } private void UpdatePropertyGrid() { _propertyBrowser.SelectedObject = (SelectedStyle == null) ? null : ((StyleNode)SelectedStyle).RuntimeStyle; } private void UpdateTypeText() { if (SelectedStyle == null) { _txtType.Text = String.Empty; } else { _txtType.Text = ((StyleNode)SelectedStyle).FullName; } } /// <summary> /// Update scheme preview /// </summary> /// <internalonly/> private void UpdateSamplePreview() { if (_firstActivate) { return; } NativeMethods.IHTMLDocument2 tridentDocument = _samplePreview.GetDocument(); NativeMethods.IHTMLElement documentElement = tridentDocument.GetBody(); NativeMethods.IHTMLBodyElement bodyElement; bodyElement = (NativeMethods.IHTMLBodyElement) documentElement; bodyElement.SetScroll("no"); if (SelectedStyle == null) { documentElement.SetInnerHTML(String.Empty); tridentDocument.SetBgColor("buttonface"); return; } else { tridentDocument.SetBgColor(String.Empty); } bool cycle = ReferencesContainCycle(SelectedStyle); if (cycle) { documentElement.SetInnerHTML(String.Empty); return; } // apply the current Style to label ApplyStyle(); DesignerTextWriter tw = new DesignerTextWriter(); //ToolTip tw.AddAttribute("title", ((StyleNode)SelectedStyle).RuntimeStyle.Name); // ForeColor Color c = _previewStyle.ForeColor; if (!c.Equals(Color.Empty)) { tw.AddStyleAttribute("color", ColorTranslator.ToHtml(c)); } // BackColor c = _previewStyle.BackColor; if (!c.Equals(Color.Empty)) { tw.AddStyleAttribute("background-color", ColorTranslator.ToHtml(c)); } // Font Name String name = _previewStyle.Font.Name; if (name.Length > 0) { tw.AddStyleAttribute("font-family", name); } // Font Size switch (_previewStyle.Font.Size) { case FontSize.Large : tw.AddStyleAttribute("font-size", "Medium"); break; case FontSize.Small : tw.AddStyleAttribute("font-size", "X-Small"); break; default: tw.AddStyleAttribute("font-size", "Small"); break; } // Font Style if (_previewStyle.Font.Bold == BooleanOption.True) { tw.AddStyleAttribute("font-weight", "bold"); } if (_previewStyle.Font.Italic == BooleanOption.True) { tw.AddStyleAttribute("font-style", "italic"); } tw.RenderBeginTag("span"); tw.Write(SR.GetString(SR.StylesEditorDialog_PreviewText)); tw.RenderEndTag(); // and show it! String finalHTML = "<div align='center'><table width='100%' height='100%'><tr><td><p align='center'>" + tw.ToString() + "</p></td></tr></table></div>"; documentElement.SetInnerHTML(finalHTML); } /* * BEGIN EVENT HANDLING */ Timer _delayTimer; private void StylesEditorDialog_Activated(Object sender, System.EventArgs e) { if (!_firstActivate) { return; } _firstActivate = false; _samplePreview.CreateTrident(); _samplePreview.ActivateTrident(); UpdateSamplePreview(); _delayTimer = new Timer(); _delayTimer.Interval = 100; _delayTimer.Tick += new EventHandler(this.OnActivateDefinedStyles); _delayTimer.Start(); } private void OnActivateDefinedStyles(Object sender, System.EventArgs e) { _delayTimer.Stop(); _delayTimer.Tick -= new EventHandler(this.OnActivateDefinedStyles); _lvAvailableStyles.Focus(); } internal delegate void StyleRenamedEventHandler( Object source, StyleRenamedEventArgs e); internal event StyleRenamedEventHandler StyleRenamed; private void OnStyleRenamed(StyleRenamedEventArgs e) { if(StyleRenamed != null) { StyleRenamed(this, e); } } private void OnAfterLabelEdit(Object source, NodeLabelEditEventArgs e) { Debug.Assert(null != e); Debug.Assert(e.CancelEdit == false); // this happens when the label is unchanged after entering and exiting // label editing mode - bizarre behavior. this may be a bug in treeview if (null == e.Label) { return; } String oldValue = e.Node.Text; String newValue = e.Label; String messageTitle = SR.GetString(SR.Style_ErrorMessageTitle); // can't accept a style name that already exists if (String.Compare(oldValue, newValue , StringComparison.OrdinalIgnoreCase) != 0 && StyleIndex(newValue) >= 0) { MessageBox.Show( SR.GetString(SR.Style_DuplicateName), messageTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); e.CancelEdit = true; return; } // can't accept an empty style name if (newValue.Length == 0) { MessageBox.Show( SR.GetString(SR.StylesEditorDialog_EmptyName), messageTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); e.CancelEdit = true; return; } /* Removed for DCR 4240 // can't accept an illegal style name if (!DesignerUtility.IsValidName(newValue)) { MessageBox.Show( SR.GetString(SR.Style_InvalidName, newValue), messageTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); e.CancelEdit = true; return; } */ SelectedStyle.RuntimeStyle.Name = newValue; _tempStyleSheet.Remove(oldValue); _tempStyleSheet[newValue] = SelectedStyle.RuntimeStyle; if (ReferencesContainCycle(SelectedStyle)) { // Restore original settings SelectedStyle.RuntimeStyle.Name = oldValue; _tempStyleSheet.Remove(newValue); _tempStyleSheet[oldValue] = SelectedStyle.RuntimeStyle; MessageBox.Show( SR.GetString(SR.Style_NameChangeCauseCircularLoop), messageTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); e.CancelEdit = true; return; } // Raise StyleRenamed event for any styles which vere // renamed. OnStyleRenamed( new StyleRenamedEventArgs( oldValue, newValue ) ); } private void OnCreateNewStyle() { String newStyleAutoID = AutoIDStyle(); Style newStyle = (Style)Activator.CreateInstance(_currentNewStyleType); Debug.Assert(newStyle != null); newStyle.Name = newStyleAutoID; // Add this style to StyleSheet _tempStyleSheet[newStyle.Name] = newStyle; newStyle.SetControl(_tempStyleSheet); StyleNode newStyleItem = new StyleNode(newStyle); _tvDefinedStyles.Enabled = true; _propertyBrowser.Enabled = true; _tvDefinedStyles.Nodes.Add(newStyleItem); SelectedStyle = newStyleItem; UpdateSamplePreview(); UpdateButtonsEnabling(); } private void OnClickOKButton(Object sender, EventArgs e) { SaveComponent(); Close(); DialogResult = DialogResult.OK; } private void OnStylesSelected(Object sender, TreeViewEventArgs e) { UpdateTypeText(); UpdatePropertyGrid(); UpdateSamplePreview(); UpdateButtonsEnabling(); UpdateFieldsEnabling(); } private void OnNewStyleTypeChanged(Object sender, EventArgs e) { if (_lvAvailableStyles.SelectedItems.Count != 0) { _currentNewStyleType = Type.GetType((String) _lvAvailableStyles.SelectedItems[0].SubItems[1].Text + "." + _lvAvailableStyles.SelectedItems[0].Text, true); //Debug.Assert(typeof(Style).IsAssignableFrom(_currentNewStyleType), "Non style object passed in."); } } private void MoveSelectedNode(int direction) { Debug.Assert(direction == 1 || direction == -1); StyleNode node = SelectedStyle; Debug.Assert(node != null); int index = node.Index; _tvDefinedStyles.Nodes.RemoveAt(index); _tvDefinedStyles.Nodes.Insert(index + direction, node); SelectedStyle = node; } private void OnClickUpButton(Object source, EventArgs e) { MoveSelectedNode(-1); UpdateButtonsEnabling(); } private void OnClickDownButton(Object source, EventArgs e) { MoveSelectedNode(1); UpdateButtonsEnabling(); } private void OnClickAddButton(Object sender, EventArgs e) { OnCreateNewStyle(); } internal delegate void StyleDeletedEventHandler( Object source, StyleDeletedEventArgs e); internal event StyleDeletedEventHandler StyleDeleted; private void OnStyleDeleted(StyleDeletedEventArgs e) { if(StyleDeleted != null) { StyleDeleted(this, e); } } private void OnClickRemoveButton(Object source, EventArgs e) { Debug.Assert(SelectedStyle != null); String message = SR.GetString(SR.StylesEditorDialog_DeleteStyleMessage); String caption = SR.GetString(SR.StylesEditorDialog_DeleteStyleCaption); if (System.Windows.Forms.MessageBox.Show(message, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No) { return; } String deletedStyle = ((StyleNode)SelectedStyle).RuntimeStyle.Name; // Remove this style from temporary StyleSheet _tempStyleSheet.Remove(deletedStyle); ((StyleNode)SelectedStyle).Dispose(); int selectedIndex = SelectedStyle.Index; int stylesCount = _tvDefinedStyles.Nodes.Count; _tvDefinedStyles.Nodes.RemoveAt(selectedIndex); OnStyleDeleted(new StyleDeletedEventArgs(deletedStyle)); if (selectedIndex < stylesCount-1) { SelectedStyle = (StyleNode) _tvDefinedStyles.Nodes[selectedIndex]; } else if (selectedIndex >= 1) { SelectedStyle = (StyleNode) _tvDefinedStyles.Nodes[selectedIndex-1]; } else if (stylesCount == 1) { SelectedStyle = null; UpdateTypeText(); UpdatePropertyGrid(); UpdateSamplePreview(); UpdateButtonsEnabling(); UpdateFieldsEnabling(); } } private void OnDoubleClick(Object sender, EventArgs e) { OnCreateNewStyle(); } private void OnKeyDown(Object sender, KeyEventArgs e) { switch(e.KeyData) { case Keys.F2: { if(SelectedStyle != null) { SelectedStyle.BeginEdit(); } break; } case (Keys.Control | Keys.Home): { if(_tvDefinedStyles.Nodes.Count > 0) { SelectedStyle = (StyleNode)_tvDefinedStyles.Nodes[0]; } break; } case (Keys.Control | Keys.End): { int numNodes = _tvDefinedStyles.Nodes.Count; if(numNodes > 0) { SelectedStyle = (StyleNode)_tvDefinedStyles.Nodes[numNodes - 1]; } break; } } } private void OnListMouseUp(Object sender, MouseEventArgs e) { _editCandidateNode= null; if (e.Button == MouseButtons.Right) { _editCandidateNode = (TreeNode)_tvDefinedStyles.GetNodeAt (e.X, e.Y); } } private void OnListMouseDown(Object sender, MouseEventArgs e) { _editCandidateNode = null; if (e.Button == MouseButtons.Right) { _editCandidateNode = (TreeNode)_tvDefinedStyles.GetNodeAt (e.X, e.Y); } } private void OnPopup(Object sender, EventArgs e) { _cntxtMenuItem.Enabled = (_editCandidateNode != null || _tvDefinedStyles.SelectedNode != null); } private void OnContextMenuItemClick(Object sender, EventArgs e) { if(_editCandidateNode == null) { // context menu key pressed if (_tvDefinedStyles.SelectedNode != null) { _tvDefinedStyles.SelectedNode.BeginEdit(); } } else { // right mouseclick _editCandidateNode.BeginEdit(); } _editCandidateNode = null; } private void OnPropertyValueChanged(Object sender, PropertyValueChangedEventArgs e) { if (SelectedStyle == null) { return; } UpdateSamplePreview(); } /* * END EVENT HANDLING */ private bool ReferencesContainCycle(StyleNode startingStyleItem) { StyleNode currentStyleItem = startingStyleItem; Style currentStyle = currentStyleItem.RuntimeStyle; String reference = currentStyle.StyleReference; bool found = true; bool cycle = false; // Clear referenced boolean foreach (StyleNode styleNode in _tvDefinedStyles.Nodes) { styleNode.Referenced = false; } // Set current style as referenced. currentStyleItem.Referenced = true; while ((reference != null && reference.Length > 0) && found && !cycle) { found = false; foreach (StyleNode styleNode in _tvDefinedStyles.Nodes) { Style style = styleNode.RuntimeStyle; if (0 == String.Compare(style.Name, reference, StringComparison.OrdinalIgnoreCase)) { reference = style.StyleReference; found = true; if (styleNode.Referenced) { cycle = true; } else { styleNode.Referenced = true; } break; } } // keep on looking. // It depends on whether a style defined in web.config can have a reference or not. /* if we do need to keep on looking we need to store the Referenced flag // for those styles as well. // If not found, check default styles if (!found) { if (null != StyleSheet.Default[reference]) { Style style = StyleSheet.Default[reference]; reference = style.Reference; found = true; // get styleNode from other list if (styleNode.Referenced) { cycle = true; } else { styleNode.Referenced = true; } break; } } */ } return cycle; } /// <summary> /// Apply the currently selected style to the preview label. /// This function should only be called after making sure that there is no /// cycle that starts with _tvDefinedStyles.SelectedItem /// </summary> private void ApplyStyle() { StyleNode currentStyleItem = (StyleNode)SelectedStyle; Style currentStyle = currentStyleItem.RuntimeStyle; Color foreColor = currentStyle.ForeColor; Color backColor = currentStyle.BackColor; BooleanOption fontBold = currentStyle.Font.Bold; BooleanOption fontItalic = currentStyle.Font.Italic; FontSize fontSize = currentStyle.Font.Size; String fontName = currentStyle.Font.Name; String reference = currentStyle.StyleReference; bool found = true; while ((reference != null && reference.Length > 0) && found) { found = false; foreach (StyleNode styleNode in _tvDefinedStyles.Nodes) { Style style = styleNode.RuntimeStyle; if (0 == String.Compare(style.Name, reference, StringComparison.OrdinalIgnoreCase)) { if (foreColor == Color.Empty) { foreColor = style.ForeColor; } if (backColor == Color.Empty) { backColor = style.BackColor; } if (fontBold == BooleanOption.NotSet) { fontBold = style.Font.Bold; } if (fontItalic == BooleanOption.NotSet) { fontItalic = style.Font.Italic; } if (fontSize == FontSize.NotSet) { fontSize = style.Font.Size; } if (fontName.Length == 0) { fontName = style.Font.Name; } reference = style.StyleReference; found = true; break; } } // If not found, check default styles if (!found) { if (null != StyleSheet.Default[reference]) { Style style = StyleSheet.Default[reference]; if (foreColor == Color.Empty) { foreColor = style.ForeColor; } if (backColor == Color.Empty) { backColor = style.BackColor; } if (fontBold == BooleanOption.NotSet) { fontBold = style.Font.Bold; } if (fontItalic == BooleanOption.NotSet) { fontItalic = style.Font.Italic; } if (fontSize == FontSize.NotSet) { fontSize = style.Font.Size; } if (fontName.Length == 0) { fontName = style.Font.Name; } reference = null; found = true; break; } } } _previewStyle.ForeColor = foreColor; _previewStyle.BackColor = backColor; _previewStyle.Font.Name = fontName; _previewStyle.Font.Size = fontSize; _previewStyle.Font.Bold = fontBold; _previewStyle.Font.Italic = fontItalic; } /* * BEGIN INTERNAL CLASS */ [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] private class StyleNode : TreeNode { private String _fullName; private bool _referenced; private Style _runtimeStyle; private EventHandler _styleReferenceChanged; private String _styleReference; internal StyleNode(Style style) { _runtimeStyle = style; _fullName = style.GetType().FullName; _styleReference = RuntimeStyle.StyleReference; _styleReferenceChanged = new EventHandler(this.OnStyleReferenceChanged); base.Text = RuntimeStyle.Name; PropertyDescriptor property; property = TypeDescriptor.GetProperties(typeof(Style))["StyleReference"]; Debug.Assert(property != null); property.AddValueChanged(RuntimeStyle, _styleReferenceChanged); } internal Style RuntimeStyle { get { return _runtimeStyle; } } internal bool Referenced { get { return _referenced; } set { _referenced = value; } } internal String FullName { get { return _fullName; } } internal void Dispose() { PropertyDescriptor property; property = TypeDescriptor.GetProperties(typeof(Style))["StyleReference"]; Debug.Assert(property != null); property.RemoveValueChanged(RuntimeStyle, _styleReferenceChanged); } // Note that it return false if any of the referenced styles are already in a loop // ie. it returns true if and only if current style is in a loop now. private bool InCircularLoop() { StyleSheet styleSheet = (StyleSheet)RuntimeStyle.Control; Debug.Assert(styleSheet != null); String reference = RuntimeStyle.StyleReference; int count = styleSheet.Styles.Count + 1; while ((reference != null && reference.Length > 0) && count > 0) { if (0 == String.Compare(RuntimeStyle.Name, reference, StringComparison.OrdinalIgnoreCase)) { return true; } else { Style style = styleSheet[reference]; if (null != style) { reference = style.StyleReference; count --; } else { reference = null; } } } return false; } private void OnStyleReferenceChanged(Object sender, EventArgs e) { if (InCircularLoop()) { RestoreStyleReference(); // new style reference creates a cycle throw new Exception(SR.GetString(SR.Style_ReferenceCauseCircularLoop)); } CacheStyleReference(); } private void RestoreStyleReference() { RuntimeStyle.StyleReference = _styleReference; } private void CacheStyleReference() { _styleReference = RuntimeStyle.StyleReference; } } } [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal sealed class StyleRenamedEventArgs : EventArgs { private String _oldName; private String _newName; internal StyleRenamedEventArgs( String oldName, String newName) { _oldName = oldName; _newName = newName; } internal String OldName { get { return _oldName; } } internal String NewName { get { return _newName; } } } [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal sealed class StyleDeletedEventArgs : EventArgs { private String _name; internal StyleDeletedEventArgs(String name) { _name = name; } internal String Name { get { return _name; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.HDInsight; using Microsoft.Azure.Management.HDInsight.Models; namespace Microsoft.Azure.Management.HDInsight { /// <summary> /// The HDInsight Management Client. /// </summary> public static partial class ClusterOperationsExtensions { /// <summary> /// Begins configuring the HTTP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='httpSettingsParameters'> /// Required. The name of the resource group. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightOperationResponse BeginConfiguringHttpSettings(this IClusterOperations operations, string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).BeginConfiguringHttpSettingsAsync(resourceGroupName, clusterName, httpSettingsParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins configuring the HTTP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='httpSettingsParameters'> /// Required. The name of the resource group. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightOperationResponse> BeginConfiguringHttpSettingsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters) { return operations.BeginConfiguringHttpSettingsAsync(resourceGroupName, clusterName, httpSettingsParameters, CancellationToken.None); } /// <summary> /// Begins configuring the RDP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='rdpParameters'> /// Required. The OS profile for RDP. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightOperationResponse BeginConfiguringRdpSettings(this IClusterOperations operations, string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).BeginConfiguringRdpSettingsAsync(resourceGroupName, clusterName, rdpParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins configuring the RDP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='rdpParameters'> /// Required. The OS profile for RDP. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightOperationResponse> BeginConfiguringRdpSettingsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters) { return operations.BeginConfiguringRdpSettingsAsync(resourceGroupName, clusterName, rdpParameters, CancellationToken.None); } /// <summary> /// Begins creating a new HDInsight cluster with the specified /// parameters. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='clusterCreateParameters'> /// Required. The cluster create request. /// </param> /// <returns> /// The CreateCluster operation response. /// </returns> public static ClusterCreateResponse BeginCreating(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).BeginCreatingAsync(resourceGroupName, clusterName, clusterCreateParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins creating a new HDInsight cluster with the specified /// parameters. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='clusterCreateParameters'> /// Required. The cluster create request. /// </param> /// <returns> /// The CreateCluster operation response. /// </returns> public static Task<ClusterCreateResponse> BeginCreatingAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters) { return operations.BeginCreatingAsync(resourceGroupName, clusterName, clusterCreateParameters, CancellationToken.None); } /// <summary> /// Begins deleting the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightOperationResponse BeginDeleting(this IClusterOperations operations, string resourceGroupName, string clusterName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).BeginDeletingAsync(resourceGroupName, clusterName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins deleting the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightOperationResponse> BeginDeletingAsync(this IClusterOperations operations, string resourceGroupName, string clusterName) { return operations.BeginDeletingAsync(resourceGroupName, clusterName, CancellationToken.None); } /// <summary> /// Begins a resize operation on the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='resizeParameters'> /// Required. The parameters for the resize operation. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightOperationResponse BeginResizing(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).BeginResizingAsync(resourceGroupName, clusterName, resizeParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins a resize operation on the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='resizeParameters'> /// Required. The parameters for the resize operation. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightOperationResponse> BeginResizingAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters) { return operations.BeginResizingAsync(resourceGroupName, clusterName, resizeParameters, CancellationToken.None); } /// <summary> /// Configures the HTTP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='httpSettingsParameters'> /// Required. The name of the resource group. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightLongRunningOperationResponse ConfigureHttpSettings(this IClusterOperations operations, string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ConfigureHttpSettingsAsync(resourceGroupName, clusterName, httpSettingsParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Configures the HTTP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='httpSettingsParameters'> /// Required. The name of the resource group. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightLongRunningOperationResponse> ConfigureHttpSettingsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters) { return operations.ConfigureHttpSettingsAsync(resourceGroupName, clusterName, httpSettingsParameters, CancellationToken.None); } /// <summary> /// Configures the RDP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='rdpParameters'> /// Required. The OS profile for RDP. Use null to turn RDP off. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightLongRunningOperationResponse ConfigureRdpSettings(this IClusterOperations operations, string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ConfigureRdpSettingsAsync(resourceGroupName, clusterName, rdpParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Configures the RDP settings on the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='rdpParameters'> /// Required. The OS profile for RDP. Use null to turn RDP off. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightLongRunningOperationResponse> ConfigureRdpSettingsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters) { return operations.ConfigureRdpSettingsAsync(resourceGroupName, clusterName, rdpParameters, CancellationToken.None); } /// <summary> /// Creates a new HDInsight cluster with the specified parameters. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='clusterCreateParameters'> /// Required. The cluster create request. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static ClusterGetResponse Create(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).CreateAsync(resourceGroupName, clusterName, clusterCreateParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a new HDInsight cluster with the specified parameters. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='clusterCreateParameters'> /// Required. The cluster create request. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static Task<ClusterGetResponse> CreateAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters) { return operations.CreateAsync(resourceGroupName, clusterName, clusterCreateParameters, CancellationToken.None); } /// <summary> /// Deletes the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static ClusterGetResponse Delete(this IClusterOperations operations, string resourceGroupName, string clusterName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).DeleteAsync(resourceGroupName, clusterName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static Task<ClusterGetResponse> DeleteAsync(this IClusterOperations operations, string resourceGroupName, string clusterName) { return operations.DeleteAsync(resourceGroupName, clusterName, CancellationToken.None); } /// <summary> /// Gets the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static ClusterGetResponse Get(this IClusterOperations operations, string resourceGroupName, string clusterName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetAsync(resourceGroupName, clusterName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static Task<ClusterGetResponse> GetAsync(this IClusterOperations operations, string resourceGroupName, string clusterName) { return operations.GetAsync(resourceGroupName, clusterName, CancellationToken.None); } /// <summary> /// Gets the capabilities for the specified location. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='location'> /// Required. The location to get capabilities for. /// </param> /// <returns> /// The Get Capabilities operation response. /// </returns> public static CapabilitiesResponse GetCapabilities(this IClusterOperations operations, string location) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetCapabilitiesAsync(location); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the capabilities for the specified location. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='location'> /// Required. The location to get capabilities for. /// </param> /// <returns> /// The Get Capabilities operation response. /// </returns> public static Task<CapabilitiesResponse> GetCapabilitiesAsync(this IClusterOperations operations, string location) { return operations.GetCapabilitiesAsync(location, CancellationToken.None); } /// <summary> /// Gets the connectivity settings for the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The payload for a Configure HTTP settings request. /// </returns> public static HttpConnectivitySettings GetConnectivitySettings(this IClusterOperations operations, string resourceGroupName, string clusterName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetConnectivitySettingsAsync(resourceGroupName, clusterName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the connectivity settings for the specified cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <returns> /// The payload for a Configure HTTP settings request. /// </returns> public static Task<HttpConnectivitySettings> GetConnectivitySettingsAsync(this IClusterOperations operations, string resourceGroupName, string clusterName) { return operations.GetConnectivitySettingsAsync(resourceGroupName, clusterName, CancellationToken.None); } /// <summary> /// Gets the status of the Create operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static ClusterGetResponse GetCreateStatus(this IClusterOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetCreateStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the status of the Create operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static Task<ClusterGetResponse> GetCreateStatusAsync(this IClusterOperations operations, string operationStatusLink) { return operations.GetCreateStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Gets the status of the Delete operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static ClusterGetResponse GetDeleteStatus(this IClusterOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).GetDeleteStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the status of the Delete operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> public static Task<ClusterGetResponse> GetDeleteStatusAsync(this IClusterOperations operations, string operationStatusLink) { return operations.GetDeleteStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Lists HDInsight clusters under the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <returns> /// The List Cluster operation response. /// </returns> public static ClusterListResponse List(this IClusterOperations operations) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists HDInsight clusters under the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <returns> /// The List Cluster operation response. /// </returns> public static Task<ClusterListResponse> ListAsync(this IClusterOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// List the HDInsight clusters in a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// The List Cluster operation response. /// </returns> public static ClusterListResponse ListByResourceGroup(this IClusterOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ListByResourceGroupAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List the HDInsight clusters in a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// The List Cluster operation response. /// </returns> public static Task<ClusterListResponse> ListByResourceGroupAsync(this IClusterOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Resizes the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='resizeParameters'> /// Required. The parameters for the resize operation. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static HDInsightLongRunningOperationResponse Resize(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters) { return Task.Factory.StartNew((object s) => { return ((IClusterOperations)s).ResizeAsync(resourceGroupName, clusterName, resizeParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Resizes the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.IClusterOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='clusterName'> /// Required. The name of the cluster. /// </param> /// <param name='resizeParameters'> /// Required. The parameters for the resize operation. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> public static Task<HDInsightLongRunningOperationResponse> ResizeAsync(this IClusterOperations operations, string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters) { return operations.ResizeAsync(resourceGroupName, clusterName, resizeParameters, CancellationToken.None); } } }
// 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.Xml; using System.Xml.Linq; using Microsoft.Test.ModuleCore; using Xunit; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { //[TestCase(Name = "ReadState", Desc = "ReadState")] public partial class TCReadState : BridgeHelpers { //[Variation("XmlReader ReadState Initial", Priority = 0)] public void ReadState1() { XDocument doc = new XDocument(); XmlReader r = doc.CreateReader(); if (r.ReadState != ReadState.Initial) throw new TestFailedException(""); } //[Variation("XmlReader ReadState Interactive", Priority = 0)] public void ReadState2() { XDocument doc = XDocument.Parse("<a/>"); XmlReader r = doc.CreateReader(); while (r.Read()) { if (r.ReadState != ReadState.Interactive) throw new TestFailedException(""); else return; } if (r.ReadState != ReadState.EndOfFile) throw new TestFailedException(""); } //[Variation("XmlReader ReadState EndOfFile", Priority = 0)] public void ReadState3() { XDocument doc = new XDocument(); XmlReader r = doc.CreateReader(); while (r.Read()) { }; if (r.ReadState != ReadState.EndOfFile) throw new TestFailedException(""); } //[Variation("XmlReader ReadState Initial", Priority = 0)] public void ReadState4() { XDocument doc = XDocument.Parse("<a/>"); XmlReader r = doc.CreateReader(); try { r.ReadContentAsInt(); } catch (InvalidOperationException) { } if (r.ReadState != ReadState.Initial) throw new TestFailedException(""); } //[Variation("XmlReader ReadState EndOfFile", Priority = 0)] public void ReadState5() { XDocument doc = XDocument.Parse("<a/>"); XmlReader r = doc.CreateReader(); while (r.Read()) { }; try { r.ReadContentAsInt(); } catch (InvalidOperationException) { } if (r.ReadState != ReadState.EndOfFile) throw new TestFailedException(""); } } //[TestCase(Name = "ReadInnerXml", Desc = "ReadInnerXml")] public partial class TCReadInnerXml : BridgeHelpers { void VerifyNextNode(XmlReader DataReader, XmlNodeType nt, string name, string value) { while (DataReader.NodeType == XmlNodeType.Whitespace || DataReader.NodeType == XmlNodeType.SignificantWhitespace) { // skip all whitespace nodes // if EOF is reached NodeType=None DataReader.Read(); } TestLog.Compare(VerifyNode(DataReader, nt, name, value), "VerifyNextNode"); } //[Variation("ReadInnerXml on Empty Tag", Priority = 0)] public void TestReadInnerXml1() { bool bPassed = false; String strExpected = String.Empty; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("ReadInnerXml on non Empty Tag", Priority = 0)] public void TestReadInnerXml2() { bool bPassed = false; String strExpected = String.Empty; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY2"); bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("ReadInnerXml on non Empty Tag with text content", Priority = 0)] public void TestReadInnerXml3() { bool bPassed = false; String strExpected = "ABCDE"; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONEMPTY1"); bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("ReadInnerXml with multiple Level of elements")] public void TestReadInnerXml6() { bool bPassed = false; String strExpected; strExpected = "<ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 />"; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "SKIP3"); bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc); VerifyNextNode(DataReader, XmlNodeType.Element, "AFTERSKIP3", String.Empty); BoolToLTMResult(bPassed); } //[Variation("ReadInnerXml with multiple Level of elements, text and attributes", Priority = 0)] public void TestReadInnerXml7() { bool bPassed = false; String strExpected = "<e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1>"; strExpected = strExpected.Replace('\'', '"'); XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "CONTENT"); bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("ReadInnerXml with with entity references, EntityHandling = ExpandEntities")] public void TestReadInnerXml8() { bool bPassed = false; String strExpected = ST_EXPAND_ENTITIES2; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_ENTTEST_NAME); bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc); VerifyNextNode(DataReader, XmlNodeType.Element, "ENTITY2", String.Empty); BoolToLTMResult(bPassed); } //[Variation("ReadInnerXml on attribute node", Priority = 0)] public void TestReadInnerXml9() { bool bPassed = false; String strExpected = "a1value"; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ATTRIBUTE2"); bPassed = DataReader.MoveToFirstAttribute(); bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc); VerifyNextNode(DataReader, XmlNodeType.Attribute, "a1", strExpected); BoolToLTMResult(bPassed); } //[Variation("ReadInnerXml on attribute node with entity reference in value", Priority = 0)] public void TestReadInnerXml10() { bool bPassed = false; string strExpected = ST_ENT1_ATT_EXPAND_CHAR_ENTITIES4; string strExpectedAttValue = ST_ENT1_ATT_EXPAND_ENTITIES; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_ENTTEST_NAME); bPassed = DataReader.MoveToFirstAttribute(); bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc); VerifyNextNode(DataReader, XmlNodeType.Attribute, "att1", strExpectedAttValue); BoolToLTMResult(bPassed); } //[Variation("ReadInnerXml on Text", Priority = 0)] public void TestReadInnerXml11() { XmlNodeType nt; string name; string value; XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Text); TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc); // save status and compare with Read nt = DataReader.NodeType; name = DataReader.Name; value = DataReader.Value; DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Text); DataReader.Read(); TestLog.Compare(VerifyNode(DataReader, nt, name, value), "vn"); } //[Variation("ReadInnerXml on CDATA")] public void TestReadInnerXml12() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.CDATA)) { TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc); return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadInnerXml on ProcessingInstruction")] public void TestReadInnerXml13() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.ProcessingInstruction)) { TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc); return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadInnerXml on Comment")] public void TestReadInnerXml14() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.Comment)) { TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc); return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadInnerXml on EndElement")] public void TestReadInnerXml16() { XmlReader DataReader = GetReader(); FindNodeType(DataReader, XmlNodeType.EndElement); TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc); } //[Variation("ReadInnerXml on XmlDeclaration")] public void TestReadInnerXml17() { XmlReader DataReader = GetReader(); TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc); } //[Variation("Current node after ReadInnerXml on element", Priority = 0)] public void TestReadInnerXml18() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "SKIP2"); DataReader.ReadInnerXml(); TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "AFTERSKIP2", String.Empty), true, "VN"); } //[Variation("Current node after ReadInnerXml on element")] public void TestReadInnerXml19() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "MARKUP"); TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, "RIX"); TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Text, String.Empty, "yyy"), true, "VN"); } //[Variation("ReadInnerXml with with entity references, EntityHandling = ExpandCharEntites")] public void TestTextReadInnerXml2() { bool bPassed = false; String strExpected = ST_EXPAND_ENTITIES2; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_ENTTEST_NAME); bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("ReadInnerXml on EntityReference")] public void TestTextReadInnerXml4() { XmlReader DataReader = GetReader(); TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc); } //[Variation("ReadInnerXml on EndEntity")] public void TestTextReadInnerXml5() { XmlReader DataReader = GetReader(); TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc); } //[Variation("One large element")] public void TestTextReadInnerXml18() { String strp = "a "; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; string strxml = "<Name a=\"b\">" + strp + "</Name>"; XmlReader DataReader = GetReaderStr(strxml); DataReader.Read(); TestLog.Compare(DataReader.ReadInnerXml(), strp, "rix"); } } //[TestCase(Name = "MoveToContent", Desc = "MoveToContent")] public partial class TCMoveToContent : BridgeHelpers { public const String ST_TEST_NAME1 = "GOTOCONTENT"; public const String ST_TEST_NAME2 = "SKIPCONTENT"; public const String ST_TEST_NAME3 = "MIXCONTENT"; public const String ST_TEST_TEXT = "some text"; public const String ST_TEST_CDATA = "cdata info"; //[Variation("MoveToContent on Skip XmlDeclaration", Priority = 0)] public void TestMoveToContent1() { XmlReader DataReader = GetReader(); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc); TestLog.Compare(DataReader.Name, "PLAY", Variation.Desc); } //[Variation("MoveToContent on Read through All valid Content Node(Element, Text, CDATA, and EndElement)", Priority = 0)] public void TestMoveToContent2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_NAME1); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc); TestLog.Compare(DataReader.Name, ST_TEST_NAME1, "Element name"); DataReader.Read(); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text"); TestLog.Compare(DataReader.ReadContentAsString(), ST_TEST_TEXT + ST_TEST_CDATA, "Read String"); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.EndElement, "Move to EndElement"); TestLog.Compare(DataReader.Name, ST_TEST_NAME1, "EndElement value"); } //[Variation("MoveToContent on Read through All invalid Content Node(PI, Comment and whitespace)", Priority = 0)] public void TestMoveToContent3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_NAME2); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc); TestLog.Compare(DataReader.Name, ST_TEST_NAME2, "Element name"); DataReader.Read(); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text"); TestLog.Compare(DataReader.Name, "", "EndElement value"); } //[Variation("MoveToContent on Read through Mix valid and Invalid Content Node")] public void TestMoveToContent4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_NAME3); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc); TestLog.Compare(DataReader.Name, ST_TEST_NAME3, "Element name"); DataReader.Read(); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text"); DataReader.Read(); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text"); TestLog.Compare(DataReader.Value, ST_TEST_TEXT, "text value"); DataReader.Read(); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.CDATA, "Move to CDATA"); TestLog.Compare(DataReader.Name, "", "CDATA value"); DataReader.Read(); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.EndElement, "Move to EndElement"); TestLog.Compare(DataReader.Name, ST_TEST_NAME3, "EndElement value"); } //[Variation("MoveToContent on Attribute", Priority = 0)] public void TestMoveToContent5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_NAME1); PositionOnNodeType(DataReader, XmlNodeType.Attribute); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, "Move to EndElement"); TestLog.Compare(DataReader.Name, ST_TEST_NAME2, "EndElement value"); } } //[TestCase(Name = "IsStartElement", Desc = "IsStartElement")] public partial class TCIsStartElement : BridgeHelpers { private const String ST_TEST_ELEM = "DOCNAMESPACE"; private const String ST_TEST_EMPTY_ELEM = "NOSPACE"; private const String ST_TEST_ELEM_NS = "NAMESPACE1"; private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1"; //[Variation("IsStartElement on Regular Element, no namespace", Priority = 0)] public void TestIsStartElement1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM); TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()"); TestLog.Compare(DataReader.IsStartElement(ST_TEST_ELEM), true, "IsStartElement(n)"); TestLog.Compare(DataReader.IsStartElement(ST_TEST_ELEM, String.Empty), true, "IsStartElement(n,ns)"); } //[Variation("IsStartElement on Empty Element, no namespace", Priority = 0)] public void TestIsStartElement2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM); TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()"); TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM), true, "IsStartElement(n)"); TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM, String.Empty), true, "IsStartElement(n,ns)"); } //[Variation("IsStartElement on regular Element, with namespace", Priority = 0)] public void TestIsStartElement3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM_NS); PositionOnElement(DataReader, "bar:check"); TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()"); TestLog.Compare(DataReader.IsStartElement("check", "1"), true, "IsStartElement(n,ns)"); TestLog.Compare(DataReader.IsStartElement("check", String.Empty), false, "IsStartElement(n)"); TestLog.Compare(DataReader.IsStartElement("check"), false, "IsStartElement2(n)"); TestLog.Compare(DataReader.IsStartElement("bar:check"), true, "IsStartElement(qname)"); TestLog.Compare(DataReader.IsStartElement("bar1:check"), false, "IsStartElement(invalid_qname)"); } //[Variation("IsStartElement on Empty Tag, with default namespace", Priority = 0)] public void TestIsStartElement4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS); TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()"); TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS, "14"), true, "IsStartElement(n,ns)"); TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS, String.Empty), false, "IsStartElement(n)"); TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS), true, "IsStartElement2(n)"); } //[Variation("IsStartElement with Name=String.Empty")] public void TestIsStartElement5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM); TestLog.Compare(DataReader.IsStartElement(String.Empty), false, Variation.Desc); } //[Variation("IsStartElement on Empty Element with Name and Namespace=String.Empty")] public void TestIsStartElement6() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM); TestLog.Compare(DataReader.IsStartElement(String.Empty, String.Empty), false, Variation.Desc); } //[Variation("IsStartElement on CDATA")] public void TestIsStartElement7() { XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.CDATA); TestLog.Compare(DataReader.IsStartElement(), false, Variation.Desc); } //[Variation("IsStartElement on EndElement, no namespace")] public void TestIsStartElement8() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONAMESPACE"); PositionOnNodeType(DataReader, XmlNodeType.EndElement); TestLog.Compare(DataReader.IsStartElement(), false, "IsStartElement()"); TestLog.Compare(DataReader.IsStartElement("NONAMESPACE"), false, "IsStartElement(n)"); TestLog.Compare(DataReader.IsStartElement("NONAMESPACE", String.Empty), false, "IsStartElement(n,ns)"); } //[Variation("IsStartElement on EndElement, with namespace")] public void TestIsStartElement9() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM_NS); PositionOnElement(DataReader, "bar:check"); PositionOnNodeType(DataReader, XmlNodeType.EndElement); TestLog.Compare(DataReader.IsStartElement(), false, "IsStartElement()"); TestLog.Compare(DataReader.IsStartElement("check", "1"), false, "IsStartElement(n,ns)"); TestLog.Compare(DataReader.IsStartElement("bar:check"), false, "IsStartElement(qname)"); } //[Variation("IsStartElement on Attribute")] public void TestIsStartElement10() { XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Attribute); TestLog.Compare(DataReader.IsStartElement(), true, Variation.Desc); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, Variation.Desc); } //[Variation("IsStartElement on Text")] public void TestIsStartElement11() { XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Text); TestLog.Compare(DataReader.IsStartElement(), false, Variation.Desc); } //[Variation("IsStartElement on ProcessingInstruction")] public void TestIsStartElement12() { XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.ProcessingInstruction); TestLog.Compare(DataReader.IsStartElement(), true, Variation.Desc); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, Variation.Desc); } //[Variation("IsStartElement on Comment")] public void TestIsStartElement13() { XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Comment); TestLog.Compare(DataReader.IsStartElement(), true, Variation.Desc); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, Variation.Desc); } } //[TestCase(Name = "ReadStartElement", Desc = "ReadStartElement")] public partial class TCReadStartElement : BridgeHelpers { private const String ST_TEST_ELEM = "DOCNAMESPACE"; private const String ST_TEST_EMPTY_ELEM = "NOSPACE"; private const String ST_TEST_ELEM_NS = "NAMESPACE1"; private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1"; //[Variation("ReadStartElement on Regular Element, no namespace", Priority = 0)] public void TestReadStartElement1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM); DataReader.ReadStartElement(); DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM); DataReader.ReadStartElement(ST_TEST_ELEM); DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM); DataReader.ReadStartElement(ST_TEST_ELEM, String.Empty); } //[Variation("ReadStartElement on Empty Element, no namespace", Priority = 0)] public void TestReadStartElement2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM); DataReader.ReadStartElement(); DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM); DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM); DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM); DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM, String.Empty); } //[Variation("ReadStartElement on regular Element, with namespace", Priority = 0)] public void TestReadStartElement3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM_NS); PositionOnElement(DataReader, "bar:check"); DataReader.ReadStartElement(); DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM_NS); PositionOnElement(DataReader, "bar:check"); DataReader.ReadStartElement("check", "1"); DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM_NS); PositionOnElement(DataReader, "bar:check"); DataReader.ReadStartElement("bar:check"); } //[Variation("Passing ns=String.EmptyErrorCase: ReadStartElement on regular Element, with namespace", Priority = 0)] public void TestReadStartElement4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM_NS); PositionOnElement(DataReader, "bar:check"); try { DataReader.ReadStartElement("check", String.Empty); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("Passing no ns: ReadStartElement on regular Element, with namespace", Priority = 0)] public void TestReadStartElement5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM_NS); PositionOnElement(DataReader, "bar:check"); try { DataReader.ReadStartElement("check"); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement on Empty Tag, with namespace")] public void TestReadStartElement6() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS); DataReader.ReadStartElement(); DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS); DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS, "14"); } //[Variation("ErrorCase: ReadStartElement on Empty Tag, with namespace, passing ns=String.Empty")] public void TestReadStartElement7() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS); try { DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS, String.Empty); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement on Empty Tag, with namespace, passing no ns")] public void TestReadStartElement8() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS); DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS); } //[Variation("ReadStartElement with Name=String.Empty")] public void TestReadStartElement9() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM); try { DataReader.ReadStartElement(String.Empty); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement on Empty Element with Name and Namespace=String.Empty")] public void TestReadStartElement10() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS); try { DataReader.ReadStartElement(String.Empty, String.Empty); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement on CDATA")] public void TestReadStartElement11() { XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.CDATA); try { DataReader.ReadStartElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement() on EndElement, no namespace")] public void TestReadStartElement12() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONAMESPACE"); PositionOnNodeType(DataReader, XmlNodeType.EndElement); try { DataReader.ReadStartElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement(n) on EndElement, no namespace")] public void TestReadStartElement13() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONAMESPACE"); PositionOnNodeType(DataReader, XmlNodeType.EndElement); try { DataReader.ReadStartElement("NONAMESPACE"); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement(n, String.Empty) on EndElement, no namespace")] public void TestReadStartElement14() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONAMESPACE"); PositionOnNodeType(DataReader, XmlNodeType.EndElement); try { DataReader.ReadStartElement("NONAMESPACE", String.Empty); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement() on EndElement, with namespace")] public void TestReadStartElement15() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM_NS); PositionOnElement(DataReader, "bar:check"); PositionOnNodeType(DataReader, XmlNodeType.EndElement); try { DataReader.ReadStartElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement(n,ns) on EndElement, with namespace")] public void TestReadStartElement16() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM_NS); PositionOnElement(DataReader, "bar:check"); PositionOnNodeType(DataReader, XmlNodeType.EndElement); try { DataReader.ReadStartElement("check", "1"); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } } //[TestCase(Name = "ReadEndElement", Desc = "ReadEndElement")] public partial class TCReadEndElement : BridgeHelpers { private const String ST_TEST_ELEM = "DOCNAMESPACE"; private const String ST_TEST_EMPTY_ELEM = "NOSPACE"; private const String ST_TEST_ELEM_NS = "NAMESPACE1"; private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1"; [Fact] public void TestReadEndElementOnEndElementWithoutNamespace() { using (XmlReader DataReader = GetPGenericXmlReader()) { PositionOnElement(DataReader, "NONAMESPACE"); PositionOnNodeType(DataReader, XmlNodeType.EndElement); Assert.True(VerifyNode(DataReader, XmlNodeType.EndElement, "NONAMESPACE", String.Empty)); } } [Fact] public void TestReadEndElementOnEndElementWithNamespace() { using (XmlReader DataReader = GetPGenericXmlReader()) { PositionOnElement(DataReader, ST_TEST_ELEM_NS); PositionOnElement(DataReader, "bar:check"); PositionOnNodeType(DataReader, XmlNodeType.EndElement); Assert.True(VerifyNode(DataReader, XmlNodeType.EndElement, "bar:check", String.Empty)); } } //[Variation("ReadEndElement on Start Element, no namespace")] public void TestReadEndElement3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadEndElement on Empty Element, no namespace", Priority = 0)] public void TestReadEndElement4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadEndElement on regular Element, with namespace", Priority = 0)] public void TestReadEndElement5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_ELEM_NS); PositionOnElement(DataReader, "bar:check"); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadEndElement on Empty Tag, with namespace", Priority = 0)] public void TestReadEndElement6() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadEndElement on CDATA")] public void TestReadEndElement7() { XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.CDATA); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadEndElement on Text")] public void TestReadEndElement9() { XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Text); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadEndElement on ProcessingInstruction")] public void TestReadEndElement10() { XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.ProcessingInstruction); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadEndElement on Comment")] public void TestReadEndElement11() { XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Comment); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadEndElement on XmlDeclaration")] public void TestReadEndElement13() { XmlReader DataReader = GetReader(); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadEndElement on EntityReference")] public void TestTextReadEndElement1() { XmlReader DataReader = GetReader(); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadEndElement on EndEntity")] public void TestTextReadEndElement2() { XmlReader DataReader = GetReader(); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } } public partial class TCMoveToElement : BridgeHelpers { //[Variation("Attribute node")] public void v1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "elem2"); DataReader.MoveToAttribute(1); TestLog.Compare(DataReader.MoveToElement(), "MTE on elem2 failed"); TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "elem2", String.Empty), "MTE moved on wrong node"); } //[Variation("Element node")] public void v2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "elem2"); TestLog.Compare(!DataReader.MoveToElement(), "MTE on elem2 failed"); TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "elem2", String.Empty), "MTE moved on wrong node"); } //[Variation("Comment node")] public void v5() { XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Comment); TestLog.Compare(!DataReader.MoveToElement(), "MTE on comment failed"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Comment, "comment"); } } } } }
/* * 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 System.Threading; using Timer = System.Timers.Timer; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework; using OpenSim.Services.Interfaces; namespace OpenSim.Region.OptionalModules.World.NPC { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "NPCModule")] public class NPCModule : INPCModule, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private Dictionary<UUID, NPCAvatar> m_avatars = new Dictionary<UUID, NPCAvatar>(); public bool Enabled { get; private set; } public void Initialise(IConfigSource source) { IConfig config = source.Configs["NPC"]; Enabled = (config != null && config.GetBoolean("Enabled", false)); } public void AddRegion(Scene scene) { if (Enabled) scene.RegisterModuleInterface<INPCModule>(this); } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void RemoveRegion(Scene scene) { scene.UnregisterModuleInterface<INPCModule>(this); } public void Close() { } public string Name { get { return "NPCModule"; } } public Type ReplaceableInterface { get { return null; } } public bool IsNPC(UUID agentId, Scene scene) { // FIXME: This implementation could not just use the // ScenePresence.PresenceType (and callers could inspect that // directly). ScenePresence sp = scene.GetScenePresence(agentId); if (sp == null || sp.IsChildAgent) return false; lock (m_avatars) return m_avatars.ContainsKey(agentId); } public bool SetNPCAppearance(UUID agentId, AvatarAppearance appearance, Scene scene) { ScenePresence npc = scene.GetScenePresence(agentId); if (npc == null || npc.IsChildAgent) return false; lock (m_avatars) if (!m_avatars.ContainsKey(agentId)) return false; // Delete existing npc attachments scene.AttachmentsModule.DeleteAttachmentsFromScene(npc, false); // XXX: We can't just use IAvatarFactoryModule.SetAppearance() yet // since it doesn't transfer attachments AvatarAppearance npcAppearance = new AvatarAppearance(appearance, true); npc.Appearance = npcAppearance; // Rez needed npc attachments scene.AttachmentsModule.RezAttachments(npc); IAvatarFactoryModule module = scene.RequestModuleInterface<IAvatarFactoryModule>(); module.SendAppearance(npc.UUID); return true; } public UUID CreateNPC(string firstname, string lastname, Vector3 position, UUID owner, bool senseAsAgent, Scene scene, AvatarAppearance appearance) { NPCAvatar npcAvatar = new NPCAvatar(firstname, lastname, position, owner, senseAsAgent, scene); npcAvatar.CircuitCode = (uint)Util.RandomClass.Next(0, int.MaxValue); m_log.DebugFormat( "[NPC MODULE]: Creating NPC {0} {1} {2}, owner={3}, senseAsAgent={4} at {5} in {6}", firstname, lastname, npcAvatar.AgentId, owner, senseAsAgent, position, scene.RegionInfo.RegionName); AgentCircuitData acd = new AgentCircuitData(); acd.AgentID = npcAvatar.AgentId; acd.firstname = firstname; acd.lastname = lastname; acd.ServiceURLs = new Dictionary<string, object>(); AvatarAppearance npcAppearance = new AvatarAppearance(appearance, true); acd.Appearance = npcAppearance; /* for (int i = 0; i < acd.Appearance.Texture.FaceTextures.Length; i++) { m_log.DebugFormat( "[NPC MODULE]: NPC avatar {0} has texture id {1} : {2}", acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]); } */ lock (m_avatars) { scene.AuthenticateHandler.AddNewCircuit(npcAvatar.CircuitCode, acd); scene.AddNewClient(npcAvatar, PresenceType.Npc); ScenePresence sp; if (scene.TryGetScenePresence(npcAvatar.AgentId, out sp)) { /* m_log.DebugFormat( "[NPC MODULE]: Successfully retrieved scene presence for NPC {0} {1}", sp.Name, sp.UUID); */ sp.CompleteMovement(npcAvatar, false); m_avatars.Add(npcAvatar.AgentId, npcAvatar); m_log.DebugFormat("[NPC MODULE]: Created NPC {0} {1}", npcAvatar.AgentId, sp.Name); return npcAvatar.AgentId; } else { m_log.WarnFormat( "[NPC MODULE]: Could not find scene presence for NPC {0} {1}", sp.Name, sp.UUID); return UUID.Zero; } } } public bool MoveToTarget(UUID agentID, Scene scene, Vector3 pos, bool noFly, bool landAtTarget, bool running) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { m_log.DebugFormat( "[NPC MODULE]: Moving {0} to {1} in {2}, noFly {3}, landAtTarget {4}", sp.Name, pos, scene.RegionInfo.RegionName, noFly, landAtTarget); sp.MoveToTarget(pos, noFly, landAtTarget); sp.SetAlwaysRun = running; return true; } } } return false; } public bool StopMoveToTarget(UUID agentID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { sp.Velocity = Vector3.Zero; sp.ResetMoveToTarget(); return true; } } } return false; } public bool Say(UUID agentID, Scene scene, string text) { return Say(agentID, scene, text, 0); } public bool Say(UUID agentID, Scene scene, string text, int channel) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { m_avatars[agentID].Say(channel, text); return true; } } return false; } public bool Shout(UUID agentID, Scene scene, string text, int channel) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { m_avatars[agentID].Shout(channel, text); return true; } } return false; } public bool Sit(UUID agentID, UUID partID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { sp.HandleAgentRequestSit(m_avatars[agentID], agentID, partID, Vector3.Zero); //sp.HandleAgentSit(m_avatars[agentID], agentID); return true; } } } return false; } public bool Whisper(UUID agentID, Scene scene, string text, int channel) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { m_avatars[agentID].Whisper(channel, text); return true; } } return false; } public bool Stand(UUID agentID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) { ScenePresence sp; if (scene.TryGetScenePresence(agentID, out sp)) { sp.StandUp(); return true; } } } return false; } public bool Touch(UUID agentID, UUID objectID) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) return m_avatars[agentID].Touch(objectID); return false; } } public UUID GetOwner(UUID agentID) { lock (m_avatars) { NPCAvatar av; if (m_avatars.TryGetValue(agentID, out av)) return av.OwnerID; } return UUID.Zero; } public INPC GetNPC(UUID agentID, Scene scene) { lock (m_avatars) { if (m_avatars.ContainsKey(agentID)) return m_avatars[agentID]; else return null; } } public bool DeleteNPC(UUID agentID, Scene scene) { lock (m_avatars) { NPCAvatar av; if (m_avatars.TryGetValue(agentID, out av)) { /* m_log.DebugFormat("[NPC MODULE]: Found {0} {1} to remove", agentID, av.Name); */ scene.RemoveClient(agentID, false); m_avatars.Remove(agentID); /* m_log.DebugFormat("[NPC MODULE]: Removed NPC {0} {1}", agentID, av.Name); */ return true; } } /* m_log.DebugFormat("[NPC MODULE]: Could not find {0} to remove", agentID); */ return false; } public bool CheckPermissions(UUID npcID, UUID callerID) { lock (m_avatars) { NPCAvatar av; if (m_avatars.TryGetValue(npcID, out av)) return CheckPermissions(av, callerID); else return false; } } /// <summary> /// Check if the caller has permission to manipulate the given NPC. /// </summary> /// <param name="av"></param> /// <param name="callerID"></param> /// <returns>true if they do, false if they don't.</returns> private bool CheckPermissions(NPCAvatar av, UUID callerID) { return callerID == UUID.Zero || av.OwnerID == UUID.Zero || av.OwnerID == callerID; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsRequiredOptional { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// ExplicitModel operations. /// </summary> public partial interface IExplicitModel { /// <summary> /// Test explicitly required integer. Please put null and the client /// library should throw before the request is sent. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> PostRequiredIntegerParameterWithHttpMessagesAsync(int? bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly optional integer. Please put null. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PostOptionalIntegerParameterWithHttpMessagesAsync(int? bodyParameter = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly required integer. Please put a valid int-wrapper /// with 'value' = null and the client library should throw before /// the request is sent. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> PostRequiredIntegerPropertyWithHttpMessagesAsync(IntWrapper bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly optional integer. Please put a valid int-wrapper /// with 'value' = null. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PostOptionalIntegerPropertyWithHttpMessagesAsync(IntOptionalWrapper bodyParameter = default(IntOptionalWrapper), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly required integer. Please put a header /// 'headerParameter' =&gt; null and the client library should throw /// before the request is sent. /// </summary> /// <param name='headerParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> PostRequiredIntegerHeaderWithHttpMessagesAsync(int? headerParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly optional integer. Please put a header /// 'headerParameter' =&gt; null. /// </summary> /// <param name='headerParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PostOptionalIntegerHeaderWithHttpMessagesAsync(int? headerParameter = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly required string. Please put null and the client /// library should throw before the request is sent. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> PostRequiredStringParameterWithHttpMessagesAsync(string bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly optional string. Please put null. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PostOptionalStringParameterWithHttpMessagesAsync(string bodyParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly required string. Please put a valid string-wrapper /// with 'value' = null and the client library should throw before /// the request is sent. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> PostRequiredStringPropertyWithHttpMessagesAsync(StringWrapper bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly optional integer. Please put a valid /// string-wrapper with 'value' = null. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PostOptionalStringPropertyWithHttpMessagesAsync(StringOptionalWrapper bodyParameter = default(StringOptionalWrapper), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly required string. Please put a header /// 'headerParameter' =&gt; null and the client library should throw /// before the request is sent. /// </summary> /// <param name='headerParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> PostRequiredStringHeaderWithHttpMessagesAsync(string headerParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly optional string. Please put a header /// 'headerParameter' =&gt; null. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PostOptionalStringHeaderWithHttpMessagesAsync(string bodyParameter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly required complex object. Please put null and the /// client library should throw before the request is sent. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> PostRequiredClassParameterWithHttpMessagesAsync(Product bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly optional complex object. Please put null. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PostOptionalClassParameterWithHttpMessagesAsync(Product bodyParameter = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly required complex object. Please put a valid /// class-wrapper with 'value' = null and the client library should /// throw before the request is sent. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> PostRequiredClassPropertyWithHttpMessagesAsync(ClassWrapper bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly optional complex object. Please put a valid /// class-wrapper with 'value' = null. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PostOptionalClassPropertyWithHttpMessagesAsync(ClassOptionalWrapper bodyParameter = default(ClassOptionalWrapper), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly required array. Please put null and the client /// library should throw before the request is sent. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> PostRequiredArrayParameterWithHttpMessagesAsync(IList<string> bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly optional array. Please put null. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PostOptionalArrayParameterWithHttpMessagesAsync(IList<string> bodyParameter = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly required array. Please put a valid array-wrapper /// with 'value' = null and the client library should throw before /// the request is sent. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> PostRequiredArrayPropertyWithHttpMessagesAsync(ArrayWrapper bodyParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly optional array. Please put a valid array-wrapper /// with 'value' = null. /// </summary> /// <param name='bodyParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PostOptionalArrayPropertyWithHttpMessagesAsync(ArrayOptionalWrapper bodyParameter = default(ArrayOptionalWrapper), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly required array. Please put a header /// 'headerParameter' =&gt; null and the client library should throw /// before the request is sent. /// </summary> /// <param name='headerParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> PostRequiredArrayHeaderWithHttpMessagesAsync(IList<string> headerParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Test explicitly optional integer. Please put a header /// 'headerParameter' =&gt; null. /// </summary> /// <param name='headerParameter'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PostOptionalArrayHeaderWithHttpMessagesAsync(IList<string> headerParameter = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ConcurrentBag.cs // // An unordered collection that allows duplicates and that provides add and get operations. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.Collections.Concurrent { /// <summary> /// Represents an thread-safe, unordered collection of objects. /// </summary> /// <typeparam name="T">Specifies the type of elements in the bag.</typeparam> /// <remarks> /// <para> /// Bags are useful for storing objects when ordering doesn't matter, and unlike sets, bags support /// duplicates. <see cref="ConcurrentBag{T}"/> is a thread-safe bag implementation, optimized for /// scenarios where the same thread will be both producing and consuming data stored in the bag. /// </para> /// <para> /// <see cref="ConcurrentBag{T}"/> accepts null reference (Nothing in Visual Basic) as a valid /// value for reference types. /// </para> /// <para> /// All public and protected members of <see cref="ConcurrentBag{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </para> /// </remarks> [DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class ConcurrentBag<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> { // ThreadLocalList object that contains the data per thread private ThreadLocal<ThreadLocalList> _locals; // This head and tail pointers points to the first and last local lists, to allow enumeration on the thread locals objects private volatile ThreadLocalList _headList, _tailList; // A flag used to tell the operations thread that it must synchronize the operation, this flag is set/unset within // GlobalListsLock lock private bool _needSync; /// <summary> /// Initializes a new instance of the <see cref="ConcurrentBag{T}"/> /// class. /// </summary> public ConcurrentBag() { Initialize(null); } /// <summary> /// Initializes a new instance of the <see cref="ConcurrentBag{T}"/> /// class that contains elements copied from the specified collection. /// </summary> /// <param name="collection">The collection whose elements are copied to the new <see /// cref="ConcurrentBag{T}"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="collection"/> is a null reference /// (Nothing in Visual Basic).</exception> public ConcurrentBag(IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException("collection", SR.ConcurrentBag_Ctor_ArgumentNullException); } Initialize(collection); } /// <summary> /// Local helper function to initialize a new bag object /// </summary> /// <param name="collection">An enumeration containing items with which to initialize this bag.</param> private void Initialize(IEnumerable<T> collection) { _locals = new ThreadLocal<ThreadLocalList>(); // Copy the collection to the bag if (collection != null) { ThreadLocalList list = GetThreadList(true); foreach (T item in collection) { list.Add(item, false); } } } /// <summary> /// Adds an object to the <see cref="ConcurrentBag{T}"/>. /// </summary> /// <param name="item">The object to be added to the /// <see cref="ConcurrentBag{T}"/>. The value can be a null reference /// (Nothing in Visual Basic) for reference types.</param> public void Add(T item) { // Get the local list for that thread, create a new list if this thread doesn't exist //(first time to call add) ThreadLocalList list = GetThreadList(true); AddInternal(list, item); } /// <summary> /// </summary> /// <param name="list"></param> /// <param name="item"></param> private void AddInternal(ThreadLocalList list, T item) { bool lockTaken = false; try { #pragma warning disable 0420 Interlocked.Exchange(ref list._currentOp, (int)ListOperation.Add); #pragma warning restore 0420 //Synchronization cases: // if the list count is less than two to avoid conflict with any stealing thread // if _needSync is set, this means there is a thread that needs to freeze the bag if (list.Count < 2 || _needSync) { // reset it back to zero to avoid deadlock with stealing thread list._currentOp = (int)ListOperation.None; Monitor.Enter(list, ref lockTaken); } list.Add(item, lockTaken); } finally { list._currentOp = (int)ListOperation.None; if (lockTaken) { Monitor.Exit(list); } } } /// <summary> /// Attempts to add an object to the <see cref="ConcurrentBag{T}"/>. /// </summary> /// <param name="item">The object to be added to the /// <see cref="ConcurrentBag{T}"/>. The value can be a null reference /// (Nothing in Visual Basic) for reference types.</param> /// <returns>Always returns true</returns> bool IProducerConsumerCollection<T>.TryAdd(T item) { Add(item); return true; } /// <summary> /// Attempts to remove and return an object from the <see /// cref="ConcurrentBag{T}"/>. /// </summary> /// <param name="result">When this method returns, <paramref name="result"/> contains the object /// removed from the <see cref="ConcurrentBag{T}"/> or the default value /// of <typeparamref name="T"/> if the operation failed.</param> /// <returns>true if an object was removed successfully; otherwise, false.</returns> public bool TryTake(out T result) { return TryTakeOrPeek(out result, true); } /// <summary> /// Attempts to return an object from the <see cref="ConcurrentBag{T}"/> /// without removing it. /// </summary> /// <param name="result">When this method returns, <paramref name="result"/> contains an object from /// the <see cref="ConcurrentBag{T}"/> or the default value of /// <typeparamref name="T"/> if the operation failed.</param> /// <returns>true if and object was returned successfully; otherwise, false.</returns> public bool TryPeek(out T result) { return TryTakeOrPeek(out result, false); } /// <summary> /// Local helper function to Take or Peek an item from the bag /// </summary> /// <param name="result">To receive the item retrieved from the bag</param> /// <param name="take">True means Take operation, false means Peek operation</param> /// <returns>True if succeeded, false otherwise</returns> private bool TryTakeOrPeek(out T result, bool take) { // Get the local list for that thread, return null if the thread doesn't exit //(this thread never add before) ThreadLocalList list = GetThreadList(false); if (list == null || list.Count == 0) { return Steal(out result, take); } bool lockTaken = false; try { if (take) // Take operation { #pragma warning disable 0420 Interlocked.Exchange(ref list._currentOp, (int)ListOperation.Take); #pragma warning restore 0420 //Synchronization cases: // if the list count is less than or equal two to avoid conflict with any stealing thread // if _needSync is set, this means there is a thread that needs to freeze the bag if (list.Count <= 2 || _needSync) { // reset it back to zero to avoid deadlock with stealing thread list._currentOp = (int)ListOperation.None; Monitor.Enter(list, ref lockTaken); // Double check the count and steal if it became empty if (list.Count == 0) { // Release the lock before stealing if (lockTaken) { try { } finally { lockTaken = false; // reset lockTaken to avoid calling Monitor.Exit again in the finally block Monitor.Exit(list); } } return Steal(out result, true); } } list.Remove(out result); } else { if (!list.Peek(out result)) { return Steal(out result, false); } } } finally { list._currentOp = (int)ListOperation.None; if (lockTaken) { Monitor.Exit(list); } } return true; } /// <summary> /// Local helper function to retrieve a thread local list by a thread object /// </summary> /// <param name="forceCreate">Create a new list if the thread does ot exist</param> /// <returns>The local list object</returns> private ThreadLocalList GetThreadList(bool forceCreate) { ThreadLocalList list = _locals.Value; if (list != null) { return list; } else if (forceCreate) { // Acquire the lock to update the _tailList pointer lock (GlobalListsLock) { if (_headList == null) { list = new ThreadLocalList(Environment.CurrentManagedThreadId); _headList = list; _tailList = list; } else { list = GetUnownedList(); if (list == null) { list = new ThreadLocalList(Environment.CurrentManagedThreadId); _tailList._nextList = list; _tailList = list; } } _locals.Value = list; } } else { return null; } Debug.Assert(list != null); return list; } /// <summary> /// Try to reuse an unowned list if exist /// unowned lists are the lists that their owner threads are aborted or terminated /// this is workaround to avoid memory leaks. /// </summary> /// <returns>The list object, null if all lists are owned</returns> private ThreadLocalList GetUnownedList() { //the global lock must be held at this point Debug.Assert(Monitor.IsEntered(GlobalListsLock)); int currentThreadId = Environment.CurrentManagedThreadId; ThreadLocalList currentList = _headList; while (currentList != null) { if (currentList._ownerThreadId == currentThreadId) { return currentList; } currentList = currentList._nextList; } return null; } /// <summary> /// Local helper method to steal an item from any other non empty thread /// It enumerate all other threads in two passes first pass acquire the lock with TryEnter if succeeded /// it steals the item, otherwise it enumerate them again in 2nd pass and acquire the lock using Enter /// </summary> /// <param name="result">To receive the item retrieved from the bag</param> /// <param name="take">Whether to remove or peek.</param> /// <returns>True if succeeded, false otherwise.</returns> private bool Steal(out T result, bool take) { #if FEATURE_TRACING if (take) CDSCollectionETWBCLProvider.Log.ConcurrentBag_TryTakeSteals(); else CDSCollectionETWBCLProvider.Log.ConcurrentBag_TryPeekSteals(); #endif bool loop; List<int> versionsList = new List<int>(); // save the lists version do { versionsList.Clear(); //clear the list from the previous iteration loop = false; ThreadLocalList currentList = _headList; while (currentList != null) { versionsList.Add(currentList._version); if (currentList._head != null && TrySteal(currentList, out result, take)) { return true; } currentList = currentList._nextList; } // verify versioning, if other items are added to this list since we last visit it, we should retry currentList = _headList; foreach (int version in versionsList) { if (version != currentList._version) //oops state changed { loop = true; if (currentList._head != null && TrySteal(currentList, out result, take)) return true; } currentList = currentList._nextList; } } while (loop); result = default(T); return false; } /// <summary> /// local helper function tries to steal an item from given local list /// </summary> private bool TrySteal(ThreadLocalList list, out T result, bool take) { lock (list) { if (CanSteal(list)) { list.Steal(out result, take); return true; } result = default(T); return false; } } /// <summary> /// Local helper function to check the list if it became empty after acquiring the lock /// and wait if there is unsynchronized Add/Take operation in the list to be done /// </summary> /// <param name="list">The list to steal</param> /// <returns>True if can steal, false otherwise</returns> private static bool CanSteal(ThreadLocalList list) { if (list.Count <= 2 && list._currentOp != (int)ListOperation.None) { SpinWait spinner = new SpinWait(); while (list._currentOp != (int)ListOperation.None) { spinner.SpinOnce(); } } return list.Count > 0; } /// <summary> /// Copies the <see cref="ConcurrentBag{T}"/> elements to an existing /// one-dimensional <see cref="T:System.Array">Array</see>, starting at the specified array /// index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the /// destination of the elements copied from the /// <see cref="ConcurrentBag{T}"/>. The <see /// cref="T:System.Array">Array</see> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the /// length of the <paramref name="array"/> /// -or- the number of elements in the source <see /// cref="ConcurrentBag{T}"/> is greater than the available space from /// <paramref name="index"/> to the end of the destination <paramref name="array"/>.</exception> public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException("array", SR.ConcurrentBag_CopyTo_ArgumentNullException); } if (index < 0) { throw new ArgumentOutOfRangeException ("index", SR.ConcurrentBag_CopyTo_ArgumentOutOfRangeException); } // Short path if the bag is empty if (_headList == null) return; bool lockTaken = false; try { FreezeBag(ref lockTaken); ToList().CopyTo(array, index); } finally { UnfreezeBag(lockTaken); } } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see /// cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the /// destination of the elements copied from the /// <see cref="ConcurrentBag{T}"/>. The <see /// cref="T:System.Array">Array</see> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the /// destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException("array", SR.ConcurrentBag_CopyTo_ArgumentNullException); } bool lockTaken = false; try { FreezeBag(ref lockTaken); ((ICollection)ToList()).CopyTo(array, index); } finally { UnfreezeBag(lockTaken); } } /// <summary> /// Copies the <see cref="ConcurrentBag{T}"/> elements to a new array. /// </summary> /// <returns>A new array containing a snapshot of elements copied from the <see /// cref="ConcurrentBag{T}"/>.</returns> public T[] ToArray() { // Short path if the bag is empty if (_headList == null) return new T[0]; bool lockTaken = false; try { FreezeBag(ref lockTaken); return ToList().ToArray(); } finally { UnfreezeBag(lockTaken); } } /// <summary> /// Returns an enumerator that iterates through the <see /// cref="ConcurrentBag{T}"/>. /// </summary> /// <returns>An enumerator for the contents of the <see /// cref="ConcurrentBag{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the bag. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the bag. /// </remarks> public IEnumerator<T> GetEnumerator() { // Short path if the bag is empty if (_headList == null) return new List<T>().GetEnumerator(); // empty list bool lockTaken = false; try { FreezeBag(ref lockTaken); return ToList().GetEnumerator(); } finally { UnfreezeBag(lockTaken); } } /// <summary> /// Returns an enumerator that iterates through the <see /// cref="ConcurrentBag{T}"/>. /// </summary> /// <returns>An enumerator for the contents of the <see /// cref="ConcurrentBag{T}"/>.</returns> /// <remarks> /// The items enumerated represent a moment-in-time snapshot of the contents /// of the bag. It does not reflect any update to the collection after /// <see cref="GetEnumerator"/> was called. /// </remarks> IEnumerator IEnumerable.GetEnumerator() { return ((ConcurrentBag<T>)this).GetEnumerator(); } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentBag{T}"/>. /// </summary> /// <value>The number of elements contained in the <see cref="ConcurrentBag{T}"/>.</value> /// <remarks> /// The count returned represents a moment-in-time snapshot of the contents /// of the bag. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. /// </remarks> public int Count { get { // Short path if the bag is empty if (_headList == null) return 0; bool lockTaken = false; try { FreezeBag(ref lockTaken); return GetCountInternal(); } finally { UnfreezeBag(lockTaken); } } } /// <summary> /// Gets a value that indicates whether the <see cref="ConcurrentBag{T}"/> is empty. /// </summary> /// <value>true if the <see cref="ConcurrentBag{T}"/> is empty; otherwise, false.</value> public bool IsEmpty { get { if (_headList == null) return true; bool lockTaken = false; try { FreezeBag(ref lockTaken); ThreadLocalList currentList = _headList; while (currentList != null) { if (currentList._head != null) //at least this list is not empty, we return false { return false; } currentList = currentList._nextList; } return true; } finally { UnfreezeBag(lockTaken); } } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is /// synchronized with the SyncRoot. /// </summary> /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentBag{T}"/>, this property always /// returns false.</value> bool ICollection.IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see /// cref="T:System.Collections.ICollection"/>. This property is not supported. /// </summary> /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception> object ICollection.SyncRoot { get { throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported); } } /// <summary> /// A global lock object, used in two cases: /// 1- To maintain the _tailList pointer for each new list addition process ( first time a thread called Add ) /// 2- To freeze the bag in GetEnumerator, CopyTo, ToArray and Count members /// </summary> private object GlobalListsLock { get { Debug.Assert(_locals != null); return _locals; } } #region Freeze bag helper methods /// <summary> /// Local helper method to freeze all bag operations, it /// 1- Acquire the global lock to prevent any other thread to freeze the bag, and also new new thread can be added /// to the dictionary /// 2- Then Acquire all local lists locks to prevent steal and synchronized operations /// 3- Wait for all un-synchronized operations to be done /// </summary> /// <param name="lockTaken">Retrieve the lock taken result for the global lock, to be passed to Unfreeze method</param> private void FreezeBag(ref bool lockTaken) { Debug.Assert(!Monitor.IsEntered(GlobalListsLock)); // global lock to be safe against multi threads calls count and corrupt _needSync Monitor.Enter(GlobalListsLock, ref lockTaken); // This will force any future add/take operation to be synchronized _needSync = true; //Acquire all local lists locks AcquireAllLocks(); // Wait for all un-synchronized operation to be done WaitAllOperations(); } /// <summary> /// Local helper method to unfreeze the bag from a frozen state /// </summary> /// <param name="lockTaken">The lock taken result from the Freeze method</param> private void UnfreezeBag(bool lockTaken) { ReleaseAllLocks(); _needSync = false; if (lockTaken) { Monitor.Exit(GlobalListsLock); } } /// <summary> /// local helper method to acquire all local lists locks /// </summary> private void AcquireAllLocks() { Debug.Assert(Monitor.IsEntered(GlobalListsLock)); bool lockTaken = false; ThreadLocalList currentList = _headList; while (currentList != null) { // Try/Finally block to avoid thread abort between acquiring the lock and setting the taken flag try { Monitor.Enter(currentList, ref lockTaken); } finally { if (lockTaken) { currentList._lockTaken = true; lockTaken = false; } } currentList = currentList._nextList; } } /// <summary> /// Local helper method to release all local lists locks /// </summary> private void ReleaseAllLocks() { ThreadLocalList currentList = _headList; while (currentList != null) { if (currentList._lockTaken) { currentList._lockTaken = false; Monitor.Exit(currentList); } currentList = currentList._nextList; } } /// <summary> /// Local helper function to wait all unsynchronized operations /// </summary> private void WaitAllOperations() { Debug.Assert(Monitor.IsEntered(GlobalListsLock)); ThreadLocalList currentList = _headList; while (currentList != null) { if (currentList._currentOp != (int)ListOperation.None) { SpinWait spinner = new SpinWait(); while (currentList._currentOp != (int)ListOperation.None) { spinner.SpinOnce(); } } currentList = currentList._nextList; } } /// <summary> /// Local helper function to get the bag count, the caller should call it from Freeze/Unfreeze block /// </summary> /// <returns>The current bag count</returns> private int GetCountInternal() { Debug.Assert(Monitor.IsEntered(GlobalListsLock)); int count = 0; ThreadLocalList currentList = _headList; while (currentList != null) { checked { count += currentList.Count; } currentList = currentList._nextList; } return count; } /// <summary> /// Local helper function to return the bag item in a list, this is mainly used by CopyTo and ToArray /// This is not thread safe, should be called in Freeze/UnFreeze bag block /// </summary> /// <returns>List the contains the bag items</returns> private List<T> ToList() { Debug.Assert(Monitor.IsEntered(GlobalListsLock)); List<T> list = new List<T>(); ThreadLocalList currentList = _headList; while (currentList != null) { Node currentNode = currentList._head; while (currentNode != null) { list.Add(currentNode._value); currentNode = currentNode._next; } currentList = currentList._nextList; } return list; } #endregion #region Inner Classes /// <summary> /// A class that represents a node in the lock thread list /// </summary> internal class Node { public Node(T value) { _value = value; } public readonly T _value; public Node _next; public Node _prev; } /// <summary> /// A class that represents the lock thread list /// </summary> internal class ThreadLocalList { // Tead node in the list, null means the list is empty internal volatile Node _head; // Tail node for the list private volatile Node _tail; // The current list operation internal volatile int _currentOp; // The list count from the Add/Take perspective private int _count; // The stealing count internal int _stealCount; // Next list in the dictionary values internal volatile ThreadLocalList _nextList; // Set if the locl lock is taken internal bool _lockTaken; // The owner thread for this list internal int _ownerThreadId; // the version of the list, incremented only when the list changed from empty to non empty state internal volatile int _version; /// <summary> /// ThreadLocalList constructor /// </summary> /// <param name="ownerThread">The owner thread for this list</param> internal ThreadLocalList(int ownerThreadId) { _ownerThreadId = ownerThreadId; } /// <summary> /// Add new item to head of the list /// </summary> /// <param name="item">The item to add.</param> /// <param name="updateCount">Whether to update the count.</param> internal void Add(T item, bool updateCount) { checked { _count++; } Node node = new Node(item); if (_head == null) { Debug.Assert(_tail == null); _head = node; _tail = node; _version++; // changing from empty state to non empty state } else { node._next = _head; _head._prev = node; _head = node; } if (updateCount) // update the count to avoid overflow if this add is synchronized { _count = _count - _stealCount; _stealCount = 0; } } /// <summary> /// Remove an item from the head of the list /// </summary> /// <param name="result">The removed item</param> internal void Remove(out T result) { Debug.Assert(_head != null); Node head = _head; _head = _head._next; if (_head != null) { _head._prev = null; } else { _tail = null; } _count--; result = head._value; } /// <summary> /// Peek an item from the head of the list /// </summary> /// <param name="result">the peeked item</param> /// <returns>True if succeeded, false otherwise</returns> internal bool Peek(out T result) { Node head = _head; if (head != null) { result = head._value; return true; } result = default(T); return false; } /// <summary> /// Steal an item from the tail of the list /// </summary> /// <param name="result">the removed item</param> /// <param name="remove">remove or peek flag</param> internal void Steal(out T result, bool remove) { Node tail = _tail; Debug.Assert(tail != null); if (remove) // Take operation { _tail = _tail._prev; if (_tail != null) { _tail._next = null; } else { _head = null; } // Increment the steal count _stealCount++; } result = tail._value; } /// <summary> /// Gets the total list count, it's not thread safe, may provide incorrect count if it is called concurrently /// </summary> internal int Count { get { return _count - _stealCount; } } } #endregion } /// <summary> /// List operations for ConcurrentBag /// </summary> internal enum ListOperation { None, Add, Take }; }
using System; using UnityEngine; using System.Collections.Generic; using System.Linq; using System.Collections; using UnityEngine.UI.Extensions; namespace UnityEngine.UI.Windows { [RequireComponent(typeof(Canvas))] [RequireComponent(typeof(CanvasUpdater))] public class WindowLayout : WindowObjectElement, ICanvasElement, IWindowEventsAsync { public enum ScaleMode : byte { Normal, Fixed, Custom, }; public CanvasScaler canvasScaler; [ReadOnly] public WindowLayoutRoot root; [ReadOnly] public List<WindowLayoutElement> elements = new List<WindowLayoutElement>(); public bool showGrid = false; public Vector2 gridSize = Vector2.one * 5f; [HideInInspector][SerializeField] public Canvas canvas; [HideInInspector][SerializeField] public UnityEngine.EventSystems.BaseRaycaster raycaster; [HideInInspector][SerializeField] public CanvasUpdater canvasUpdater; [HideInInspector][SerializeField] public bool initialized = false; [HideInInspector][SerializeField] private bool isAlive = false; public override bool NeedToInactive() { return false; } #if UNITY_EDITOR public override void OnValidateEditor() { base.OnValidateEditor(); if (Application.isPlaying == true) return; if (this.canvasUpdater == null || this.GetComponents<CanvasUpdater>().Length > 1) { if (this.GetComponent<CanvasUpdater>() != null) Component.DestroyImmediate(this.GetComponent<CanvasUpdater>()); this.canvasUpdater = this.GetComponent<CanvasUpdater>(); if (this.canvasUpdater == null) this.canvasUpdater = this.gameObject.AddComponent<CanvasUpdater>(); if (this.canvasUpdater != null) this.canvasUpdater.OnValidate(); } if (this.canvasScaler == null || this.GetComponents<CanvasScaler>().Length > 1) { if (this.GetComponent<CanvasScaler>() != null) Component.DestroyImmediate(this.GetComponent<CanvasScaler>()); this.canvasScaler = this.GetComponent<CanvasScaler>(); if (this.canvasScaler == null) this.canvasScaler = this.gameObject.AddComponent<CanvasScaler>(); } var rectTransform = (this.transform as RectTransform); rectTransform.anchorMin = Vector2.zero; rectTransform.anchorMax = Vector2.one; rectTransform.pivot = Vector2.one * 0.5f; rectTransform.localScale = Vector3.one; rectTransform.localRotation = Quaternion.identity; rectTransform.anchoredPosition3D = Vector3.zero; } #endif public void Init(float depth, int raycastPriority, int orderInLayer, WindowLayout.ScaleMode scaleMode, Vector2 fixedScaleResolution) { if (this.initialized == false) { Debug.LogError("Can't initialize window instance because of some components was not installed properly."); return; } this.transform.localScale = Vector3.zero; this.canvas.sortingOrder = orderInLayer; this.canvas.planeDistance = 10f;// * orderInLayer; this.canvas.worldCamera = this.GetWindow().workCamera; CanvasUpdater.ForceUpdate(this.canvas, this.canvasScaler); this.SetScale(scaleMode, fixedScaleResolution); for (int i = 0; i < this.elements.Count; ++i) this.elements[i].Setup(this.GetWindow()); this.root.Setup(this.GetWindow()); } public Vector2 GetSize() { this.ValidateCanvasScaler(); var scaleFactor = 1f; var width = Screen.width; var height = Screen.height; if (this.canvasScaler != null) { //scaleFactor = this.canvasScaler.scaleFactor; if (this.canvasScaler.uiScaleMode == CanvasScaler.ScaleMode.ConstantPixelSize) { scaleFactor = this.GetConstantPixelSize(); } else if (this.canvasScaler.uiScaleMode == CanvasScaler.ScaleMode.ConstantPhysicalSize) { scaleFactor = this.GetConstantPhysicalSize(); } else if (this.canvasScaler.uiScaleMode == CanvasScaler.ScaleMode.ScaleWithScreenSize) { scaleFactor = this.GetScaleWithScreenSize(); } } return new Vector2(width * scaleFactor, height * scaleFactor); } #region GET SIZE protected float GetConstantPhysicalSize() { float dpi = Screen.dpi; float num = (dpi != 0f) ? dpi : this.canvasScaler.fallbackScreenDPI; float num2 = 1f; switch (this.canvasScaler.physicalUnit) { case CanvasScaler.Unit.Centimeters: num2 = 2.54f; break; case CanvasScaler.Unit.Millimeters: num2 = 25.4f; break; case CanvasScaler.Unit.Inches: num2 = 1f; break; case CanvasScaler.Unit.Points: num2 = 72f; break; case CanvasScaler.Unit.Picas: num2 = 6f; break; } var scaleFactor = num / num2; return scaleFactor; } protected float GetConstantPixelSize() { return this.canvasScaler.scaleFactor; } protected float GetScaleWithScreenSize() { Vector2 vector = new Vector2(Screen.width, Screen.height); float scaleFactor = 0f; switch (this.canvasScaler.screenMatchMode) { case CanvasScaler.ScreenMatchMode.MatchWidthOrHeight: { float num = Mathf.Log (vector.x / this.canvasScaler.referenceResolution.x, 2f); float num2 = Mathf.Log (vector.y / this.canvasScaler.referenceResolution.y, 2f); float num3 = Mathf.Lerp (num, num2, this.canvasScaler.matchWidthOrHeight); scaleFactor = Mathf.Pow (2f, num3); break; } case CanvasScaler.ScreenMatchMode.Expand: scaleFactor = Mathf.Min (vector.x / this.canvasScaler.referenceResolution.x, vector.y / this.canvasScaler.referenceResolution.y); break; case CanvasScaler.ScreenMatchMode.Shrink: scaleFactor = Mathf.Max (vector.x / this.canvasScaler.referenceResolution.x, vector.y / this.canvasScaler.referenceResolution.y); break; } return scaleFactor; } #endregion public bool ValidateCanvasScaler() { var changed = false; if (this.canvasScaler == null) { this.canvasScaler = this.GetComponent<CanvasScaler>(); changed = true; } if (this.canvasScaler == null) { this.canvasScaler = this.gameObject.AddComponent<CanvasScaler>(); changed = true; } return changed; } public void SetNoScale() { this.ValidateCanvasScaler(); this.canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ConstantPixelSize; this.canvasScaler.enabled = false; } public void SetScale(WindowLayout.ScaleMode scaleMode, Vector2 fixedResolution) { this.ValidateCanvasScaler(); if (scaleMode == ScaleMode.Normal) { this.SetNoScale(); } else { this.canvasScaler.enabled = true; if (scaleMode == ScaleMode.Fixed) { this.canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; this.canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight; this.canvasScaler.matchWidthOrHeight = 0f; this.canvasScaler.referenceResolution = new Vector2(fixedResolution.x, fixedResolution.y); } else if (scaleMode == ScaleMode.Custom) { // We should not do anything in canvasScaler } } } public void Rebuild(CanvasUpdate executing) { if (this.root != null) this.root.Rebuild(); } public bool IsDestroyed() { return !this.isAlive; } public WindowLayoutElement GetRootByTag(LayoutTag tag) { return this.elements.FirstOrDefault((element) => element.tag == tag); } public void GetTags(List<LayoutTag> tags) { tags.Clear(); foreach (var element in this.elements) { if (element == null) continue; tags.Add(element.tag); } } public override void OnShowBegin(System.Action callback, bool resetAnimation = true) { this.isAlive = true; CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this); this.SetComponentState(WindowObjectState.Showing); ME.Utilities.CallInSequence(() => base.OnShowBegin(callback, resetAnimation), this.subComponents, (e, c) => e.OnShowBegin(c, resetAnimation)); } public override void OnHideBegin(System.Action callback, bool immediately = false) { this.SetComponentState(WindowObjectState.Hiding); ME.Utilities.CallInSequence(() => base.OnHideBegin(callback, immediately), this.subComponents, (e, c) => e.OnHideBegin(c, immediately)); } public override void OnHideEnd() { this.isAlive = false; CanvasUpdateRegistry.UnRegisterCanvasElementForRebuild(this); base.OnHideEnd(); } /*public virtual void OnInit() {} public virtual void OnDeinit() {} public virtual void OnShowEnd() {} public virtual void OnHideBegin(System.Action callback, bool immediately = false) { if (callback != null) callback(); }*/ /* public virtual void OnShowBeginEvent() {} public virtual void OnHideEndEvent() {} */ } }
/* * Copyright 2007 ZXing authors * * 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.Collections.Generic; using ZXing.Aztec; using ZXing.Datamatrix; using ZXing.IMB; using ZXing.Maxicode; using ZXing.OneD; using ZXing.PDF417; using ZXing.QrCode; namespace ZXing { /// <summary> /// MultiFormatReader is a convenience class and the main entry point into the library for most uses. /// By default it attempts to decode all barcode formats that the library supports. Optionally, you /// can provide a hints object to request different behavior, for example only decoding QR codes. /// </summary> /// <author>Sean Owen</author> /// <author>dswitkin@google.com (Daniel Switkin)</author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source</author> public sealed class MultiFormatReader : Reader { private IDictionary<DecodeHintType, object> hints; private IList<Reader> readers; /// <summary> This version of decode honors the intent of Reader.decode(BinaryBitmap) in that it /// passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly. /// Use setHints() followed by decodeWithState() for continuous scan applications. /// /// </summary> /// <param name="image">The pixel data to decode /// </param> /// <returns> The contents of the image /// </returns> /// <throws> ReaderException Any errors which occurred </throws> public Result decode(BinaryBitmap image) { Hints = null; return decodeInternal(image); } /// <summary> Decode an image using the hints provided. Does not honor existing state. /// /// </summary> /// <param name="image">The pixel data to decode /// </param> /// <param name="hints">The hints to use, clearing the previous state. /// </param> /// <returns> The contents of the image /// </returns> /// <throws> ReaderException Any errors which occurred </throws> public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints) { Hints = hints; return decodeInternal(image); } /// <summary> Decode an image using the state set up by calling setHints() previously. Continuous scan /// clients will get a <b>large</b> speed increase by using this instead of decode(). /// /// </summary> /// <param name="image">The pixel data to decode /// </param> /// <returns> The contents of the image /// </returns> /// <throws> ReaderException Any errors which occurred </throws> public Result decodeWithState(BinaryBitmap image) { // Make sure to set up the default state so we don't crash if (readers == null) { Hints = null; } return decodeInternal(image); } /// <summary> This method adds state to the MultiFormatReader. By setting the hints once, subsequent calls /// to decodeWithState(image) can reuse the same set of readers without reallocating memory. This /// is important for performance in continuous scan clients. /// /// </summary> public IDictionary<DecodeHintType, object> Hints { set { hints = value; var tryHarder = value != null && value.ContainsKey(DecodeHintType.TRY_HARDER); var formats = value == null || !value.ContainsKey(DecodeHintType.POSSIBLE_FORMATS) ? null : (IList<BarcodeFormat>)value[DecodeHintType.POSSIBLE_FORMATS]; if (formats != null) { bool addOneDReader = formats.Contains(BarcodeFormat.All_1D) || formats.Contains(BarcodeFormat.UPC_A) || formats.Contains(BarcodeFormat.UPC_E) || formats.Contains(BarcodeFormat.EAN_13) || formats.Contains(BarcodeFormat.EAN_8) || formats.Contains(BarcodeFormat.CODABAR) || formats.Contains(BarcodeFormat.CODE_39) || formats.Contains(BarcodeFormat.CODE_93) || formats.Contains(BarcodeFormat.CODE_128) || formats.Contains(BarcodeFormat.ITF) || formats.Contains(BarcodeFormat.RSS_14) || formats.Contains(BarcodeFormat.RSS_EXPANDED); readers = new List<Reader>(); // Put 1D readers upfront in "normal" mode if (addOneDReader && !tryHarder) { readers.Add(new MultiFormatOneDReader(value)); } if (formats.Contains(BarcodeFormat.QR_CODE)) { readers.Add(new QRCodeReader()); } if (formats.Contains(BarcodeFormat.DATA_MATRIX)) { readers.Add(new DataMatrixReader()); } if (formats.Contains(BarcodeFormat.AZTEC)) { readers.Add(new AztecReader()); } if (formats.Contains(BarcodeFormat.PDF_417)) { readers.Add(new PDF417Reader()); } if (formats.Contains(BarcodeFormat.MAXICODE)) { readers.Add(new MaxiCodeReader()); } if (formats.Contains(BarcodeFormat.IMB)) { readers.Add(new IMBReader()); } // At end in "try harder" mode if (addOneDReader && tryHarder) { readers.Add(new MultiFormatOneDReader(value)); } } if (readers == null || readers.Count == 0) { readers = readers ?? new List<Reader>(); if (!tryHarder) { readers.Add(new MultiFormatOneDReader(value)); } readers.Add(new QRCodeReader()); readers.Add(new DataMatrixReader()); readers.Add(new AztecReader()); readers.Add(new PDF417Reader()); readers.Add(new MaxiCodeReader()); if (tryHarder) { readers.Add(new MultiFormatOneDReader(value)); } } } } /// <summary> /// resets all specific readers /// </summary> public void reset() { if (readers != null) { foreach (var reader in readers) { reader.reset(); } } } private Result decodeInternal(BinaryBitmap image) { if (readers != null) { var rpCallback = hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK) ? (ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK] : null; for (var index = 0; index < readers.Count; index++) { var reader = readers[index]; reader.reset(); var result = reader.decode(image, hints); if (result != null) { // found a barcode, pushing the successful reader up front // I assume that the same type of barcode is read multiple times // so the reordering of the readers list should speed up the next reading // a little bit readers.RemoveAt(index); readers.Insert(0, reader); return result; } if (rpCallback != null) rpCallback(null); } } return null; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using DBSchemaInfo.Base; namespace DBSchemaInfo.MsSql { public class SqlCatalog : InformationSchemaCatalogBase { public SqlCatalog(string cnString, string catalog) : base(cnString, catalog) { } protected override DBStructure GetTableViewSchema(IDbConnection cn) { var ds = new DBStructure(); using (var cmd = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.TABLES", (SqlConnection)cn)) { using (var da = new SqlDataAdapter(cmd)) { da.Fill(ds.INFORMATION_SCHEMA_TABLES); } } using (var cmd = new SqlCommand(Properties.Resources.SqlServerGetColumn, (SqlConnection)cn)) { using (var da = new SqlDataAdapter(cmd)) { da.Fill(ds.INFORMATION_SCHEMA_COLUMNS); } } return ds; } protected override ITableInfo CreateTableInfo(DBStructure.INFORMATION_SCHEMA_TABLESRow dr) { return new SqlTableInfo(dr, this); } protected override IViewInfo CreateViewInfo(DBStructure.INFORMATION_SCHEMA_TABLESRow dr) { return new SqlViewInfo(dr, this); } protected override void LoadForeignKeys() { DataTable table = GetConstraintInformation(); var fkeys = new Dictionary<string, StandardForeignKeyConstraint>(); foreach (DataRow dr in table.Rows) { try { StandardForeignKeyConstraint constraint; var constraintName = (string)dr["CONSTRAINT_NAME"]; if (!fkeys.ContainsKey(constraintName)) { ITableInfo cnstTable = Tables[(string)dr["TABLE_CATALOG"], (string)dr["TABLE_SCHEMA"], (string)dr["TABLE_NAME"]]; cnstTable.Catalog = this; ITableInfo pkTable = Tables[ (string)dr["REF_TABLE_CATALOG"], (string)dr["REF_TABLE_SCHEMA"], (string)dr["REF_TABLE_NAME"]]; pkTable.Catalog = this; constraint = new StandardForeignKeyConstraint( constraintName, pkTable, cnstTable); fkeys.Add(constraintName, constraint); } constraint = fkeys[constraintName]; var cp = new StandardForeignKeyColumnPair( constraint.PKTable.Columns[(string)dr["REF_COLUMN_NAME"]], constraint.ConstraintTable.Columns[(string)dr["COLUMN_NAME"]]); constraint.Columns.Add(cp); } catch (Exception ex) { Console.WriteLine(@"Failed reading constraint: {0}", ex.Message); } } foreach (string constraintName in fkeys.Keys) { ForeignKeyConstraints.Add(fkeys[constraintName]); foreach (var columnPair in fkeys[constraintName].Columns) { columnPair.FKColumn.FKConstraint = fkeys[constraintName]; } } } private DataTable GetConstraintInformation() { var table = new DataTable(); var sb = new System.Text.StringBuilder(); sb.Append(" select object_name(constid) CONSTRAINT_NAME, "); sb.Append( " db_name() TABLE_CATALOG, SCHEMA_NAME(o1.uid) TABLE_SCHEMA, o1.name TABLE_NAME, c1.name COLUMN_NAME,"); sb.Append( " db_name() REF_TABLE_CATALOG, SCHEMA_NAME(o2.uid) REF_TABLE_SCHEMA, o2.name REF_TABLE_NAME, c2.name REF_COLUMN_NAME"); sb.Append(" from sysforeignkeys a"); sb.Append(" INNER JOIN syscolumns c1"); sb.Append(" ON a.fkeyid = c1.id"); sb.Append(" AND a.fkey = c1.colid"); sb.Append(" INNER JOIN syscolumns c2"); sb.Append(" ON a.rkeyid = c2.id"); sb.Append(" AND a.rkey = c2.colid"); sb.Append(" INNER JOIN sysobjects o1"); sb.Append(" ON c1.id = o1.id"); sb.Append(" INNER JOIN sysobjects o2"); sb.Append(" ON c2.id = o2.id"); //sb.Append(" WHERE constid in ("); //sb.Append(" SELECT object_id(CONSTRAINT_NAME)"); //sb.Append(" FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS)"); OpenConnection(); try { var cn = (SqlConnection)Connection; using (var cmd = cn.CreateCommand()) { cmd.CommandText = sb.ToString(); cmd.CommandType = CommandType.Text; using (var da = new SqlDataAdapter(cmd)) { da.Fill(table); } } } finally { CloseConnection(); } return table; } protected override void LoadDescriptions() { DataTable dt = GetColumnsDescriptionInformation(); foreach (DataRow dr in dt.Rows) { try { var schema = (string) dr["SchemaOwner"]; var objectName = (string) dr["ObjectName"]; var objectType = (string) dr["ObjectType"]; var description = (string) dr["Description"]; if (dr.IsNull("ColumnName")) { if (objectType == "U ") Tables[CatalogName, schema, objectName].ObjectDescription = description; else if (objectType == "V ") Views[CatalogName, schema, objectName].ObjectDescription = description; else if (objectType == "P ") Procedures[CatalogName, schema, objectName].ObjectDescription = description; } else Tables[CatalogName, schema, objectName].Columns[(string) dr["ColumnName"]].ColumnDescription = description; } catch (Exception ex) { Console.WriteLine(@"Failed reading descriptions: {0}", ex.Message); } } } private DataTable GetColumnsDescriptionInformation() { var table = new DataTable(); var sb = new System.Text.StringBuilder(); sb.Append(" SELECT s.name AS SchemaOwner,"); sb.Append(" o.Name AS ObjectName,"); sb.Append(" o.type AS ObjectType,"); sb.Append(" c.name AS ColumnName,"); sb.Append(" ep.value AS Description"); sb.Append(" FROM sys.objects o INNER JOIN sys.extended_properties ep"); sb.Append(" ON o.object_id = ep.major_id"); sb.Append(" INNER JOIN sys.schemas s"); sb.Append(" ON o.schema_id = s.schema_id"); sb.Append(" LEFT JOIN syscolumns c"); sb.Append(" ON ep.minor_id = c.colid"); sb.Append(" AND ep.major_id = c.id"); sb.Append(" WHERE (o.type ='U' AND c.name IS NOT NULL) OR "); sb.Append(" ((o.type ='U' OR o.type ='V' OR o.type ='P') AND c.name IS NULL AND ep.name LIKE '%Description')"); sb.Append(" ORDER BY SchemaOwner, ObjectName, ObjectType, ColumnName"); OpenConnection(); try { var cn = (SqlConnection)Connection; using (var cmd = cn.CreateCommand()) { cmd.CommandText = sb.ToString(); cmd.CommandType = CommandType.Text; using (var da = new SqlDataAdapter(cmd)) { da.Fill(table); } } } finally { CloseConnection(); } return table; } protected override DBStructure GetProcedureSchema(IDbConnection cn) { var ds = new DBStructure(); var scn = (SqlConnection)cn; //.GetSchema("Procedures", new string[] { Catalog }); var sb = new System.Text.StringBuilder(); if (scn.ServerVersion.StartsWith("08")) { sb.AppendLine(Properties.Resources.SqlServerGetProcedures2000); } else { sb.AppendLine(Properties.Resources.SqlServerGetProcedures2005); } sb.AppendLine(); sb.AppendLine(Properties.Resources.SqlServerGetParameters); using (SqlCommand cmd = scn.CreateCommand()) { cmd.CommandText = sb.ToString(); cmd.CommandType = CommandType.Text; using (var da = new SqlDataAdapter(cmd)) { da.TableMappings.Add("Table", "INFORMATION_SCHEMA_ROUTINES"); da.TableMappings.Add("Table1", "INFORMATION_SCHEMA_PARAMETERS"); ds.EnforceConstraints = false; da.Fill(ds); } } return ds; } protected override IStoredProcedureInfo CreateProcedureInfo(DBStructure.INFORMATION_SCHEMA_ROUTINESRow dr) { return new SqlStoredProcedureInfo(dr, this); } public override IDbConnection CreateConnection() { return new SqlConnection(ConnectionString); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using Relisten.Api.Models; using Dapper; using Relisten.Vendor; using Relisten.Data; using System.Text.RegularExpressions; using Microsoft.Extensions.Logging; using System.Diagnostics; using System.IO; using HtmlAgilityPack; using System.Globalization; using System.Net; using Hangfire.Server; using Hangfire.Console; using Microsoft.Extensions.Configuration; namespace Relisten.Import { public class PanicStreamComImporter : ImporterBase { public const string DataSourceName = "panicstream.com"; protected SourceService _sourceService { get; set; } protected SourceSetService _sourceSetService { get; set; } protected SourceReviewService _sourceReviewService { get; set; } protected SourceTrackService _sourceTrackService { get; set; } protected VenueService _venueService { get; set; } protected TourService _tourService { get; set; } protected ILogger<PanicStreamComImporter> _log { get; set; } public IConfiguration _configuration { get; } readonly LinkService linkService; public PanicStreamComImporter( DbService db, VenueService venueService, TourService tourService, SourceService sourceService, SourceSetService sourceSetService, SourceReviewService sourceReviewService, SourceTrackService sourceTrackService, LinkService linkService, ILogger<PanicStreamComImporter> log, IConfiguration configuration ) : base(db) { this.linkService = linkService; this._sourceService = sourceService; this._venueService = venueService; this._tourService = tourService; this._log = log; _configuration = configuration; _sourceReviewService = sourceReviewService; _sourceTrackService = sourceTrackService; _sourceSetService = sourceSetService; } public override string ImporterName => "panicstream.com"; public override ImportableData ImportableDataForArtist(Artist artist) { return ImportableData.Sources; } private static Regex ShowDirMatcher = new Regex(@"href=""([0-9_]+)([a-z]?)\/"">[0-9_]+[a-z]?\/<\/a>\s+([0-9A-Za-z: -]+)\s+-"); private static Regex TrackPrefixFinder = new Regex(@"^((?:\d{2,3} )|(?:[Ww][sS]?[pP][0-9-]+(?:[.]|EQ)?(?:[dD]\d+)?[tT]\d+\.(?!mp3|m4a|MP3|M4A))|(?:(?:d\d+)?t\d+) )"); private static Regex Mp3FileFinder = new Regex(@" href=""(.*\.(?:mp3|m4a|MP3|M4A))"""); private static Regex TxtFileFinder = new Regex(@" href=""(.*\.txt)"""); private async Task<string> FetchUrl(string url, PerformContext ctx) { url = url.Replace("&amp;", "&"); ctx?.WriteLine("Fetching URL: " + url); var page = await http.GetAsync(url); if (page.StatusCode != HttpStatusCode.OK) { var e = new Exception("URL fetch failed: " + url); e.Data["url"] = url; e.Data["StatusCode"] = page.StatusCode; throw e; } return await page.Content.ReadAsStringAsync(); } private string PanicIndexUrl() { return "https://www.panicstream.com/streams/wsp/relisten__/slim-metadata.json?key=" + _configuration["PANIC_KEY"]; } private static string PanicShowUrl(string panicDate) { return "https://www.panicstream.com/streams/wsp/" + panicDate + "/"; } private static string PanicShowFileUrl(string panicDate, string fileName) { return PanicShowUrl(panicDate) + fileName; } public override async Task<ImportStats> ImportDataForArtist(Artist artist, ArtistUpstreamSource src, PerformContext ctx) { var stats = new ImportStats(); await PreloadData(artist); var contents = await FetchUrl(PanicIndexUrl(), ctx); var tracks = JsonConvert.DeserializeObject<List<PanicStream.PanicStreamTrack>>(contents); var tracksByShow = tracks .Where(t => t.SourceName != null) .GroupBy(t => t.ShowDate) .Select(g => new { ShowDate = g.Key, Sources = g .GroupBy(subg => subg.SourceName) .Select(subg => new { SourceName = subg.Key, Tracks = subg.ToList() }) }) .ToList(); ctx?.WriteLine($"Found {tracksByShow.Count} shows"); var prog = ctx?.WriteProgressBar(); await tracksByShow.AsyncForEachWithProgress(prog, async grp => { foreach (var source in grp.Sources) { try { await ProcessShow(stats, artist, src, grp.ShowDate, source.SourceName, source.Tracks, ctx); } catch(Exception e) { ctx?.WriteLine("EXCEPTION: " + e.Message); ctx?.WriteLine("Source name: " + source.SourceName); ctx?.WriteLine(e.ToString()); ctx?.WriteLine(JsonConvert.SerializeObject(source)); } } }); ctx?.WriteLine("Rebuilding shows..."); await RebuildShows(artist); ctx?.WriteLine("Rebuilding years..."); await RebuildYears(artist); return stats; } public override Task<ImportStats> ImportSpecificShowDataForArtist(Artist artist, ArtistUpstreamSource src, string showIdentifier, PerformContext ctx) { return Task.FromResult(new ImportStats()); } private IDictionary<string, Source> existingSources = new Dictionary<string, Source>(); async Task PreloadData(Artist artist) { existingSources = (await _sourceService.AllForArtist(artist)). GroupBy(src => src.upstream_identifier). ToDictionary(grp => grp.Key, grp => grp.First()); } private async Task ProcessShow(ImportStats stats, Artist artist, ArtistUpstreamSource upstreamSrc, string showDate, string sourceName, IList<PanicStream.PanicStreamTrack> sourceTracks, PerformContext ctx) { var upstreamId = sourceName; var dbSource = existingSources.GetValue(upstreamId); var panicUpdatedAt = sourceTracks .Where(t => t.System.ParsedModificationTime.HasValue) .Max(t => t.System.ParsedModificationTime.Value); if (dbSource != null && dbSource.updated_at <= panicUpdatedAt) { return; } var isUpdate = dbSource != null; var src = new Source { artist_id = artist.id, display_date = showDate, is_soundboard = false, is_remaster = false, has_jamcharts = false, avg_rating = 0, num_reviews = 0, avg_rating_weighted = 0, upstream_identifier = upstreamId, taper_notes = "", updated_at = panicUpdatedAt }; if (isUpdate) { src.id = dbSource.id; } dbSource = await _sourceService.Save(src); existingSources[dbSource.upstream_identifier] = dbSource; if (isUpdate) { stats.Updated++; } else { stats.Created++; stats.Created += (await linkService.AddLinksForSource(dbSource, new[] { new Link { source_id = dbSource.id, for_ratings = false, for_source = true, for_reviews = false, upstream_source_id = upstreamSrc.upstream_source_id, url = $"https://www.panicstream.com/vault/widespread-panic/{dbSource.display_date.Substring(0, 4)}-streams/", label = "View show page on panicstream.com" } })).Count(); } var dbSet = await _sourceSetService.Update(dbSource, new SourceSet { source_id = dbSource.id, index = 0, is_encore = false, name = "Default Set", updated_at = panicUpdatedAt }); stats.Created++; var trackIndex = 0; var mp3s = sourceTracks .OrderBy(t => t.FileName) .Select(t => { var trackName = t.FileName .Replace(".mp3", "") .Replace(".MP3", "") .Replace(".M4A", "") .Replace(".m4a", "") .Trim(); var cleanedTrackName = Regex.Replace(trackName, @"(wsp[0-9-]+d\d+t\d+\.)|(^\d+ ?-? ?)", "").Trim(); if(cleanedTrackName.Length != 0) { trackName = cleanedTrackName; } trackIndex++; return new SourceTrack { source_id = dbSource.id, source_set_id = dbSet.id, track_position = trackIndex, duration = ((int?)t.Composite?.CalculatedDuration.TotalSeconds ?? (int?)0).Value, title = trackName, slug = SlugifyTrack(trackName), mp3_url = t.AbsoluteUrl(_configuration["PANIC_KEY"]), updated_at = panicUpdatedAt, artist_id = artist.id }; }); ResetTrackSlugCounts(); await _sourceTrackService.InsertAll(dbSource, mp3s); stats.Created += mp3s.Count(); } } } namespace Relisten.Import.PanicStream { public class PanicStreamShowSystem { public string FileModifyDate { get; set; } public DateTime? ParsedModificationTime { get { if (DateTime.TryParseExact(FileModifyDate, "yyyy:MM:dd HH:mm:sszzz", null, DateTimeStyles.AssumeUniversal, out var res)) { return res; } return null; } } } public class PanicStreamShowComposite { public string Duration { get; set; } private TimeSpan? _calculatedDuration = null; public TimeSpan CalculatedDuration { get { if (_calculatedDuration == null) { if(Duration.EndsWith(" s (approx)")) { _calculatedDuration = TimeSpan.FromSeconds(double.Parse(Duration.Replace(" s (approx)", ""))); } else { var parts = Duration .Replace(" (approx)", "") .Split(':') .Select(i => i.Length == 1 ? i : i.TrimStart('0')) .Select(i => i.Length == 0 ? "0" : i) .Select(i => int.Parse(i)) .ToList(); _calculatedDuration = TimeSpan.FromSeconds((parts[0] * 60 * 60) + (parts[1] * 60) + parts[2]); } } return _calculatedDuration.Value; } } } public class PanicStreamTrack { public string SourceFile { get; set; } private string _fileName = null; public string FileName => SourceName != null ? _fileName : null; private string _sourceName = null; public string SourceName { get { if (_sourceName == null) { var parts = SourceFile.Split('/'); if (parts.Length == 3 && Regex.IsMatch(parts[1], @"\d{4}_\d{2}_\d{2}[a-zA-Z]*")) { _sourceName = parts[1]; _fileName = parts[2]; } } return _sourceName; } } private string _showDate = null; public string ShowDate { get { if (_showDate == null && SourceName != null) { _showDate = Regex.Replace(SourceName.Replace('_', '-'), @"(\d)([^0-9-]+)", @"$1"); } return _showDate; } } public string AbsoluteUrl(string key) => "https://www.panicstream.com/streams/wsp/" + SourceFile.Substring(3) + "?key=" + key; public PanicStreamShowSystem System { get; set; } public PanicStreamShowComposite Composite { get; set; } } }
using System; using System.ComponentModel; using System.Data; namespace CslaGenerator.Metadata { public class GenerationParameters : INotifyPropertyChanged { #region State Fields private bool _saveBeforeGenerate = true; private TargetFramework _targetFramework = TargetFramework.CSLA40; private bool _backupOldSource = false; private bool _separateNamespaces = true; private bool _separateBaseClasses = false; private bool _activeObjects = false; private bool _useDotDesignerFileNameConvention = true; private bool _recompileTemplates = false; private bool _nullableSupport = false; private CodeLanguage _outputLanguage = CodeLanguage.CSharp; private CslaPropertyMode _propertyMode = CslaPropertyMode.Default; private UIEnvironment _generatedUIEnvironment = UIEnvironment.WinForms_WPF; private bool _useChildDataPortal = true; private Authorization _generateAuthorization = Authorization.FullSupport; private HeaderVerbosity _headerVerbosity = HeaderVerbosity.Full; private bool _useBypassPropertyChecks = true; private bool _useSingleCriteria = false; private bool _forceReadOnlyProperties = false; private string _baseFilenameSuffix = string.Empty; private string _extendedFilenameSuffix = string.Empty; private string _classCommentFilenameSuffix = string.Empty; private bool _separateClassComment = false; private string _utilitiesFolder = String.Empty; private string _utilitiesNamespace = String.Empty; private bool _generateSprocs = true; private bool _oneSpFilePerObject = true; private bool _generateDatabaseClass = true; #endregion #region Properties public bool SaveBeforeGenerate { get { return _saveBeforeGenerate; } set { if (_saveBeforeGenerate == value) return; _saveBeforeGenerate = value; OnPropertyChanged(""); } } public TargetFramework TargetFramework { get { return _targetFramework; } set { if (_targetFramework == value) return; _targetFramework = value; OnPropertyChanged(""); } } public bool BackupOldSource { get { return _backupOldSource; } set { if (_backupOldSource == value) return; _backupOldSource = value; OnPropertyChanged(""); } } public bool SeparateNamespaces { get { return _separateNamespaces; } set { if (_separateNamespaces == value) return; _separateNamespaces = value; OnPropertyChanged(""); } } public bool SeparateBaseClasses { get { return _separateBaseClasses; } set { if (_separateBaseClasses == value) return; _separateBaseClasses = value; OnPropertyChanged(""); } } public bool ActiveObjects { get { return _activeObjects; } set { if (_activeObjects == value) return; _activeObjects = value; OnPropertyChanged(""); } } public bool UseDotDesignerFileNameConvention { get { return false; } set { if (value) BaseFilenameSuffix = ".Designer"; if (_useDotDesignerFileNameConvention == value) return; _useDotDesignerFileNameConvention = value; OnPropertyChanged(""); } } public bool RecompileTemplates { get { return _recompileTemplates; } set { if (_recompileTemplates == value) return; _recompileTemplates = value; OnPropertyChanged(""); } } public CodeLanguage OutputLanguage { get { return _outputLanguage; } set { if (_outputLanguage == value) return; _outputLanguage = value; OnPropertyChanged(""); } } public bool NullableSupport { get { return _nullableSupport; } set { if (_nullableSupport == value) return; _nullableSupport = value; OnPropertyChanged(""); } } public CslaPropertyMode PropertyMode { get { return _propertyMode; } set { if (_propertyMode == value) return; _propertyMode = value; OnPropertyChanged(""); } } public UIEnvironment GeneratedUIEnvironment { get { return _generatedUIEnvironment; } set { if (_generatedUIEnvironment == value) return; _generatedUIEnvironment = value; OnPropertyChanged(""); } } public bool UseChildDataPortal { get { return _useChildDataPortal; } set { if (_useChildDataPortal == value) return; _useChildDataPortal = value; OnPropertyChanged(""); } } public Authorization GenerateAuthorization { get { return _generateAuthorization; } set { if (_generateAuthorization == value) return; _generateAuthorization = value; OnPropertyChanged(""); } } public HeaderVerbosity HeaderVerbosity { get { return _headerVerbosity; } set { if (_headerVerbosity == value) return; _headerVerbosity = value; OnPropertyChanged(""); } } public bool UseBypassPropertyChecks { get { return _useBypassPropertyChecks; } set { if (_useBypassPropertyChecks == value) return; _useBypassPropertyChecks = value; OnPropertyChanged(""); } } public bool UseSingleCriteria { get { return _useSingleCriteria; } set { if (_useSingleCriteria == value) return; _useSingleCriteria = value; OnPropertyChanged(""); } } public bool ForceReadOnlyProperties { get { return _forceReadOnlyProperties; } set { if (_forceReadOnlyProperties == value) return; _forceReadOnlyProperties = value; OnPropertyChanged(""); } } public string BaseFilenameSuffix { get { return _baseFilenameSuffix; } set { value = value.Trim().Replace(" ", " ").Replace(' ', '_'); if (_baseFilenameSuffix == value) return; _baseFilenameSuffix = value; OnPropertyChanged(""); } } public string ExtendedFilenameSuffix { get { return _extendedFilenameSuffix; } set { value = value.Trim().Replace(" ", " ").Replace(' ', '_'); if (_extendedFilenameSuffix == value) return; _extendedFilenameSuffix = value; OnPropertyChanged(""); } } public string ClassCommentFilenameSuffix { get { return _classCommentFilenameSuffix; } set { value = value.Trim().Replace(" ", " ").Replace(' ', '_'); if (_classCommentFilenameSuffix == value) return; _classCommentFilenameSuffix = value; OnPropertyChanged(""); } } /// <summary> /// Separate class comments in a folder. /// </summary> /// <value> /// <c>true</c> if Separate class comments in a folder; otherwise, <c>false</c>. /// </value> public bool SeparateClassComment { get { return _separateClassComment; } set { if (_separateClassComment == value) return; _separateClassComment = value; OnPropertyChanged(""); } } public string UtilitiesNamespace { get { return _utilitiesNamespace; } set { value = value.Trim().Replace(" ", " ").Replace(' ', '_'); if (_utilitiesNamespace == value) return; _utilitiesNamespace = value; OnPropertyChanged(""); } } public string UtilitiesFolder { get { return _utilitiesFolder; } set { value = value.Trim().Replace(" ", " ").Replace(' ', '_'); if (_utilitiesFolder == value) return; _utilitiesFolder = value; OnPropertyChanged(""); } } public bool GenerateSprocs { get { return _generateSprocs; } set { if (_generateSprocs == value) return; _generateSprocs = value; OnPropertyChanged(""); } } public bool OneSpFilePerObject { get { return _oneSpFilePerObject; } set { if (_oneSpFilePerObject == value) return; _oneSpFilePerObject = value; OnPropertyChanged(""); } } public bool GenerateDatabaseClass { get { return _generateDatabaseClass; } set { if (_generateDatabaseClass == value) return; _generateDatabaseClass = value; OnPropertyChanged(""); } } #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged(string propertyName) { _Dirty = true; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } private bool _Dirty = false; [Browsable(false)] internal bool Dirty { get { return _Dirty; } set { _Dirty = value; } } #endregion internal GenerationParameters Clone() { GenerationParameters obj = null; try { obj = (GenerationParameters)Util.ObjectCloner.CloneShallow(this); obj._Dirty = false; } catch (Exception ex) { Console.WriteLine(ex.Message); } return obj; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Globalization { /*=================================TaiwanCalendar========================== ** ** Taiwan calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar. ** That is, ** Taiwan year = Gregorian year - 1911. So 1912/01/01 A.D. is Taiwan 1/01/01 ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1912/01/01 9999/12/31 ** Taiwan 01/01/01 8088/12/31 ============================================================================*/ [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class TaiwanCalendar : Calendar { // // The era value for the current era. // // Since // Gregorian Year = Era Year + yearOffset // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 //m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911); // Initialize our era info. static internal EraInfo[] taiwanEraInfo = new EraInfo[] { new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; internal static volatile Calendar s_defaultInstance; internal GregorianCalendarHelper helper; /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of TaiwanCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new TaiwanCalendar(); } return (s_defaultInstance); } internal static readonly DateTime calendarMinValue = new DateTime(1912, 1, 1); [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } // Return the type of the Taiwan calendar. // public TaiwanCalendar() { try { new CultureInfo("zh-TW"); } catch (ArgumentException e) { throw new TypeInitializationException(this.GetType().ToString(), e); } helper = new GregorianCalendarHelper(this, taiwanEraInfo); } internal override CalendarId ID { get { return CalendarId.TAIWAN; } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. [System.Runtime.InteropServices.ComVisible(false)] public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } public override int[] Eras { get { return (helper.Eras); } } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, helper.MaxYear)); } twoDigitYearMax = value; } } // For Taiwan calendar, four digit year is not used. // Therefore, for any two digit number, we just return the original number. public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_NeedPosNum); } Contract.EndContractBlock(); if (year > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, helper.MaxYear)); } return (year); } } }
using UnityEngine; using System.Collections; using UnityEngine.Events; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.EventSystems; [ExecuteInEditMode] //Lets us set up buttons from inspector option public class RadialMenu : MonoBehaviour { #region Variables public List<RadialMenuButton> Buttons; public GameObject buttonPrefab; [Range(0f, 1f)] public float buttonThickness = 0.5f; public Color buttonColor = Color.white; public float offsetDistance = 1; [Range(0, 359)] public float offsetRotation; public bool rotateIcons; public float iconMargin; public bool isShown; public bool HideOnRelease; //Has to be public to keep state from editor -> play mode? public List<GameObject> menuButtons; private int currentHover = -1; private int currentPress = -1; #endregion #region Unity Methods private void Start() { if (Application.isPlaying) { if (!isShown) { transform.localScale = Vector3.zero; } RegenerateButtons(); } } private void Update() { //Keep track of pressed button and constantly invoke Hold event if (currentPress != -1) { Buttons[currentPress].Press(); } } #endregion #region Interaction //Turns and Angle and Event type into a button action private void InteractButton(float angle, ButtonEvent evt) //Can't pass ExecuteEvents as parameter? Unity gives error { //Get button ID from angle float buttonAngle = 360f / Buttons.Count; //Each button is an arc with this angle angle = mod((angle + offsetRotation), 360); //Offset the touch coordinate with our offset int buttonID = (int)mod(((angle + (buttonAngle / 2f)) / buttonAngle), Buttons.Count); //Convert angle into ButtonID (This is the magic) var pointer = new PointerEventData(EventSystem.current); //Create a new EventSystem (UI) Event //If we changed buttons while moving, un-hover and un-click the last button we were on if (currentHover != buttonID && currentHover != -1) { ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerUpHandler); ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler); } if (evt == ButtonEvent.click) //Click button if click, and keep track of current press { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerDownHandler); currentPress = 1; Buttons[buttonID].Click(); } else if (evt == ButtonEvent.unclick) //Clear press id to stop invoking OnHold method { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerUpHandler); currentPress = -1; } else if (evt == ButtonEvent.hoverOn && currentHover != buttonID) // Show hover UI event (darken button etc) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerEnterHandler); } currentHover = buttonID; //Set current hover ID, need this to un-hover if selected button changes } /* * Public methods to call Interact */ public void HoverButton(float angle) { InteractButton(angle, ButtonEvent.hoverOn); } public void ClickButton(float angle) { InteractButton(angle, ButtonEvent.click); } public void UnClickButton(float angle) { InteractButton(angle, ButtonEvent.unclick); } public void ToggleMenu() { if (isShown) { HideMenu(true); } else { ShowMenu(); } } public void StopTouching() { if (currentHover != -1) { var pointer = new PointerEventData(EventSystem.current); ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler); currentHover = -1; } } /* * Public methods to Show/Hide menu */ public void ShowMenu() { if (!isShown) { isShown = true; StopCoroutine("TweenMenuScale"); StartCoroutine("TweenMenuScale", isShown); } } public RadialMenuButton GetButton(int id) { if (id < Buttons.Count) { return Buttons[id]; } return null; } public void HideMenu(bool force) { if (isShown && (HideOnRelease || force)) { isShown = false; StopCoroutine("TweenMenuScale"); StartCoroutine("TweenMenuScale", isShown); } } //Simple tweening for menu, scales linearly from 0 to 1 and 1 to 0 private IEnumerator TweenMenuScale(bool show) { float targetScale = 0; Vector3 Dir = -1 * Vector3.one; if (show) { targetScale = 1; Dir = Vector3.one; } int i = 0; //Sanity check for infinite loops while (i < 250 && ((show && transform.localScale.x < targetScale) || (!show && transform.localScale.x > targetScale))) { transform.localScale += Dir * Time.deltaTime * 4f; //Tweening function - currently 0.25 second linear yield return true; i++; } transform.localScale = Dir * targetScale; StopCoroutine("TweenMenuScale"); } #endregion #region Generation //Creates all the button Arcs and populates them with desired icons public void RegenerateButtons() { RemoveAllButtons(); for (int i = 0; i < Buttons.Count; i++) { // Initial placement/instantiation GameObject newButton = (GameObject)Instantiate(buttonPrefab); newButton.transform.SetParent(transform); newButton.transform.localScale = Vector3.one; newButton.GetComponent<RectTransform>().offsetMax = Vector2.zero; newButton.GetComponent<RectTransform>().offsetMin = Vector2.zero; //Setup button arc UICircle circle = newButton.GetComponent<UICircle>(); if (buttonThickness == 1) { circle.fill = true; } else { circle.thickness = (int)(buttonThickness * ((float)GetComponent<RectTransform>().rect.width / 2f)); } int fillPerc = (int)(100f / Buttons.Count); circle.fillPercent = fillPerc; circle.color = buttonColor; //Final placement/rotation float angle = ((360 / Buttons.Count) * i) + offsetRotation; newButton.transform.localEulerAngles = new Vector3(0, 0, angle); newButton.layer = 4; //UI Layer newButton.transform.localPosition = Vector3.zero; if (circle.fillPercent < 55) { float angleRad = (angle * Mathf.PI) / 180f; Vector2 angleVector = new Vector2(-Mathf.Cos(angleRad), -Mathf.Sin(angleRad)); newButton.transform.localPosition += (Vector3)angleVector * offsetDistance; } //Place and populate Button Icon GameObject buttonIcon = newButton.GetComponentInChildren<RadialButtonIcon>().gameObject; if (Buttons[i].ButtonIcon == null) { buttonIcon.SetActive(false); } else { buttonIcon.GetComponent<Image>().sprite = Buttons[i].ButtonIcon; buttonIcon.transform.localPosition = new Vector2(-1 * ((newButton.GetComponent<RectTransform>().rect.width / 2f) - (circle.thickness / 2f)), 0); //Min icon size from thickness and arc float scale1 = Mathf.Abs(circle.thickness); float R = Mathf.Abs(buttonIcon.transform.localPosition.x); float bAngle = (359f * circle.fillPercent * 0.01f * Mathf.PI) / 180f; float scale2 = (R * 2 * Mathf.Sin(bAngle / 2f)); if (circle.fillPercent > 24) //Scale calc doesn't work for > 90 degrees { scale2 = float.MaxValue; } float iconScale = Mathf.Min(scale1, scale2) - iconMargin; buttonIcon.GetComponent<RectTransform>().sizeDelta = new Vector2(iconScale, iconScale); //Rotate icons all vertically if desired if (!rotateIcons) { buttonIcon.transform.eulerAngles = GetComponentInParent<Canvas>().transform.eulerAngles; } } menuButtons.Add(newButton); } } public void AddButton(RadialMenuButton newButton) { Buttons.Add(newButton); RegenerateButtons(); } private void RemoveAllButtons() { if (menuButtons == null) { menuButtons = new List<GameObject>(); } for (int i = 0; i < menuButtons.Count; i++) { DestroyImmediate(menuButtons[i]); } menuButtons = new List<GameObject>(); } #endregion #region Utility private float mod(float a, float b) { return a - b * Mathf.Floor(a / b); } #endregion } [System.Serializable] public class RadialMenuButton { public Sprite ButtonIcon; public UnityEvent OnClick; public UnityEvent OnHold; public void Press() { OnHold.Invoke(); } public void Click() { OnClick.Invoke(); } } public enum ButtonEvent { hoverOn, hoverOff, click, unclick }
/* * Copyright (c) 2015, Wisconsin Robotics * 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 Wisconsin Robotics 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 WISCONSIN ROBOTICS 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 BadgerJaus.Util; namespace BadgerJaus.Messages.LocalVectorDriver { public class ReportLocalVector : QueryLocalVector { protected override int CommandCode { get { return JausCommandCode.REPORT_LOCAL_VECTOR; } } public const double MAX_SPEED = 327.67; public const double MIN_SPEED = 0; public const double MAX_Z = 35000; public const double MIN_Z = -10000; public const double MAX_HEADING_ROLL_PITCH = System.Math.PI; public const double MIN_HEADING_ROLL_PITCH = -System.Math.PI; protected JausUnsignedShort speed; protected JausUnsignedInteger z; protected JausUnsignedShort heading; protected JausUnsignedShort roll; protected JausUnsignedShort pitch; protected override void InitFieldData() { base.InitFieldData(); speed = new JausUnsignedShort(); z = new JausUnsignedInteger(); heading = new JausUnsignedShort(); roll = new JausUnsignedShort(); pitch = new JausUnsignedShort(); } public bool isFieldSet(int bit) { return presence.IsBitSet(bit); } public double GetSpeed() { return speed.ScaleValueToDouble(MIN_SPEED, MAX_SPEED); } public double GetZ() { return z.ScaleValueToDouble(MIN_Z, MAX_Z); } public double GetHeading() { return heading.ScaleValueToDouble(MIN_HEADING_ROLL_PITCH, MAX_HEADING_ROLL_PITCH); } public double GetRoll() { return roll.ScaleValueToDouble(MIN_HEADING_ROLL_PITCH, MAX_HEADING_ROLL_PITCH); } public double GetPitch() { return pitch.ScaleValueToDouble(MIN_HEADING_ROLL_PITCH, MAX_HEADING_ROLL_PITCH); } public void SetSpeed(double speed) { this.speed.SetValueFromDouble(speed, MIN_SPEED, MAX_SPEED); presence.ToggleBit(SPEED_BIT, true); } public void SetZ(double z) { this.z.SetValueFromDouble(z, MIN_Z, MAX_Z); presence.ToggleBit(Z_BIT, true); } public void SetHeading(double heading) { this.heading.SetValueFromDouble(heading, MIN_HEADING_ROLL_PITCH, MAX_HEADING_ROLL_PITCH); presence.ToggleBit(HEADING_BIT, true); } public void SetRoll(double roll) { this.roll.SetValueFromDouble(roll, MIN_HEADING_ROLL_PITCH, MAX_HEADING_ROLL_PITCH); presence.ToggleBit(ROLL_BIT, true); } public void SetPitch(double pitch) { this.pitch.SetValueFromDouble(pitch, MIN_HEADING_ROLL_PITCH, MAX_HEADING_ROLL_PITCH); presence.ToggleBit(PITCH_BIT, true); } public override int GetPayloadSize() { int size = 0; size += base.GetPayloadSize(); if (presence.IsBitSet(SPEED_BIT)) size += JausBaseType.SHORT_BYTE_SIZE; if (presence.IsBitSet(Z_BIT)) size += JausBaseType.INT_BYTE_SIZE; if (presence.IsBitSet(HEADING_BIT)) size += JausBaseType.SHORT_BYTE_SIZE; if (presence.IsBitSet(ROLL_BIT)) size += JausBaseType.SHORT_BYTE_SIZE; if (presence.IsBitSet(PITCH_BIT)) size += JausBaseType.SHORT_BYTE_SIZE; return size; } protected override bool SetPayloadFromJausBuffer(byte[] buffer, int index, out int indexOffset) { indexOffset = index; if (buffer.Length < index + this.MessageSize() - base.MessageSize()) { return false; // Not Enough Size } //presence.getPresenceVector().setFromJausBuffer(buffer, index); base.SetPayloadFromJausBuffer(buffer, indexOffset, out indexOffset); if (presence.IsBitSet(SPEED_BIT)) { speed.Deserialize(buffer, indexOffset, out indexOffset); } if (presence.IsBitSet(Z_BIT)) { z.Deserialize(buffer, indexOffset, out indexOffset); } if (presence.IsBitSet(HEADING_BIT)) { heading.Deserialize(buffer, indexOffset, out indexOffset); } if (presence.IsBitSet(ROLL_BIT)) { roll.Deserialize(buffer, indexOffset, out indexOffset); } if (presence.IsBitSet(PITCH_BIT)) { pitch.Deserialize(buffer, indexOffset, out indexOffset); } return true; } protected override bool PayloadToJausBuffer(byte[] buffer, int index, out int indexOffset) { base.PayloadToJausBuffer(buffer, index, out indexOffset); if (presence.IsBitSet(SPEED_BIT)) { if (!speed.Serialize(buffer, indexOffset, out indexOffset)) return false; } if (presence.IsBitSet(Z_BIT)) { if (!z.Serialize(buffer, indexOffset, out indexOffset)) return false; } if (presence.IsBitSet(HEADING_BIT)) { if (!heading.Serialize(buffer, indexOffset, out indexOffset)) return false; } if (presence.IsBitSet(ROLL_BIT)) { if (!roll.Serialize(buffer, indexOffset, out indexOffset)) return false; } if (presence.IsBitSet(PITCH_BIT)) { if (!pitch.Serialize(buffer, indexOffset, out indexOffset)) return false; } return true; } } }
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Updating.Resources { public sealed class UpdateToOneRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>> { private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext; private readonly ReadWriteFakers _fakers = new(); public UpdateToOneRelationshipTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext) { _testContext = testContext; testContext.UseController<WorkItemsController>(); testContext.UseController<WorkItemGroupsController>(); testContext.UseController<RgbColorsController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddResourceDefinition<ImplicitlyChangingWorkItemDefinition>(); }); } [Fact] public async Task Can_clear_ManyToOne_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Assignee = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { assignee = new { data = (object)null } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Assignee.Should().BeNull(); }); } [Fact] public async Task Can_create_OneToOne_relationship_from_principal_side() { // Arrange WorkItemGroup existingGroup = _fakers.WorkItemGroup.Generate(); existingGroup.Color = _fakers.RgbColor.Generate(); RgbColor existingColor = _fakers.RgbColor.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingGroup, existingColor); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItemGroups", id = existingGroup.StringId, relationships = new { color = new { data = new { type = "rgbColors", id = existingColor.StringId } } } } }; string route = $"/workItemGroups/{existingGroup.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { List<RgbColor> colorsInDatabase = await dbContext.RgbColors.Include(rgbColor => rgbColor.Group).ToListAsync(); RgbColor colorInDatabase1 = colorsInDatabase.Single(color => color.Id == existingGroup.Color.Id); colorInDatabase1.Group.Should().BeNull(); RgbColor colorInDatabase2 = colorsInDatabase.Single(color => color.Id == existingColor.Id); colorInDatabase2.Group.Should().NotBeNull(); colorInDatabase2.Group.Id.Should().Be(existingGroup.Id); }); } [Fact] public async Task Can_replace_OneToOne_relationship_from_dependent_side() { // Arrange List<WorkItemGroup> existingGroups = _fakers.WorkItemGroup.Generate(2); existingGroups[0].Color = _fakers.RgbColor.Generate(); existingGroups[1].Color = _fakers.RgbColor.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Groups.AddRange(existingGroups); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "rgbColors", id = existingGroups[0].Color.StringId, relationships = new { group = new { data = new { type = "workItemGroups", id = existingGroups[1].StringId } } } } }; string route = $"/rgbColors/{existingGroups[0].Color.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { List<WorkItemGroup> groupsInDatabase = await dbContext.Groups.Include(group => group.Color).ToListAsync(); WorkItemGroup groupInDatabase1 = groupsInDatabase.Single(group => group.Id == existingGroups[0].Id); groupInDatabase1.Color.Should().BeNull(); WorkItemGroup groupInDatabase2 = groupsInDatabase.Single(group => group.Id == existingGroups[1].Id); groupInDatabase2.Color.Should().NotBeNull(); groupInDatabase2.Color.Id.Should().Be(existingGroups[0].Color.Id); List<RgbColor> colorsInDatabase = await dbContext.RgbColors.Include(color => color.Group).ToListAsync(); RgbColor colorInDatabase1 = colorsInDatabase.Single(color => color.Id == existingGroups[0].Color.Id); colorInDatabase1.Group.Should().NotBeNull(); colorInDatabase1.Group.Id.Should().Be(existingGroups[1].Id); RgbColor colorInDatabase2 = colorsInDatabase.SingleOrDefault(color => color.Id == existingGroups[1].Color.Id); colorInDatabase2.Should().NotBeNull(); colorInDatabase2!.Group.Should().BeNull(); }); } [Fact] public async Task Can_clear_OneToOne_relationship() { // Arrange RgbColor existingColor = _fakers.RgbColor.Generate(); existingColor.Group = _fakers.WorkItemGroup.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.RgbColors.AddRange(existingColor); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "rgbColors", id = existingColor.StringId, relationships = new { group = new { data = (object)null } } } }; string route = $"/rgbColors/{existingColor.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { RgbColor colorInDatabase = await dbContext.RgbColors.Include(color => color.Group).FirstWithIdOrDefaultAsync(existingColor.Id); colorInDatabase.Group.Should().BeNull(); }); } [Fact] public async Task Can_replace_ManyToOne_relationship() { // Arrange List<UserAccount> existingUserAccounts = _fakers.UserAccount.Generate(2); existingUserAccounts[0].AssignedItems = _fakers.WorkItem.Generate(2).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.AddRange(existingUserAccounts); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingUserAccounts[0].AssignedItems.ElementAt(1).StringId, relationships = new { assignee = new { data = new { type = "userAccounts", id = existingUserAccounts[1].StringId } } } } }; string route = $"/workItems/{existingUserAccounts[0].AssignedItems.ElementAt(1).StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); await _testContext.RunOnDatabaseAsync(async dbContext => { int workItemId = existingUserAccounts[0].AssignedItems.ElementAt(1).Id; WorkItem workItemInDatabase2 = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(workItemId); workItemInDatabase2.Assignee.Should().NotBeNull(); workItemInDatabase2.Assignee.Id.Should().Be(existingUserAccounts[1].Id); }); } [Fact] public async Task Can_create_relationship_with_include() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingWorkItem, existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { assignee = new { data = new { type = "userAccounts", id = existingUserAccount.StringId } } } } }; string route = $"/workItems/{existingWorkItem.StringId}?include=assignee"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); string description = $"{existingWorkItem.Description}{ImplicitlyChangingWorkItemDefinition.Suffix}"; responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Type.Should().Be("workItems"); responseDocument.Data.SingleValue.Id.Should().Be(existingWorkItem.StringId); responseDocument.Data.SingleValue.Attributes["description"].Should().Be(description); responseDocument.Data.SingleValue.Relationships.Should().NotBeEmpty(); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Type.Should().Be("userAccounts"); responseDocument.Included[0].Id.Should().Be(existingUserAccount.StringId); responseDocument.Included[0].Attributes["firstName"].Should().Be(existingUserAccount.FirstName); responseDocument.Included[0].Attributes["lastName"].Should().Be(existingUserAccount.LastName); responseDocument.Included[0].Relationships.Should().NotBeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Assignee.Should().NotBeNull(); workItemInDatabase.Assignee.Id.Should().Be(existingUserAccount.Id); }); } [Fact] public async Task Can_replace_relationship_with_include_and_fieldsets() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Assignee = _fakers.UserAccount.Generate(); UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingWorkItem, existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { assignee = new { data = new { type = "userAccounts", id = existingUserAccount.StringId } } } } }; string route = $"/workItems/{existingWorkItem.StringId}?fields[workItems]=description,assignee&include=assignee&fields[userAccounts]=lastName"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); string description = $"{existingWorkItem.Description}{ImplicitlyChangingWorkItemDefinition.Suffix}"; responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Type.Should().Be("workItems"); responseDocument.Data.SingleValue.Id.Should().Be(existingWorkItem.StringId); responseDocument.Data.SingleValue.Attributes.Should().HaveCount(1); responseDocument.Data.SingleValue.Attributes["description"].Should().Be(description); responseDocument.Data.SingleValue.Relationships.Should().HaveCount(1); responseDocument.Data.SingleValue.Relationships["assignee"].Data.SingleValue.Id.Should().Be(existingUserAccount.StringId); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Type.Should().Be("userAccounts"); responseDocument.Included[0].Id.Should().Be(existingUserAccount.StringId); responseDocument.Included[0].Attributes.Should().HaveCount(1); responseDocument.Included[0].Attributes["lastName"].Should().Be(existingUserAccount.LastName); responseDocument.Included[0].Relationships.Should().BeNull(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Assignee.Should().NotBeNull(); workItemInDatabase.Assignee.Id.Should().Be(existingUserAccount.Id); }); } [Fact] public async Task Cannot_create_for_missing_relationship_type() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { assignee = new { data = new { id = Unknown.StringId.For<UserAccount, long>() } } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body must include 'type' element."); error.Detail.Should().StartWith("Expected 'type' element in 'assignee' relationship. - Request body: <<"); } [Fact] public async Task Cannot_create_for_unknown_relationship_type() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { assignee = new { data = new { type = Unknown.ResourceType, id = Unknown.StringId.For<UserAccount, long>() } } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body includes unknown resource type."); error.Detail.Should().StartWith($"Resource type '{Unknown.ResourceType}' does not exist. - Request body: <<"); } [Fact] public async Task Cannot_create_for_missing_relationship_ID() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { assignee = new { data = new { type = "userAccounts" } } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body must include 'id' element."); error.Detail.Should().StartWith("Expected 'id' element in 'assignee' relationship. - Request body: <<"); } [Fact] public async Task Cannot_create_with_unknown_relationship_ID() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); string userAccountId = Unknown.StringId.For<UserAccount, long>(); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { assignee = new { data = new { type = "userAccounts", id = userAccountId } } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'userAccounts' with ID '{userAccountId}' in relationship 'assignee' does not exist."); } [Fact] public async Task Cannot_create_on_relationship_type_mismatch() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { assignee = new { data = new { type = "rgbColors", id = "0A0B0C" } } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Relationship contains incompatible resource type."); error.Detail.Should().StartWith("Relationship 'assignee' contains incompatible resource type 'rgbColors'. - Request body: <<"); } [Fact] public async Task Cannot_create_with_data_array_in_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingWorkItem, existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { assignee = new { data = new[] { new { type = "userAccounts", id = existingUserAccount.StringId } } } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Expected single data element for to-one relationship."); error.Detail.Should().StartWith("Expected single data element for 'assignee' relationship. - Request body: <<"); } [Fact] public async Task Can_clear_cyclic_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); existingWorkItem.Parent = existingWorkItem; await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { parent = new { data = (object)null } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Parent).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Parent.Should().BeNull(); }); } [Fact] public async Task Can_assign_cyclic_relationship() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { parent = new { data = new { type = "workItems", id = existingWorkItem.StringId } } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Parent).FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Parent.Should().NotBeNull(); workItemInDatabase.Parent.Id.Should().Be(existingWorkItem.Id); }); } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // /* * Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DynamoDBv2.Model { /// <summary> /// Container for the parameters to the DeleteItem operation. /// Deletes a single item in a table by primary key. You can perform a conditional delete /// operation that deletes the item if it exists, or if it has an expected attribute value. /// /// /// <para> /// In addition to deleting an item, you can also return the item's attribute values in /// the same operation, using the <i>ReturnValues</i> parameter. /// </para> /// /// <para> /// Unless you specify conditions, the <i>DeleteItem</i> is an idempotent operation; running /// it multiple times on the same item or attribute does <i>not</i> result in an error /// response. /// </para> /// /// <para> /// Conditional deletes are useful for deleting items only if specific conditions are /// met. If those conditions are met, DynamoDB performs the delete. Otherwise, the item /// is not deleted. /// </para> /// </summary> public partial class DeleteItemRequest : AmazonDynamoDBRequest { private ConditionalOperator _conditionalOperator; private string _conditionExpression; private Dictionary<string, ExpectedAttributeValue> _expected = new Dictionary<string, ExpectedAttributeValue>(); private Dictionary<string, string> _expressionAttributeNames = new Dictionary<string, string>(); private Dictionary<string, AttributeValue> _expressionAttributeValues = new Dictionary<string, AttributeValue>(); private Dictionary<string, AttributeValue> _key = new Dictionary<string, AttributeValue>(); private ReturnConsumedCapacity _returnConsumedCapacity; private ReturnItemCollectionMetrics _returnItemCollectionMetrics; private ReturnValue _returnValues; private string _tableName; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public DeleteItemRequest() { } /// <summary> /// Instantiates DeleteItemRequest with the parameterized properties /// </summary> /// <param name="tableName">The name of the table from which to delete the item.</param> /// <param name="key">A map of attribute names to <i>AttributeValue</i> objects, representing the primary key of the item to delete. For the primary key, you must provide all of the attributes. For example, with a hash type primary key, you only need to provide the hash attribute. For a hash-and-range type primary key, you must provide both the hash attribute and the range attribute.</param> public DeleteItemRequest(string tableName, Dictionary<string, AttributeValue> key) { _tableName = tableName; _key = key; } /// <summary> /// Instantiates DeleteItemRequest with the parameterized properties /// </summary> /// <param name="tableName">The name of the table from which to delete the item.</param> /// <param name="key">A map of attribute names to <i>AttributeValue</i> objects, representing the primary key of the item to delete. For the primary key, you must provide all of the attributes. For example, with a hash type primary key, you only need to provide the hash attribute. For a hash-and-range type primary key, you must provide both the hash attribute and the range attribute.</param> /// <param name="returnValues">Use <i>ReturnValues</i> if you want to get the item attributes as they appeared before they were deleted. For <i>DeleteItem</i>, the valid values are: <ul> <li> <code>NONE</code> - If <i>ReturnValues</i> is not specified, or if its value is <code>NONE</code>, then nothing is returned. (This setting is the default for <i>ReturnValues</i>.) </li> <li> <code>ALL_OLD</code> - The content of the old item is returned. </li> </ul></param> public DeleteItemRequest(string tableName, Dictionary<string, AttributeValue> key, ReturnValue returnValues) { _tableName = tableName; _key = key; _returnValues = returnValues; } /// <summary> /// Gets and sets the property ConditionalOperator. <important> /// <para> /// There is a newer parameter available. Use <i>ConditionExpression</i> instead. Note /// that if you use <i>ConditionalOperator</i> and <i> ConditionExpression </i> at the /// same time, DynamoDB will return a <i>ValidationException</i> exception. /// </para> /// </important> /// <para> /// A logical operator to apply to the conditions in the <i>Expected</i> map: /// </para> /// <ul> <li> /// <para> /// <code>AND</code> - If all of the conditions evaluate to true, then the entire map /// evaluates to true. /// </para> /// </li> <li> /// <para> /// <code>OR</code> - If at least one of the conditions evaluate to true, then the entire /// map evaluates to true. /// </para> /// </li> </ul> /// <para> /// If you omit <i>ConditionalOperator</i>, then <code>AND</code> is the default. /// </para> /// /// <para> /// The operation will succeed only if the entire map evaluates to true. /// </para> /// <note> /// <para> /// This parameter does not support attributes of type List or Map. /// </para> /// </note> /// </summary> public ConditionalOperator ConditionalOperator { get { return this._conditionalOperator; } set { this._conditionalOperator = value; } } // Check to see if ConditionalOperator property is set internal bool IsSetConditionalOperator() { return this._conditionalOperator != null; } /// <summary> /// Gets and sets the property ConditionExpression. /// <para> /// A condition that must be satisfied in order for a conditional <i>DeleteItem</i> to /// succeed. /// </para> /// /// <para> /// An expression can contain any of the following: /// </para> /// <ul> <li> /// <para> /// Boolean functions: <code>attribute_exists | attribute_not_exists | contains | begins_with</code> /// /// </para> /// /// <para> /// These function names are case-sensitive. /// </para> /// </li> <li> /// <para> /// Comparison operators: <code> = | &#x3C;&#x3E; | &#x3C; | &#x3E; | &#x3C;= | &#x3E;= /// | BETWEEN | IN</code> /// </para> /// </li> <li> /// <para> /// Logical operators: <code>AND | OR | NOT</code> /// </para> /// </li> </ul> /// <para> /// For more information on condition expressions, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html">Specifying /// Conditions</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> public string ConditionExpression { get { return this._conditionExpression; } set { this._conditionExpression = value; } } // Check to see if ConditionExpression property is set internal bool IsSetConditionExpression() { return this._conditionExpression != null; } /// <summary> /// Gets and sets the property Expected. <important> /// <para> /// There is a newer parameter available. Use <i>ConditionExpression</i> instead. Note /// that if you use <i>Expected</i> and <i> ConditionExpression </i> at the same time, /// DynamoDB will return a <i>ValidationException</i> exception. /// </para> /// </important> /// <para> /// A map of attribute/condition pairs. <i>Expected</i> provides a conditional block for /// the <i>DeleteItem</i> operation. /// </para> /// /// <para> /// Each element of <i>Expected</i> consists of an attribute name, a comparison operator, /// and one or more values. DynamoDB compares the attribute with the value(s) you supplied, /// using the comparison operator. For each <i>Expected</i> element, the result of the /// evaluation is either true or false. /// </para> /// /// <para> /// If you specify more than one element in the <i>Expected</i> map, then by default all /// of the conditions must evaluate to true. In other words, the conditions are ANDed /// together. (You can use the <i>ConditionalOperator</i> parameter to OR the conditions /// instead. If you do this, then at least one of the conditions must evaluate to true, /// rather than all of them.) /// </para> /// /// <para> /// If the <i>Expected</i> map evaluates to true, then the conditional operation succeeds; /// otherwise, it fails. /// </para> /// /// <para> /// <i>Expected</i> contains the following: /// </para> /// <ul> <li> /// <para> /// <i>AttributeValueList</i> - One or more values to evaluate against the supplied attribute. /// The number of values in the list depends on the <i>ComparisonOperator</i> being used. /// </para> /// /// <para> /// For type Number, value comparisons are numeric. /// </para> /// /// <para> /// String value comparisons for greater than, equals, or less than are based on ASCII /// character code values. For example, <code>a</code> is greater than <code>A</code>, /// and <code>a</code> is greater than <code>B</code>. For a list of code values, see /// <a href="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters" >http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>. /// </para> /// /// <para> /// For type Binary, DynamoDB treats each byte of the binary data as unsigned when it /// compares binary values. /// </para> /// </li> <li> /// <para> /// <i>ComparisonOperator</i> - A comparator for evaluating attributes in the <i>AttributeValueList</i>. /// When performing the comparison, DynamoDB uses strongly consistent reads. /// </para> /// /// <para> /// The following comparison operators are available: /// </para> /// /// <para> /// <code>EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH /// | IN | BETWEEN</code> /// </para> /// /// <para> /// The following are descriptions of each comparison operator. /// </para> /// <ul> <li> /// <para> /// <code>EQ</code> : Equal. <code>EQ</code> is supported for all datatypes, including /// lists and maps. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains /// an <i>AttributeValue</i> element of a different type than the one provided in the /// request, the value does not match. For example, <code>{"S":"6"}</code> does not equal /// <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> does not equal <code>{"NS":["6", /// "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>NE</code> : Not equal. <code>NE</code> is supported for all datatypes, including /// lists and maps. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String, /// Number, Binary, String Set, Number Set, or Binary Set. If an item contains an <i>AttributeValue</i> /// of a different type than the one provided in the request, the value does not match. /// For example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> /// does not equal <code>{"NS":["6", "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>LE</code> : Less than or equal. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, or Binary (not a set type). If an item contains an <i>AttributeValue</i> /// element of a different type than the one provided in the request, the value does not /// match. For example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. /// Also, <code>{"N":"6"}</code> does not compare to <code>{"NS":["6", "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>LT</code> : Less than. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String, /// Number, or Binary (not a set type). If an item contains an <i>AttributeValue</i> element /// of a different type than the one provided in the request, the value does not match. /// For example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. Also, <code>{"N":"6"}</code> /// does not compare to <code>{"NS":["6", "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>GE</code> : Greater than or equal. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, or Binary (not a set type). If an item contains an <i>AttributeValue</i> /// element of a different type than the one provided in the request, the value does not /// match. For example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. /// Also, <code>{"N":"6"}</code> does not compare to <code>{"NS":["6", "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>GT</code> : Greater than. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, or Binary (not a set type). If an item contains an <i>AttributeValue</i> /// element of a different type than the one provided in the request, the value does not /// match. For example, <code>{"S":"6"}</code> does not equal <code>{"N":"6"}</code>. /// Also, <code>{"N":"6"}</code> does not compare to <code>{"NS":["6", "2", "1"]}</code>. /// </para> /// <p/> </li> <li> /// <para> /// <code>NOT_NULL</code> : The attribute exists. <code>NOT_NULL</code> is supported for /// all datatypes, including lists and maps. /// </para> /// <note> /// <para> /// This operator tests for the existence of an attribute, not its data type. If the data /// type of attribute "<code>a</code>" is null, and you evaluate it using <code>NOT_NULL</code>, /// the result is a Boolean <i>true</i>. This result is because the attribute "<code>a</code>" /// exists; its data type is not relevant to the <code>NOT_NULL</code> comparison operator. /// </para> /// </note> </li> <li> /// <para> /// <code>NULL</code> : The attribute does not exist. <code>NULL</code> is supported for /// all datatypes, including lists and maps. /// </para> /// <note> /// <para> /// This operator tests for the nonexistence of an attribute, not its data type. If the /// data type of attribute "<code>a</code>" is null, and you evaluate it using <code>NULL</code>, /// the result is a Boolean <i>false</i>. This is because the attribute "<code>a</code>" /// exists; its data type is not relevant to the <code>NULL</code> comparison operator. /// </para> /// </note> </li> <li> /// <para> /// <code>CONTAINS</code> : Checks for a subsequence, or value in a set. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, or Binary (not a set type). If the target attribute of the comparison /// is of type String, then the operator checks for a substring match. If the target attribute /// of the comparison is of type Binary, then the operator looks for a subsequence of /// the target that matches the input. If the target attribute of the comparison is a /// set ("<code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), then the operator /// evaluates to true if it finds an exact match with any member of the set. /// </para> /// /// <para> /// CONTAINS is supported for lists: When evaluating "<code>a CONTAINS b</code>", "<code>a</code>" /// can be a list; however, "<code>b</code>" cannot be a set, a map, or a list. /// </para> /// </li> <li> /// <para> /// <code>NOT_CONTAINS</code> : Checks for absence of a subsequence, or absence of a value /// in a set. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> element of type /// String, Number, or Binary (not a set type). If the target attribute of the comparison /// is a String, then the operator checks for the absence of a substring match. If the /// target attribute of the comparison is Binary, then the operator checks for the absence /// of a subsequence of the target that matches the input. If the target attribute of /// the comparison is a set ("<code>SS</code>", "<code>NS</code>", or "<code>BS</code>"), /// then the operator evaluates to true if it <i>does not</i> find an exact match with /// any member of the set. /// </para> /// /// <para> /// NOT_CONTAINS is supported for lists: When evaluating "<code>a NOT CONTAINS b</code>", /// "<code>a</code>" can be a list; however, "<code>b</code>" cannot be a set, a map, /// or a list. /// </para> /// </li> <li> /// <para> /// <code>BEGINS_WITH</code> : Checks for a prefix. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain only one <i>AttributeValue</i> of type String /// or Binary (not a Number or a set type). The target attribute of the comparison must /// be of type String or Binary (not a Number or a set type). /// </para> /// <p/> </li> <li> /// <para> /// <code>IN</code> : Checks for matching elements within two sets. /// </para> /// /// <para> /// <i>AttributeValueList</i> can contain one or more <i>AttributeValue</i> elements of /// type String, Number, or Binary (not a set type). These attributes are compared against /// an existing set type attribute of an item. If any elements of the input set are present /// in the item attribute, the expression evaluates to true. /// </para> /// </li> <li> /// <para> /// <code>BETWEEN</code> : Greater than or equal to the first value, and less than or /// equal to the second value. /// </para> /// /// <para> /// <i>AttributeValueList</i> must contain two <i>AttributeValue</i> elements of the same /// type, either String, Number, or Binary (not a set type). A target attribute matches /// if the target value is greater than, or equal to, the first element and less than, /// or equal to, the second element. If an item contains an <i>AttributeValue</i> element /// of a different type than the one provided in the request, the value does not match. /// For example, <code>{"S":"6"}</code> does not compare to <code>{"N":"6"}</code>. Also, /// <code>{"N":"6"}</code> does not compare to <code>{"NS":["6", "2", "1"]}</code> /// </para> /// </li> </ul> </li> </ul> /// <para> /// For usage examples of <i>AttributeValueList</i> and <i>ComparisonOperator</i>, see /// <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.html">Legacy /// Conditional Parameters</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// For backward compatibility with previous DynamoDB releases, the following parameters /// can be used instead of <i>AttributeValueList</i> and <i>ComparisonOperator</i>: /// </para> /// <ul> <li> /// <para> /// <i>Value</i> - A value for DynamoDB to compare with an attribute. /// </para> /// </li> <li> /// <para> /// <i>Exists</i> - A Boolean value that causes DynamoDB to evaluate the value before /// attempting the conditional operation: /// </para> /// <ul> <li> /// <para> /// If <i>Exists</i> is <code>true</code>, DynamoDB will check to see if that attribute /// value already exists in the table. If it is found, then the condition evaluates to /// true; otherwise the condition evaluate to false. /// </para> /// </li> <li> /// <para> /// If <i>Exists</i> is <code>false</code>, DynamoDB assumes that the attribute value /// does <i>not</i> exist in the table. If in fact the value does not exist, then the /// assumption is valid and the condition evaluates to true. If the value is found, despite /// the assumption that it does not exist, the condition evaluates to false. /// </para> /// </li> </ul> /// <para> /// Note that the default value for <i>Exists</i> is <code>true</code>. /// </para> /// </li> </ul> /// <para> /// The <i>Value</i> and <i>Exists</i> parameters are incompatible with <i>AttributeValueList</i> /// and <i>ComparisonOperator</i>. Note that if you use both sets of parameters at once, /// DynamoDB will return a <i>ValidationException</i> exception. /// </para> /// <note> /// <para> /// This parameter does not support attributes of type List or Map. /// </para> /// </note> /// </summary> public Dictionary<string, ExpectedAttributeValue> Expected { get { return this._expected; } set { this._expected = value; } } // Check to see if Expected property is set internal bool IsSetExpected() { return this._expected != null && this._expected.Count > 0; } /// <summary> /// Gets and sets the property ExpressionAttributeNames. /// <para> /// One or more substitution tokens for attribute names in an expression. The following /// are some use cases for using <i>ExpressionAttributeNames</i>: /// </para> /// <ul> <li> /// <para> /// To access an attribute whose name conflicts with a DynamoDB reserved word. /// </para> /// </li> <li> /// <para> /// To create a placeholder for repeating occurrences of an attribute name in an expression. /// </para> /// </li> <li> /// <para> /// To prevent special characters in an attribute name from being misinterpreted in an /// expression. /// </para> /// </li> </ul> /// <para> /// Use the <b>#</b> character in an expression to dereference an attribute name. For /// example, consider the following attribute name: /// </para> /// <ul><li> /// <para> /// <code>Percentile</code> /// </para> /// </li></ul> /// <para> /// The name of this attribute conflicts with a reserved word, so it cannot be used directly /// in an expression. (For the complete list of reserved words, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html">Reserved /// Words</a> in the <i>Amazon DynamoDB Developer Guide</i>). To work around this, you /// could specify the following for <i>ExpressionAttributeNames</i>: /// </para> /// <ul><li> /// <para> /// <code>{"#P":"Percentile"}</code> /// </para> /// </li></ul> /// <para> /// You could then use this substitution in an expression, as in this example: /// </para> /// <ul><li> /// <para> /// <code>#P = :val</code> /// </para> /// </li></ul> <note> /// <para> /// Tokens that begin with the <b>:</b> character are <i>expression attribute values</i>, /// which are placeholders for the actual value at runtime. /// </para> /// </note> /// <para> /// For more information on expression attribute names, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html">Accessing /// Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> public Dictionary<string, string> ExpressionAttributeNames { get { return this._expressionAttributeNames; } set { this._expressionAttributeNames = value; } } // Check to see if ExpressionAttributeNames property is set internal bool IsSetExpressionAttributeNames() { return this._expressionAttributeNames != null && this._expressionAttributeNames.Count > 0; } /// <summary> /// Gets and sets the property ExpressionAttributeValues. /// <para> /// One or more values that can be substituted in an expression. /// </para> /// /// <para> /// Use the <b>:</b> (colon) character in an expression to dereference an attribute value. /// For example, suppose that you wanted to check whether the value of the <i>ProductStatus</i> /// attribute was one of the following: /// </para> /// /// <para> /// <code>Available | Backordered | Discontinued</code> /// </para> /// /// <para> /// You would first need to specify <i>ExpressionAttributeValues</i> as follows: /// </para> /// /// <para> /// <code>{ ":avail":{"S":"Available"}, ":back":{"S":"Backordered"}, ":disc":{"S":"Discontinued"} /// }</code> /// </para> /// /// <para> /// You could then use these values in an expression, such as this: /// </para> /// /// <para> /// <code>ProductStatus IN (:avail, :back, :disc)</code> /// </para> /// /// <para> /// For more information on expression attribute values, go to <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html">Specifying /// Conditions</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> public Dictionary<string, AttributeValue> ExpressionAttributeValues { get { return this._expressionAttributeValues; } set { this._expressionAttributeValues = value; } } // Check to see if ExpressionAttributeValues property is set internal bool IsSetExpressionAttributeValues() { return this._expressionAttributeValues != null && this._expressionAttributeValues.Count > 0; } /// <summary> /// Gets and sets the property Key. /// <para> /// A map of attribute names to <i>AttributeValue</i> objects, representing the primary /// key of the item to delete. /// </para> /// /// <para> /// For the primary key, you must provide all of the attributes. For example, with a hash /// type primary key, you only need to provide the hash attribute. For a hash-and-range /// type primary key, you must provide both the hash attribute and the range attribute. /// </para> /// </summary> public Dictionary<string, AttributeValue> Key { get { return this._key; } set { this._key = value; } } // Check to see if Key property is set internal bool IsSetKey() { return this._key != null && this._key.Count > 0; } /// <summary> /// Gets and sets the property ReturnConsumedCapacity. /// </summary> public ReturnConsumedCapacity ReturnConsumedCapacity { get { return this._returnConsumedCapacity; } set { this._returnConsumedCapacity = value; } } // Check to see if ReturnConsumedCapacity property is set internal bool IsSetReturnConsumedCapacity() { return this._returnConsumedCapacity != null; } /// <summary> /// Gets and sets the property ReturnItemCollectionMetrics. /// <para> /// A value that if set to <code>SIZE</code>, the response includes statistics about item /// collections, if any, that were modified during the operation are returned in the response. /// If set to <code>NONE</code> (the default), no statistics are returned. /// </para> /// </summary> public ReturnItemCollectionMetrics ReturnItemCollectionMetrics { get { return this._returnItemCollectionMetrics; } set { this._returnItemCollectionMetrics = value; } } // Check to see if ReturnItemCollectionMetrics property is set internal bool IsSetReturnItemCollectionMetrics() { return this._returnItemCollectionMetrics != null; } /// <summary> /// Gets and sets the property ReturnValues. /// <para> /// Use <i>ReturnValues</i> if you want to get the item attributes as they appeared before /// they were deleted. For <i>DeleteItem</i>, the valid values are: /// </para> /// <ul> <li> /// <para> /// <code>NONE</code> - If <i>ReturnValues</i> is not specified, or if its value is <code>NONE</code>, /// then nothing is returned. (This setting is the default for <i>ReturnValues</i>.) /// </para> /// </li> <li> /// <para> /// <code>ALL_OLD</code> - The content of the old item is returned. /// </para> /// </li> </ul> /// </summary> public ReturnValue ReturnValues { get { return this._returnValues; } set { this._returnValues = value; } } // Check to see if ReturnValues property is set internal bool IsSetReturnValues() { return this._returnValues != null; } /// <summary> /// Gets and sets the property TableName. /// <para> /// The name of the table from which to delete the item. /// </para> /// </summary> public string TableName { get { return this._tableName; } set { this._tableName = value; } } // Check to see if TableName property is set internal bool IsSetTableName() { return this._tableName != 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. namespace System.Xml.Serialization { using System; using System.IO; using System.Collections; using System.ComponentModel; using System.Threading; using System.Reflection; using System.Security; using System.Globalization; ///<internalonly/> public abstract class XmlSerializationGeneratedCode { internal void Init(TempAssembly tempAssembly) { } // this method must be called at the end of serialization internal void Dispose() { } } internal class XmlSerializationCodeGen { private readonly IndentedWriter _writer; private int _nextMethodNumber = 0; private readonly Hashtable _methodNames = new Hashtable(); private readonly ReflectionAwareCodeGen _raCodeGen; private readonly TypeScope[] _scopes; private readonly TypeDesc _stringTypeDesc = null; private readonly TypeDesc _qnameTypeDesc = null; private readonly string _access; private readonly string _className; private TypeMapping[] _referencedMethods; private int _references = 0; private readonly Hashtable _generatedMethods = new Hashtable(); internal XmlSerializationCodeGen(IndentedWriter writer, TypeScope[] scopes, string access, string className) { _writer = writer; _scopes = scopes; if (scopes.Length > 0) { _stringTypeDesc = scopes[0].GetTypeDesc(typeof(string)); _qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName)); } _raCodeGen = new ReflectionAwareCodeGen(writer); _className = className; _access = access; } internal IndentedWriter Writer { get { return _writer; } } internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareCodeGen RaCodeGen { get { return _raCodeGen; } } internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } } internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal string Access { get { return _access; } } internal TypeScope[] Scopes { get { return _scopes; } } internal Hashtable MethodNames { get { return _methodNames; } } internal Hashtable GeneratedMethods { get { return _generatedMethods; } } internal virtual void GenerateMethod(TypeMapping mapping) { } internal void GenerateReferencedMethods() { while (_references > 0) { TypeMapping mapping = _referencedMethods[--_references]; GenerateMethod(mapping); } } internal string ReferenceMapping(TypeMapping mapping) { if (!mapping.IsSoap) { if (_generatedMethods[mapping] == null) { _referencedMethods = EnsureArrayIndex(_referencedMethods, _references); _referencedMethods[_references++] = mapping; } } return (string)_methodNames[mapping]; } private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) { if (a == null) return new TypeMapping[32]; if (index < a.Length) return a; TypeMapping[] b = new TypeMapping[a.Length + 32]; Array.Copy(a, 0, b, 0, index); return b; } internal void WriteQuotedCSharpString(string value) { _raCodeGen.WriteQuotedCSharpString(value); } internal void GenerateHashtableGetBegin(string privateName, string publicName) { _writer.Write(typeof(Hashtable).FullName); _writer.Write(" "); _writer.Write(privateName); _writer.WriteLine(" = null;"); _writer.Write("public override "); _writer.Write(typeof(Hashtable).FullName); _writer.Write(" "); _writer.Write(publicName); _writer.WriteLine(" {"); _writer.Indent++; _writer.WriteLine("get {"); _writer.Indent++; _writer.Write("if ("); _writer.Write(privateName); _writer.WriteLine(" == null) {"); _writer.Indent++; _writer.Write(typeof(Hashtable).FullName); _writer.Write(" _tmp = new "); _writer.Write(typeof(Hashtable).FullName); _writer.WriteLine("();"); } internal void GenerateHashtableGetEnd(string privateName) { _writer.Write("if ("); _writer.Write(privateName); _writer.Write(" == null) "); _writer.Write(privateName); _writer.WriteLine(" = _tmp;"); _writer.Indent--; _writer.WriteLine("}"); _writer.Write("return "); _writer.Write(privateName); _writer.WriteLine(";"); _writer.Indent--; _writer.WriteLine("}"); _writer.Indent--; _writer.WriteLine("}"); } internal void GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings) { GenerateHashtableGetBegin(privateName, publicName); if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length) { for (int i = 0; i < methods.Length; i++) { if (methods[i] == null) continue; _writer.Write("_tmp["); WriteQuotedCSharpString(xmlMappings[i].Key); _writer.Write("] = "); WriteQuotedCSharpString(methods[i]); _writer.WriteLine(";"); } } GenerateHashtableGetEnd(privateName); } internal void GenerateSupportedTypes(Type[] types) { _writer.Write("public override "); _writer.Write(typeof(bool).FullName); _writer.Write(" CanSerialize("); _writer.Write(typeof(Type).FullName); _writer.WriteLine(" type) {"); _writer.Indent++; Hashtable uniqueTypes = new Hashtable(); for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (uniqueTypes[type] != null) continue; if (DynamicAssemblies.IsTypeDynamic(type)) continue; if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments())) continue; uniqueTypes[type] = type; _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.WriteLine(")) return true;"); } _writer.WriteLine("return false;"); _writer.Indent--; _writer.WriteLine("}"); } internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) { baseSerializer = CodeIdentifier.MakeValid(baseSerializer); baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); _writer.WriteLine(); _writer.Write("public abstract class "); _writer.Write(CodeIdentifier.GetCSharpName(baseSerializer)); _writer.Write(" : "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName); _writer.WriteLine(" {"); _writer.Indent++; _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.WriteLine(" CreateReader() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(readerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.WriteLine(" CreateWriter() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(writerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Indent--; _writer.WriteLine("}"); return baseSerializer; } internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) { string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name)); serializerName = classes.AddUnique(serializerName + "Serializer", mapping); _writer.WriteLine(); _writer.Write("public sealed class "); _writer.Write(CodeIdentifier.GetCSharpName(serializerName)); _writer.Write(" : "); _writer.Write(baseSerializer); _writer.WriteLine(" {"); _writer.Indent++; _writer.WriteLine(); _writer.Write("public override "); _writer.Write(typeof(bool).FullName); _writer.Write(" CanDeserialize("); _writer.Write(typeof(XmlReader).FullName); _writer.WriteLine(" xmlReader) {"); _writer.Indent++; if (mapping.Accessor.Any) { _writer.WriteLine("return true;"); } else { _writer.Write("return xmlReader.IsStartElement("); WriteQuotedCSharpString(mapping.Accessor.Name); _writer.Write(", "); WriteQuotedCSharpString(mapping.Accessor.Namespace); _writer.WriteLine(");"); } _writer.Indent--; _writer.WriteLine("}"); if (writeMethod != null) { _writer.WriteLine(); _writer.Write("protected override void Serialize(object objectToSerialize, "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.WriteLine(" writer) {"); _writer.Indent++; _writer.Write("(("); _writer.Write(writerClass); _writer.Write(")writer)."); _writer.Write(writeMethod); _writer.Write("("); if (mapping is XmlMembersMapping) { _writer.Write("(object[])"); } _writer.WriteLine("objectToSerialize);"); _writer.Indent--; _writer.WriteLine("}"); } if (readMethod != null) { _writer.WriteLine(); _writer.Write("protected override object Deserialize("); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.WriteLine(" reader) {"); _writer.Indent++; _writer.Write("return (("); _writer.Write(readerClass); _writer.Write(")reader)."); _writer.Write(readMethod); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); } _writer.Indent--; _writer.WriteLine("}"); return serializerName; } private void GenerateTypedSerializers(Hashtable serializers) { string privateName = "typedSerializers"; GenerateHashtableGetBegin(privateName, "TypedSerializers"); foreach (string key in serializers.Keys) { _writer.Write("_tmp.Add("); WriteQuotedCSharpString(key); _writer.Write(", new "); _writer.Write((string)serializers[key]); _writer.WriteLine("());"); } GenerateHashtableGetEnd("typedSerializers"); } //GenerateGetSerializer(serializers, xmlMappings); private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappings) { _writer.Write("public override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName); _writer.Write(" GetSerializer("); _writer.Write(typeof(Type).FullName); _writer.WriteLine(" type) {"); _writer.Indent++; for (int i = 0; i < xmlMappings.Length; i++) { if (xmlMappings[i] is XmlTypeMapping) { Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (DynamicAssemblies.IsTypeDynamic(type)) continue; if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments())) continue; _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.Write(")) return new "); _writer.Write((string)serializers[xmlMappings[i].Key]); _writer.WriteLine("();"); } } _writer.WriteLine("return null;"); _writer.Indent--; _writer.WriteLine("}"); } internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Hashtable serializers) { _writer.WriteLine(); _writer.Write("public class XmlSerializerContract : global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializerImplementation).FullName); _writer.WriteLine(" {"); _writer.Indent++; _writer.Write("public override global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.Write(" Reader { get { return new "); _writer.Write(readerType); _writer.WriteLine("(); } }"); _writer.Write("public override global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.Write(" Writer { get { return new "); _writer.Write(writerType); _writer.WriteLine("(); } }"); GeneratePublicMethods(nameof(readMethods), "ReadMethods", readMethods, xmlMappings); GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings); GenerateTypedSerializers(serializers); GenerateSupportedTypes(types); GenerateGetSerializer(serializers, xmlMappings); _writer.Indent--; _writer.WriteLine("}"); } internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; return mapping.TypeDesc.CanBeElementValue; } } }