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 System.Linq; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// A PCI device /// First published in XenServer 6.0. /// </summary> public partial class PCI : XenObject<PCI> { #region Constructors public PCI() { } public PCI(string uuid, string class_name, string vendor_name, string device_name, XenRef<Host> host, string pci_id, List<XenRef<PCI>> dependencies, Dictionary<string, string> other_config, string subsystem_vendor_name, string subsystem_device_name, string driver_name) { this.uuid = uuid; this.class_name = class_name; this.vendor_name = vendor_name; this.device_name = device_name; this.host = host; this.pci_id = pci_id; this.dependencies = dependencies; this.other_config = other_config; this.subsystem_vendor_name = subsystem_vendor_name; this.subsystem_device_name = subsystem_device_name; this.driver_name = driver_name; } /// <summary> /// Creates a new PCI 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 PCI(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new PCI from a Proxy_PCI. /// </summary> /// <param name="proxy"></param> public PCI(Proxy_PCI proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given PCI. /// </summary> public override void UpdateFrom(PCI record) { uuid = record.uuid; class_name = record.class_name; vendor_name = record.vendor_name; device_name = record.device_name; host = record.host; pci_id = record.pci_id; dependencies = record.dependencies; other_config = record.other_config; subsystem_vendor_name = record.subsystem_vendor_name; subsystem_device_name = record.subsystem_device_name; driver_name = record.driver_name; } internal void UpdateFrom(Proxy_PCI proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; class_name = proxy.class_name == null ? null : proxy.class_name; vendor_name = proxy.vendor_name == null ? null : proxy.vendor_name; device_name = proxy.device_name == null ? null : proxy.device_name; host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host); pci_id = proxy.pci_id == null ? null : proxy.pci_id; dependencies = proxy.dependencies == null ? null : XenRef<PCI>.Create(proxy.dependencies); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); subsystem_vendor_name = proxy.subsystem_vendor_name == null ? null : proxy.subsystem_vendor_name; subsystem_device_name = proxy.subsystem_device_name == null ? null : proxy.subsystem_device_name; driver_name = proxy.driver_name == null ? null : proxy.driver_name; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this PCI /// 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("class_name")) class_name = Marshalling.ParseString(table, "class_name"); if (table.ContainsKey("vendor_name")) vendor_name = Marshalling.ParseString(table, "vendor_name"); if (table.ContainsKey("device_name")) device_name = Marshalling.ParseString(table, "device_name"); if (table.ContainsKey("host")) host = Marshalling.ParseRef<Host>(table, "host"); if (table.ContainsKey("pci_id")) pci_id = Marshalling.ParseString(table, "pci_id"); if (table.ContainsKey("dependencies")) dependencies = Marshalling.ParseSetRef<PCI>(table, "dependencies"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("subsystem_vendor_name")) subsystem_vendor_name = Marshalling.ParseString(table, "subsystem_vendor_name"); if (table.ContainsKey("subsystem_device_name")) subsystem_device_name = Marshalling.ParseString(table, "subsystem_device_name"); if (table.ContainsKey("driver_name")) driver_name = Marshalling.ParseString(table, "driver_name"); } public Proxy_PCI ToProxy() { Proxy_PCI result_ = new Proxy_PCI(); result_.uuid = uuid ?? ""; result_.class_name = class_name ?? ""; result_.vendor_name = vendor_name ?? ""; result_.device_name = device_name ?? ""; result_.host = host ?? ""; result_.pci_id = pci_id ?? ""; result_.dependencies = dependencies == null ? new string[] {} : Helper.RefListToStringArray(dependencies); result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.subsystem_vendor_name = subsystem_vendor_name ?? ""; result_.subsystem_device_name = subsystem_device_name ?? ""; result_.driver_name = driver_name ?? ""; return result_; } public bool DeepEquals(PCI other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._class_name, other._class_name) && Helper.AreEqual2(this._vendor_name, other._vendor_name) && Helper.AreEqual2(this._device_name, other._device_name) && Helper.AreEqual2(this._host, other._host) && Helper.AreEqual2(this._pci_id, other._pci_id) && Helper.AreEqual2(this._dependencies, other._dependencies) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._subsystem_vendor_name, other._subsystem_vendor_name) && Helper.AreEqual2(this._subsystem_device_name, other._subsystem_device_name) && Helper.AreEqual2(this._driver_name, other._driver_name); } public override string SaveChanges(Session session, string opaqueRef, PCI server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { PCI.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given PCI. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static PCI get_record(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_record(session.opaque_ref, _pci); else return new PCI(session.XmlRpcProxy.pci_get_record(session.opaque_ref, _pci ?? "").parse()); } /// <summary> /// Get a reference to the PCI instance with the specified UUID. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<PCI> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<PCI>.Create(session.XmlRpcProxy.pci_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given PCI. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static string get_uuid(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_uuid(session.opaque_ref, _pci); else return session.XmlRpcProxy.pci_get_uuid(session.opaque_ref, _pci ?? "").parse(); } /// <summary> /// Get the class_name field of the given PCI. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static string get_class_name(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_class_name(session.opaque_ref, _pci); else return session.XmlRpcProxy.pci_get_class_name(session.opaque_ref, _pci ?? "").parse(); } /// <summary> /// Get the vendor_name field of the given PCI. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static string get_vendor_name(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_vendor_name(session.opaque_ref, _pci); else return session.XmlRpcProxy.pci_get_vendor_name(session.opaque_ref, _pci ?? "").parse(); } /// <summary> /// Get the device_name field of the given PCI. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static string get_device_name(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_device_name(session.opaque_ref, _pci); else return session.XmlRpcProxy.pci_get_device_name(session.opaque_ref, _pci ?? "").parse(); } /// <summary> /// Get the host field of the given PCI. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static XenRef<Host> get_host(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_host(session.opaque_ref, _pci); else return XenRef<Host>.Create(session.XmlRpcProxy.pci_get_host(session.opaque_ref, _pci ?? "").parse()); } /// <summary> /// Get the pci_id field of the given PCI. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static string get_pci_id(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_pci_id(session.opaque_ref, _pci); else return session.XmlRpcProxy.pci_get_pci_id(session.opaque_ref, _pci ?? "").parse(); } /// <summary> /// Get the dependencies field of the given PCI. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static List<XenRef<PCI>> get_dependencies(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_dependencies(session.opaque_ref, _pci); else return XenRef<PCI>.Create(session.XmlRpcProxy.pci_get_dependencies(session.opaque_ref, _pci ?? "").parse()); } /// <summary> /// Get the other_config field of the given PCI. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static Dictionary<string, string> get_other_config(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_other_config(session.opaque_ref, _pci); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.pci_get_other_config(session.opaque_ref, _pci ?? "").parse()); } /// <summary> /// Get the subsystem_vendor_name field of the given PCI. /// First published in XenServer 6.2 SP1 Hotfix 11. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static string get_subsystem_vendor_name(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_subsystem_vendor_name(session.opaque_ref, _pci); else return session.XmlRpcProxy.pci_get_subsystem_vendor_name(session.opaque_ref, _pci ?? "").parse(); } /// <summary> /// Get the subsystem_device_name field of the given PCI. /// First published in XenServer 6.2 SP1 Hotfix 11. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static string get_subsystem_device_name(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_subsystem_device_name(session.opaque_ref, _pci); else return session.XmlRpcProxy.pci_get_subsystem_device_name(session.opaque_ref, _pci ?? "").parse(); } /// <summary> /// Get the driver_name field of the given PCI. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> public static string get_driver_name(Session session, string _pci) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_driver_name(session.opaque_ref, _pci); else return session.XmlRpcProxy.pci_get_driver_name(session.opaque_ref, _pci ?? "").parse(); } /// <summary> /// Set the other_config field of the given PCI. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _pci, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.pci_set_other_config(session.opaque_ref, _pci, _other_config); else session.XmlRpcProxy.pci_set_other_config(session.opaque_ref, _pci ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given PCI. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _pci, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.pci_add_to_other_config(session.opaque_ref, _pci, _key, _value); else session.XmlRpcProxy.pci_add_to_other_config(session.opaque_ref, _pci ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given PCI. If the key is not in that Map, then do nothing. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pci">The opaque_ref of the given pci</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _pci, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.pci_remove_from_other_config(session.opaque_ref, _pci, _key); else session.XmlRpcProxy.pci_remove_from_other_config(session.opaque_ref, _pci ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the PCIs known to the system. /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<PCI>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_all(session.opaque_ref); else return XenRef<PCI>.Create(session.XmlRpcProxy.pci_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the PCI Records at once, in a single XML RPC call /// First published in XenServer 6.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<PCI>, PCI> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pci_get_all_records(session.opaque_ref); else return XenRef<PCI>.Create<Proxy_PCI>(session.XmlRpcProxy.pci_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> /// PCI class name /// </summary> public virtual string class_name { get { return _class_name; } set { if (!Helper.AreEqual(value, _class_name)) { _class_name = value; NotifyPropertyChanged("class_name"); } } } private string _class_name = ""; /// <summary> /// Vendor name /// </summary> public virtual string vendor_name { get { return _vendor_name; } set { if (!Helper.AreEqual(value, _vendor_name)) { _vendor_name = value; NotifyPropertyChanged("vendor_name"); } } } private string _vendor_name = ""; /// <summary> /// Device name /// </summary> public virtual string device_name { get { return _device_name; } set { if (!Helper.AreEqual(value, _device_name)) { _device_name = value; NotifyPropertyChanged("device_name"); } } } private string _device_name = ""; /// <summary> /// Physical machine that owns the PCI device /// </summary> [JsonConverter(typeof(XenRefConverter<Host>))] public virtual XenRef<Host> host { get { return _host; } set { if (!Helper.AreEqual(value, _host)) { _host = value; NotifyPropertyChanged("host"); } } } private XenRef<Host> _host = new XenRef<Host>("OpaqueRef:NULL"); /// <summary> /// PCI ID of the physical device /// </summary> public virtual string pci_id { get { return _pci_id; } set { if (!Helper.AreEqual(value, _pci_id)) { _pci_id = value; NotifyPropertyChanged("pci_id"); } } } private string _pci_id = ""; /// <summary> /// List of dependent PCI devices /// </summary> [JsonConverter(typeof(XenRefListConverter<PCI>))] public virtual List<XenRef<PCI>> dependencies { get { return _dependencies; } set { if (!Helper.AreEqual(value, _dependencies)) { _dependencies = value; NotifyPropertyChanged("dependencies"); } } } private List<XenRef<PCI>> _dependencies = new List<XenRef<PCI>>() {}; /// <summary> /// Additional configuration /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; /// <summary> /// Subsystem vendor name /// First published in XenServer 6.2 SP1 Hotfix 11. /// </summary> public virtual string subsystem_vendor_name { get { return _subsystem_vendor_name; } set { if (!Helper.AreEqual(value, _subsystem_vendor_name)) { _subsystem_vendor_name = value; NotifyPropertyChanged("subsystem_vendor_name"); } } } private string _subsystem_vendor_name = ""; /// <summary> /// Subsystem device name /// First published in XenServer 6.2 SP1 Hotfix 11. /// </summary> public virtual string subsystem_device_name { get { return _subsystem_device_name; } set { if (!Helper.AreEqual(value, _subsystem_device_name)) { _subsystem_device_name = value; NotifyPropertyChanged("subsystem_device_name"); } } } private string _subsystem_device_name = ""; /// <summary> /// Driver name /// First published in XenServer 7.5. /// </summary> public virtual string driver_name { get { return _driver_name; } set { if (!Helper.AreEqual(value, _driver_name)) { _driver_name = value; NotifyPropertyChanged("driver_name"); } } } private string _driver_name = ""; } }
// 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.Reflection.Metadata.Cil.Decoder; using System.Reflection.Metadata.Cil.Visitor; using System.Reflection.Metadata.Decoding; using System.Text; namespace System.Reflection.Metadata.Cil { public struct CilProperty : ICilVisitable { private PropertyDefinition _propertyDef; private CilReaders _readers; private string _name; private MethodSignature<CilType> _signature; private IEnumerable<CilCustomAttribute> _customAttributes; private CilMethodDefinition _getter; private CilMethodDefinition _setter; private CilConstant _defaultValue; private bool _isDefaultValueInitialized; private bool _isGetterInitialized; private bool _isSetterInitialized; private PropertyAccessors _accessors; private bool _isSignatureInitialized; private CilTypeDefinition _typeDefinition; private int _token; internal static CilProperty Create(PropertyDefinition propertyDef, int token, ref CilReaders readers, CilTypeDefinition typeDefinition) { CilProperty property = new CilProperty(); property._typeDefinition = typeDefinition; property._propertyDef = propertyDef; property._readers = readers; property._isSignatureInitialized = false; property._isDefaultValueInitialized = false; property._isGetterInitialized = false; property._isSetterInitialized = false; property._token = token; property._accessors = propertyDef.GetAccessors(); return property; } internal int Token { get { return _token; } } public CilTypeDefinition DeclaringType { get { return _typeDefinition; } } public string Name { get { return CilDecoder.GetCachedValue(_propertyDef.Name, _readers, ref _name); } } public bool HasGetter { get { return !_accessors.Getter.IsNil; } } public bool HasSetter { get { return !_accessors.Setter.IsNil; } } public bool HasDefault { get { return Attributes.HasFlag(PropertyAttributes.HasDefault); } } public CilConstant DefaultValue { get { if (!_isDefaultValueInitialized) { if (!HasDefault) { throw new InvalidOperationException("Property doesn't have default value"); } _isDefaultValueInitialized = true; _defaultValue = GetDefaultValue(); } return _defaultValue; } } public CilMethodDefinition Getter { get { if (!_isGetterInitialized) { _isGetterInitialized = true; if (HasGetter) { _getter = CilMethodDefinition.Create(_accessors.Getter, ref _readers, _typeDefinition); } } return _getter; } } public CilMethodDefinition Setter { get { if (!_isSetterInitialized) { _isSetterInitialized = true; if (HasSetter) { _setter = CilMethodDefinition.Create(_accessors.Setter, ref _readers, _typeDefinition); } } return _setter; } } public MethodSignature<CilType> Signature { get { if (!_isSignatureInitialized) { _isSignatureInitialized = true; _signature = SignatureDecoder.DecodeMethodSignature(_propertyDef.Signature, _readers.Provider); } return _signature; } } public IEnumerable<CilCustomAttribute> CustomAttributes { get { if(_customAttributes == null) { _customAttributes = GetCustomAttributes(); } return _customAttributes; } } public PropertyAttributes Attributes { get { return _propertyDef.Attributes; } } public void Accept(ICilVisitor visitor) { visitor.Visit(this); } public string GetDecodedSignature() { string attributes = GetAttributesForSignature(); StringBuilder signature = new StringBuilder(); if (Signature.Header.IsInstance) { signature.Append("instance "); } signature.Append(Signature.ReturnType); return string.Format("{0}{1} {2}{3}", attributes, signature.ToString(), Name, CilDecoder.DecodeSignatureParamerTypes(Signature)); } private IEnumerable<CilCustomAttribute> GetCustomAttributes() { foreach(var handle in _propertyDef.GetCustomAttributes()) { var attribute = _readers.MdReader.GetCustomAttribute(handle); yield return new CilCustomAttribute(attribute, ref _readers); } } private string GetAttributesForSignature() { if (Attributes.HasFlag(PropertyAttributes.SpecialName)) { return "specialname "; } if (Attributes.HasFlag(PropertyAttributes.RTSpecialName)) { return "rtspecialname "; } return string.Empty; } private CilConstant GetDefaultValue() { Constant constant = _readers.MdReader.GetConstant(_propertyDef.GetDefaultValue()); return CilConstant.Create(constant, ref _readers); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml.XPath; using Microsoft.Extensions.Options; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PublishedCache; using Umbraco.Cms.Core.Xml; using Umbraco.Cms.Core.Xml.XPath; using Umbraco.Cms.Infrastructure.PublishedCache.Navigable; using Umbraco.Extensions; namespace Umbraco.Cms.Infrastructure.PublishedCache { public class ContentCache : PublishedCacheBase, IPublishedContentCache, INavigableData, IDisposable { private readonly IDomainCache _domainCache; private readonly IAppCache _elementsCache; private readonly GlobalSettings _globalSettings; private readonly ContentStore.Snapshot _snapshot; private readonly IAppCache _snapshotCache; private readonly IVariationContextAccessor _variationContextAccessor; #region IDisposable public void Dispose() => _snapshot.Dispose(); #endregion #region Constructor // TODO: figure this out // after the current snapshot has been resync-ed // it's too late for UmbracoContext which has captured previewDefault and stuff into these ctor vars // but, no, UmbracoContext returns snapshot.Content which comes from elements SO a resync should create a new cache public ContentCache(bool previewDefault, ContentStore.Snapshot snapshot, IAppCache snapshotCache, IAppCache elementsCache, IDomainCache domainCache, IOptions<GlobalSettings> globalSettings, IVariationContextAccessor variationContextAccessor) : base(previewDefault) { _snapshot = snapshot; _snapshotCache = snapshotCache; _elementsCache = elementsCache; _domainCache = domainCache; _globalSettings = globalSettings.Value; _variationContextAccessor = variationContextAccessor; } private bool HideTopLevelNodeFromPath => _globalSettings.HideTopLevelNodeFromPath; #endregion #region Routes // routes can be // "/" // "123/" // "/path/to/node" // "123/path/to/node" // at the moment we try our best to be backward compatible, but really, // should get rid of hideTopLevelNode and other oddities entirely, eventually public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, string culture = null) => GetByRoute(PreviewDefault, route, hideTopLevelNode, culture); public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, string culture = null) { if (route == null) { throw new ArgumentNullException(nameof(route)); } IAppCache cache = preview == false || PublishedSnapshotService.FullCacheWhenPreviewing ? _elementsCache : _snapshotCache; var key = CacheKeys.ContentCacheContentByRoute(route, preview, culture); return cache.GetCacheItem(key, () => GetByRouteInternal(preview, route, hideTopLevelNode, culture)); } private IPublishedContent GetByRouteInternal(bool preview, string route, bool? hideTopLevelNode, string culture) { hideTopLevelNode = hideTopLevelNode ?? HideTopLevelNodeFromPath; // default = settings // the route always needs to be lower case because we only store the urlName attribute in lower case route = route.ToLowerInvariant(); var pos = route.IndexOf('/'); var path = pos == 0 ? route : route.Substring(pos); var startNodeId = pos == 0 ? 0 : int.Parse(route.Substring(0, pos), CultureInfo.InvariantCulture); var parts = path.Split(Constants.CharArrays.ForwardSlash, StringSplitOptions.RemoveEmptyEntries); IPublishedContent content; if (startNodeId > 0) { // if in a domain then start with the root node of the domain // and follow the path // note: if domain has a path (eg example.com/en) which is not recommended anymore // then /en part of the domain is basically ignored here... content = GetById(preview, startNodeId); content = FollowRoute(content, parts, 0, culture); } else if (parts.Length == 0) { // if not in a domain, and path is empty - what is the default page? // let's say it is the first one in the tree, if any -- order by sortOrder content = GetAtRoot(preview).FirstOrDefault(); } else { // if not in a domain... // hideTopLevelNode = support legacy stuff, look for /*/path/to/node // else normal, look for /path/to/node content = hideTopLevelNode.Value ? GetAtRoot(preview).SelectMany(x => x.Children(_variationContextAccessor, culture)) .FirstOrDefault(x => x.UrlSegment(_variationContextAccessor, culture) == parts[0]) : GetAtRoot(preview) .FirstOrDefault(x => x.UrlSegment(_variationContextAccessor, culture) == parts[0]); content = FollowRoute(content, parts, 1, culture); } // if hideTopLevelNodePath is true then for URL /foo we looked for /*/foo // but maybe that was the URL of a non-default top-level node, so we also // have to look for /foo (see note in ApplyHideTopLevelNodeFromPath). if (content == null && hideTopLevelNode.Value && parts.Length == 1) { content = GetAtRoot(preview) .FirstOrDefault(x => x.UrlSegment(_variationContextAccessor, culture) == parts[0]); } return content; } public string GetRouteById(int contentId, string culture = null) => GetRouteById(PreviewDefault, contentId, culture); public string GetRouteById(bool preview, int contentId, string culture = null) { IAppCache cache = preview == false || PublishedSnapshotService.FullCacheWhenPreviewing ? _elementsCache : _snapshotCache; var key = CacheKeys.ContentCacheRouteByContent(contentId, preview, culture); return cache.GetCacheItem(key, () => GetRouteByIdInternal(preview, contentId, null, culture)); } private string GetRouteByIdInternal(bool preview, int contentId, bool? hideTopLevelNode, string culture) { IPublishedContent node = GetById(preview, contentId); if (node == null) { return null; } hideTopLevelNode = hideTopLevelNode ?? HideTopLevelNodeFromPath; // default = settings // walk up from that node until we hit a node with a domain, // or we reach the content root, collecting URLs in the way var pathParts = new List<string>(); IPublishedContent n = node; var urlSegment = n.UrlSegment(_variationContextAccessor, culture); var hasDomains = _domainCache.GetAssignedWithCulture(culture, n.Id); while (hasDomains == false && n != null) // n is null at root { // no segment indicates this is not published when this is a variant if (urlSegment.IsNullOrWhiteSpace()) { return null; } pathParts.Add(urlSegment); // move to parent node n = n.Parent; if (n != null) { urlSegment = n.UrlSegment(_variationContextAccessor, culture); } hasDomains = n != null && _domainCache.GetAssignedWithCulture(culture, n.Id); } // at this point this will be the urlSegment of the root, no segment indicates this is not published when this is a variant if (urlSegment.IsNullOrWhiteSpace()) { return null; } // no domain, respect HideTopLevelNodeFromPath for legacy purposes if (hasDomains == false && hideTopLevelNode.Value) { ApplyHideTopLevelNodeFromPath(node, pathParts, preview); } // assemble the route pathParts.Reverse(); var path = "/" + string.Join("/", pathParts); // will be "/" or "/foo" or "/foo/bar" etc //prefix the root node id containing the domain if it exists (this is a standard way of creating route paths) //and is done so that we know the ID of the domain node for the path var route = (n?.Id.ToString(CultureInfo.InvariantCulture) ?? "") + path; return route; } private IPublishedContent FollowRoute(IPublishedContent content, IReadOnlyList<string> parts, int start, string culture) { var i = start; while (content != null && i < parts.Count) { var part = parts[i++]; content = content.Children(_variationContextAccessor, culture).FirstOrDefault(x => { var urlSegment = x.UrlSegment(_variationContextAccessor, culture); return urlSegment == part; }); } return content; } private void ApplyHideTopLevelNodeFromPath(IPublishedContent content, IList<string> segments, bool preview) { // in theory if hideTopLevelNodeFromPath is true, then there should be only one // top-level node, or else domains should be assigned. but for backward compatibility // we add this check - we look for the document matching "/" and if it's not us, then // we do not hide the top level path // it has to be taken care of in GetByRoute too so if // "/foo" fails (looking for "/*/foo") we try also "/foo". // this does not make much sense anyway esp. if both "/foo/" and "/bar/foo" exist, but // that's the way it works pre-4.10 and we try to be backward compat for the time being if (content.Parent == null) { IPublishedContent rootNode = GetByRoute(preview, "/", true); if (rootNode == null) { throw new Exception("Failed to get node at /."); } if (rootNode.Id == content.Id) // remove only if we're the default node { segments.RemoveAt(segments.Count - 1); } } else { segments.RemoveAt(segments.Count - 1); } } #endregion #region Get, Has public override IPublishedContent GetById(bool preview, int contentId) { ContentNode node = _snapshot.Get(contentId); return GetNodePublishedContent(node, preview); } public override IPublishedContent GetById(bool preview, Guid contentId) { ContentNode node = _snapshot.Get(contentId); return GetNodePublishedContent(node, preview); } public override IPublishedContent GetById(bool preview, Udi contentId) { var guidUdi = contentId as GuidUdi; if (guidUdi == null) { throw new ArgumentException($"Udi must be of type {typeof(GuidUdi).Name}.", nameof(contentId)); } if (guidUdi.EntityType != Constants.UdiEntityType.Document) { throw new ArgumentException($"Udi entity type must be \"{Constants.UdiEntityType.Document}\".", nameof(contentId)); } return GetById(preview, guidUdi.Guid); } public override bool HasById(bool preview, int contentId) { ContentNode n = _snapshot.Get(contentId); if (n == null) { return false; } return preview || n.PublishedModel != null; } IEnumerable<IPublishedContent> INavigableData.GetAtRoot(bool preview) => GetAtRoot(preview); public override IEnumerable<IPublishedContent> GetAtRoot(bool preview, string culture = null) { // handle context culture for variant if (culture == null) { culture = _variationContextAccessor?.VariationContext?.Culture ?? ""; } // _snapshot.GetAtRoot() returns all ContentNode at root // both .Draft and .Published cannot be null at the same time // root is already sorted by sortOrder, and does not contain nulls // // GetNodePublishedContent may return null if !preview and there is no // published model, so we need to filter these nulls out IEnumerable<IPublishedContent> atRoot = _snapshot.GetAtRoot() .Select(n => GetNodePublishedContent(n, preview)) .WhereNotNull(); // if a culture is specified, we must ensure that it is avail/published if (culture != "*") { atRoot = atRoot.Where(x => x.IsInvariantOrHasCulture(culture)); } return atRoot; } private static IPublishedContent GetNodePublishedContent(ContentNode node, bool preview) { if (node == null) { return null; } // both .Draft and .Published cannot be null at the same time return preview ? node.DraftModel ?? GetPublishedContentAsDraft(node.PublishedModel) : node.PublishedModel; } // gets a published content as a previewing draft, if preview is true // this is for published content when previewing private static IPublishedContent GetPublishedContentAsDraft(IPublishedContent content /*, bool preview*/) { if (content == null /*|| preview == false*/) { return null; //content; } // an object in the cache is either an IPublishedContentOrMedia, // or a model inheriting from PublishedContentExtended - in which // case we need to unwrap to get to the original IPublishedContentOrMedia. var inner = PublishedContent.UnwrapIPublishedContent(content); return inner.AsDraft(); } public override bool HasContent(bool preview) => preview ? _snapshot.IsEmpty == false : _snapshot.GetAtRoot().Any(x => x.PublishedModel != null); #endregion #region XPath public override IPublishedContent GetSingleByXPath(bool preview, string xpath, XPathVariable[] vars) { XPathNavigator navigator = CreateNavigator(preview); XPathNodeIterator iterator = navigator.Select(xpath, vars); return GetSingleByXPath(iterator); } public override IPublishedContent GetSingleByXPath(bool preview, XPathExpression xpath, XPathVariable[] vars) { XPathNavigator navigator = CreateNavigator(preview); XPathNodeIterator iterator = navigator.Select(xpath, vars); return GetSingleByXPath(iterator); } private static IPublishedContent GetSingleByXPath(XPathNodeIterator iterator) { if (iterator.MoveNext() == false) { return null; } var xnav = iterator.Current as NavigableNavigator; var xcontent = xnav?.UnderlyingObject as NavigableContent; return xcontent?.InnerContent; } public override IEnumerable<IPublishedContent> GetByXPath(bool preview, string xpath, XPathVariable[] vars) { XPathNavigator navigator = CreateNavigator(preview); XPathNodeIterator iterator = navigator.Select(xpath, vars); return GetByXPath(iterator); } public override IEnumerable<IPublishedContent> GetByXPath(bool preview, XPathExpression xpath, XPathVariable[] vars) { XPathNavigator navigator = CreateNavigator(preview); XPathNodeIterator iterator = navigator.Select(xpath, vars); return GetByXPath(iterator); } private static IEnumerable<IPublishedContent> GetByXPath(XPathNodeIterator iterator) { iterator = iterator.Clone(); while (iterator.MoveNext()) { var xnav = iterator.Current as NavigableNavigator; var xcontent = xnav?.UnderlyingObject as NavigableContent; if (xcontent == null) { continue; } yield return xcontent.InnerContent; } } public override XPathNavigator CreateNavigator(bool preview) { var source = new Source(this, preview); var navigator = new NavigableNavigator(source); return navigator; } public override XPathNavigator CreateNodeNavigator(int id, bool preview) { var source = new Source(this, preview); var navigator = new NavigableNavigator(source); return navigator.CloneWithNewRoot(id, 0); } #endregion #region Content types public override IPublishedContentType GetContentType(int id) => _snapshot.GetContentType(id); public override IPublishedContentType GetContentType(string alias) => _snapshot.GetContentType(alias); public override IPublishedContentType GetContentType(Guid key) => _snapshot.GetContentType(key); #endregion } }
/**************************************************************************** Tilde Copyright (c) 2008 Tantalus Media Pty 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 Tilde.LuaDebugger { partial class BreakpointsWindow { /// <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() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BreakpointsWindow)); this.breakpointListView = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.columnHeader3 = new System.Windows.Forms.ColumnHeader(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.removeBreakpointToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.gotoSourceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.breakpointImageList = new System.Windows.Forms.ImageList(this.components); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.buttonNewBreakpoint = new System.Windows.Forms.ToolStripButton(); this.buttonDisableBreakpoint = new System.Windows.Forms.ToolStripButton(); this.buttonEnableAllBreakpoints = new System.Windows.Forms.ToolStripButton(); this.buttonRemoveAllBreakpoints = new System.Windows.Forms.ToolStripButton(); this.contextMenuStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // breakpointListView // this.breakpointListView.CheckBoxes = true; this.breakpointListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3}); this.breakpointListView.ContextMenuStrip = this.contextMenuStrip1; this.breakpointListView.Dock = System.Windows.Forms.DockStyle.Fill; this.breakpointListView.FullRowSelect = true; this.breakpointListView.Location = new System.Drawing.Point(0, 25); this.breakpointListView.Name = "breakpointListView"; this.breakpointListView.Size = new System.Drawing.Size(465, 429); this.breakpointListView.SmallImageList = this.breakpointImageList; this.breakpointListView.TabIndex = 0; this.breakpointListView.UseCompatibleStateImageBehavior = false; this.breakpointListView.View = System.Windows.Forms.View.Details; this.breakpointListView.ItemChecked += new System.Windows.Forms.ItemCheckedEventHandler(this.breakpointListView_ItemChecked); this.breakpointListView.DoubleClick += new System.EventHandler(this.breakpointListView_DoubleClick); // // columnHeader1 // this.columnHeader1.Text = "File"; this.columnHeader1.Width = 174; // // columnHeader2 // this.columnHeader2.Text = "Line"; this.columnHeader2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // columnHeader3 // this.columnHeader3.Text = "State"; // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.removeBreakpointToolStripMenuItem, this.toolStripSeparator1, this.gotoSourceToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(139, 54); // // removeBreakpointToolStripMenuItem // this.removeBreakpointToolStripMenuItem.Name = "removeBreakpointToolStripMenuItem"; this.removeBreakpointToolStripMenuItem.Size = new System.Drawing.Size(138, 22); this.removeBreakpointToolStripMenuItem.Text = "Delete"; this.removeBreakpointToolStripMenuItem.Click += new System.EventHandler(this.removeBreakpointToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(135, 6); // // gotoSourceToolStripMenuItem // this.gotoSourceToolStripMenuItem.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.gotoSourceToolStripMenuItem.Name = "gotoSourceToolStripMenuItem"; this.gotoSourceToolStripMenuItem.Size = new System.Drawing.Size(138, 22); this.gotoSourceToolStripMenuItem.Text = "Go To Source"; this.gotoSourceToolStripMenuItem.Click += new System.EventHandler(this.gotoSourceToolStripMenuItem_Click); // // breakpointImageList // this.breakpointImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("breakpointImageList.ImageStream"))); this.breakpointImageList.TransparentColor = System.Drawing.Color.Fuchsia; this.breakpointImageList.Images.SetKeyName(0, "Breakpoint.bmp"); this.breakpointImageList.Images.SetKeyName(1, "EmptyBreakpoint.bmp"); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.buttonNewBreakpoint, this.buttonDisableBreakpoint, this.buttonEnableAllBreakpoints, this.buttonRemoveAllBreakpoints}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(465, 25); this.toolStrip1.TabIndex = 2; this.toolStrip1.Text = "toolStrip1"; // // buttonNewBreakpoint // this.buttonNewBreakpoint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.buttonNewBreakpoint.ImageTransparentColor = System.Drawing.Color.Magenta; this.buttonNewBreakpoint.Name = "buttonNewBreakpoint"; this.buttonNewBreakpoint.Size = new System.Drawing.Size(86, 22); this.buttonNewBreakpoint.Text = "New breakpoint"; // // buttonDisableBreakpoint // this.buttonDisableBreakpoint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.buttonDisableBreakpoint.ImageTransparentColor = System.Drawing.Color.Magenta; this.buttonDisableBreakpoint.Name = "buttonDisableBreakpoint"; this.buttonDisableBreakpoint.Size = new System.Drawing.Size(99, 22); this.buttonDisableBreakpoint.Text = "Disable breakpoint"; // // buttonEnableAllBreakpoints // this.buttonEnableAllBreakpoints.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.buttonEnableAllBreakpoints.ImageTransparentColor = System.Drawing.Color.Magenta; this.buttonEnableAllBreakpoints.Name = "buttonEnableAllBreakpoints"; this.buttonEnableAllBreakpoints.Size = new System.Drawing.Size(115, 22); this.buttonEnableAllBreakpoints.Text = "Enable all breakpoints"; // // buttonRemoveAllBreakpoints // this.buttonRemoveAllBreakpoints.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.buttonRemoveAllBreakpoints.ImageTransparentColor = System.Drawing.Color.Magenta; this.buttonRemoveAllBreakpoints.Name = "buttonRemoveAllBreakpoints"; this.buttonRemoveAllBreakpoints.Size = new System.Drawing.Size(122, 22); this.buttonRemoveAllBreakpoints.Text = "Remove all breakpoints"; // // BreakpointsWindow // this.ClientSize = new System.Drawing.Size(465, 454); this.Controls.Add(this.breakpointListView); this.Controls.Add(this.toolStrip1); this.DockAreas = ((WeifenLuo.WinFormsUI.Docking.DockAreas)(((((WeifenLuo.WinFormsUI.Docking.DockAreas.Float | WeifenLuo.WinFormsUI.Docking.DockAreas.DockLeft) | WeifenLuo.WinFormsUI.Docking.DockAreas.DockRight) | WeifenLuo.WinFormsUI.Docking.DockAreas.DockTop) | WeifenLuo.WinFormsUI.Docking.DockAreas.DockBottom))); this.Name = "BreakpointsWindow"; this.TabText = "Breakpoints"; this.contextMenuStrip1.ResumeLayout(false); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ListView breakpointListView; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ImageList breakpointImageList; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton buttonNewBreakpoint; private System.Windows.Forms.ToolStripButton buttonDisableBreakpoint; private System.Windows.Forms.ToolStripButton buttonEnableAllBreakpoints; private System.Windows.Forms.ToolStripButton buttonRemoveAllBreakpoints; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem gotoSourceToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem removeBreakpointToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ColumnHeader columnHeader3; } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DynamoDBv2.Model { /// <summary> /// Container for the parameters to the GetItem operation. /// <para>The <i>GetItem</i> operation returns a set of attributes for the item with the given primary key. If there is no matching item, /// <i>GetItem</i> does not return any data.</para> <para> <i>GetItem</i> provides an eventually consistent read by default. If your application /// requires a strongly consistent read, set <i>ConsistentRead</i> to <c>true</c> . Although a strongly consistent read might take more time /// than an eventually consistent read, it always returns the last updated value.</para> /// </summary> /// <seealso cref="Amazon.DynamoDBv2.AmazonDynamoDB.GetItem"/> public class GetItemRequest : AmazonWebServiceRequest { private string tableName; private Dictionary<string,AttributeValue> key = new Dictionary<string,AttributeValue>(); private List<string> attributesToGet = new List<string>(); private bool? consistentRead; private string returnConsumedCapacity; /// <summary> /// The name of the table containing the requested item. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>3 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[a-zA-Z0-9_.-]+</description> /// </item> /// </list> /// </para> /// </summary> public string TableName { get { return this.tableName; } set { this.tableName = value; } } /// <summary> /// Sets the TableName property /// </summary> /// <param name="tableName">The value to set for the TableName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public GetItemRequest WithTableName(string tableName) { this.tableName = tableName; return this; } // Check to see if TableName property is set internal bool IsSetTableName() { return this.tableName != null; } /// <summary> /// A map of attribute names to <i>AttributeValue</i> objects, representing the primary key of the item to retrieve. /// /// </summary> public Dictionary<string,AttributeValue> Key { get { return this.key; } set { this.key = value; } } /// <summary> /// Adds the KeyValuePairs to the Key dictionary. /// </summary> /// <param name="pairs">The pairs to be added to the Key dictionary.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public GetItemRequest WithKey(params KeyValuePair<string, AttributeValue>[] pairs) { foreach (KeyValuePair<string, AttributeValue> pair in pairs) { this.Key[pair.Key] = pair.Value; } return this; } // Check to see if Key property is set internal bool IsSetKey() { return this.key != null; } /// <summary> /// The names of one or more attributes to retrieve. If no attribute names are specified, then all attributes will be returned. If any of the /// requested attributes are not found, they will not appear in the result. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - </description> /// </item> /// </list> /// </para> /// </summary> public List<string> AttributesToGet { get { return this.attributesToGet; } set { this.attributesToGet = value; } } /// <summary> /// Adds elements to the AttributesToGet collection /// </summary> /// <param name="attributesToGet">The values to add to the AttributesToGet collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public GetItemRequest WithAttributesToGet(params string[] attributesToGet) { foreach (string element in attributesToGet) { this.attributesToGet.Add(element); } return this; } /// <summary> /// Adds elements to the AttributesToGet collection /// </summary> /// <param name="attributesToGet">The values to add to the AttributesToGet collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public GetItemRequest WithAttributesToGet(IEnumerable<string> attributesToGet) { foreach (string element in attributesToGet) { this.attributesToGet.Add(element); } return this; } // Check to see if AttributesToGet property is set internal bool IsSetAttributesToGet() { return this.attributesToGet.Count > 0; } /// <summary> /// If set to <c>true</c>, then the operation uses strongly consistent reads; otherwise, eventually consistent reads are used. /// /// </summary> public bool ConsistentRead { get { return this.consistentRead ?? default(bool); } set { this.consistentRead = value; } } /// <summary> /// Sets the ConsistentRead property /// </summary> /// <param name="consistentRead">The value to set for the ConsistentRead property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public GetItemRequest WithConsistentRead(bool consistentRead) { this.consistentRead = consistentRead; return this; } // Check to see if ConsistentRead property is set internal bool IsSetConsistentRead() { return this.consistentRead.HasValue; } /// <summary> /// If set to <c>TOTAL</c>, <i>ConsumedCapacity</i> is included in the response; if set to <c>NONE</c> (the default), <i>ConsumedCapacity</i> is /// not included. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>TOTAL, NONE</description> /// </item> /// </list> /// </para> /// </summary> public string ReturnConsumedCapacity { get { return this.returnConsumedCapacity; } set { this.returnConsumedCapacity = value; } } /// <summary> /// Sets the ReturnConsumedCapacity property /// </summary> /// <param name="returnConsumedCapacity">The value to set for the ReturnConsumedCapacity property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public GetItemRequest WithReturnConsumedCapacity(string returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity; return this; } // Check to see if ReturnConsumedCapacity property is set internal bool IsSetReturnConsumedCapacity() { return this.returnConsumedCapacity != null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Input; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Serialization; namespace Microsoft.MixedReality.Toolkit.Utilities.Solvers { /// <summary> /// This class handles the solver components that are attached to this <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> /// </summary> [HelpURL("https://microsoft.github.io/MixedRealityToolkit-Unity/Documentation/README_Solver.html")] [AddComponentMenu("Scripts/MRTK/SDK/SolverHandler")] public class SolverHandler : MonoBehaviour { [SerializeField] [Tooltip("Tracked object to calculate position and orientation from. If you want to manually override and use a scene object, use the TransformTarget field.")] [FormerlySerializedAs("trackedObjectToReference")] private TrackedObjectType trackedTargetType = TrackedObjectType.Head; /// <summary> /// Tracked object to calculate position and orientation from. If you want to manually override and use a scene object, use the TransformTarget field. /// </summary> public TrackedObjectType TrackedTargetType { get => trackedTargetType; set { if (trackedTargetType != value && IsValidTrackedObjectType(value)) { trackedTargetType = value; RefreshTrackedObject(); } } } [SerializeField] [Tooltip("If tracking hands or motion controllers, determines which hand(s) are valid attachments")] private Handedness trackedHandness = Handedness.Both; /// <summary> /// If tracking hands or motion controllers, determines which hand(s) are valid attachments. /// </summary> /// <remarks> /// Only None, Left, Right, and Both are valid values /// </remarks> public Handedness TrackedHandness { get => trackedHandness; set { if (trackedHandness != value && IsValidHandedness(value)) { trackedHandness = value; RefreshTrackedObject(); } } } [SerializeField] [Tooltip("When TrackedTargetType is set to hands, use this specific joint to calculate position and orientation")] private TrackedHandJoint trackedHandJoint = TrackedHandJoint.Palm; /// <summary> /// When TrackedTargetType is set to hands, use this specific joint to calculate position and orientation /// </summary> public TrackedHandJoint TrackedHandJoint { get => trackedHandJoint; set { if (trackedHandJoint != value) { trackedHandJoint = value; RefreshTrackedObject(); } } } [SerializeField] [Tooltip("Manual override for when TrackedTargetType is set to CustomOverride")] private Transform transformOverride; /// <summary> /// Manual override for when TrackedTargetType is set to CustomOverride /// </summary> public Transform TransformOverride { set { if (value != null && transformOverride != value) { transformOverride = value; RefreshTrackedObject(); } } } [SerializeField] [Tooltip("Add an additional offset of the tracked object to base the solver on. Useful for tracking something like a halo position above your head or off the side of a controller.")] private Vector3 additionalOffset; /// <summary> /// Add an additional offset of the tracked object to base the solver on. Useful for tracking something like a halo position above your head or off the side of a controller. /// </summary> public Vector3 AdditionalOffset { get => additionalOffset; set { if (additionalOffset != value) { additionalOffset = value; RefreshTrackedObject(); } } } [SerializeField] [Tooltip("Add an additional rotation on top of the tracked object. Useful for tracking what is essentially the up or right/left vectors.")] private Vector3 additionalRotation; /// <summary> /// Add an additional rotation on top of the tracked object. Useful for tracking what is essentially the up or right/left vectors. /// </summary> public Vector3 AdditionalRotation { get => additionalRotation; set { if (additionalRotation != value) { additionalRotation = value; RefreshTrackedObject(); } } } [SerializeField] [Tooltip("Whether or not this SolverHandler calls SolverUpdate() every frame. Only one SolverHandler should manage SolverUpdate(). This setting does not affect whether the Target Transform of this SolverHandler gets updated or not.")] private bool updateSolvers = true; /// <summary> /// Whether or not this SolverHandler calls SolverUpdate() every frame. Only one SolverHandler should manage SolverUpdate(). This setting does not affect whether the Target Transform of this SolverHandler gets updated or not. /// </summary> public bool UpdateSolvers { get => updateSolvers; set => updateSolvers = value; } protected readonly List<Solver> solvers = new List<Solver>(); private bool updateSolversList = false; /// <summary> /// List of solvers that this handler will manage and update /// </summary> public IReadOnlyCollection<Solver> Solvers { get => solvers.AsReadOnly(); set { if (value != null) { solvers.Clear(); solvers.AddRange(value); } } } /// <summary> /// The position the solver is trying to move to. /// </summary> public Vector3 GoalPosition { get; set; } /// <summary> /// The rotation the solver is trying to rotate to. /// </summary> public Quaternion GoalRotation { get; set; } /// <summary> /// The scale the solver is trying to scale to. /// </summary> public Vector3 GoalScale { get; set; } /// <summary> /// Alternate scale. /// </summary> public Vector3Smoothed AltScale { get; set; } /// <summary> /// The timestamp the solvers will use to calculate with. /// </summary> public float DeltaTime { get; set; } /// <summary> /// The target transform that the solvers will act upon. /// </summary> public Transform TransformTarget { get { if (IsInvalidTracking()) { RefreshTrackedObject(); } return trackingTarget != null ? trackingTarget.transform : null; } } // Stores currently attached hand if valid (only possible values Left, Right, or None) protected Handedness currentTrackedHandedness = Handedness.None; /// <summary> /// Currently tracked hand or motion controller if applicable /// </summary> /// /// <remarks> /// Only possible values Left, Right, or None /// </remarks> public Handedness CurrentTrackedHandedness => currentTrackedHandedness; // Stores controller side to favor if TrackedHandedness is set to both protected Handedness preferredTrackedHandedness = Handedness.Left; /// <summary> /// Controller side to favor and pick first if TrackedHandedness is set to both /// </summary> /// /// <remarks> /// Only possible values, Left or Right /// </remarks> public Handedness PreferredTrackedHandedness { get => preferredTrackedHandedness; set { if ((value.IsLeft() || value.IsRight()) && preferredTrackedHandedness != value) { preferredTrackedHandedness = value; } } } // Hidden GameObject managed by this component and attached as a child to the tracked target type (i.e head, hand etc) private GameObject trackingTarget; private LinePointer controllerRay; private float lastUpdateTime; private IMixedRealityHandJointService HandJointService => handJointService ?? CoreServices.GetInputSystemDataProvider<IMixedRealityHandJointService>(); private IMixedRealityHandJointService handJointService = null; #region MonoBehaviour Implementation private void Awake() { GoalScale = Vector3.one; AltScale = new Vector3Smoothed(Vector3.one, 0.1f); DeltaTime = Time.deltaTime; lastUpdateTime = Time.realtimeSinceStartup; if (!IsValidHandedness(trackedHandness)) { Debug.LogError("Using invalid SolverHandler.TrackedHandness value. Defaulting to Handedness.Both"); TrackedHandness = Handedness.Both; } if (!IsValidTrackedObjectType(trackedTargetType)) { Debug.LogError("Using Obsolete SolverHandler.TrackedTargetType. Defaulting to type Head"); TrackedTargetType = TrackedObjectType.Head; } } protected virtual void Start() { RefreshTrackedObject(); } protected virtual void Update() { if (IsInvalidTracking()) { RefreshTrackedObject(); } DeltaTime = Time.realtimeSinceStartup - lastUpdateTime; lastUpdateTime = Time.realtimeSinceStartup; } private void LateUpdate() { if (updateSolversList) { IEnumerable<Solver> inspectorOrderedSolvers = GetComponents<Solver>().Intersect(solvers); Solvers = inspectorOrderedSolvers.Union(Solvers).ToReadOnlyCollection(); updateSolversList = false; } if (UpdateSolvers) { // Before calling solvers, update goal to be the transform so that working and transform will match GoalPosition = transform.position; GoalRotation = transform.rotation; GoalScale = transform.localScale; for (int i = 0; i < solvers.Count; ++i) { Solver solver = solvers[i]; if (solver != null && solver.enabled) { solver.SolverUpdateEntry(); } } } } protected void OnDestroy() { DetachFromCurrentTrackedObject(); } #endregion MonoBehaviour Implementation /// <summary> /// Clears the transform target and attaches to the current <see cref="TrackedTargetType"/>. /// </summary> public void RefreshTrackedObject() { DetachFromCurrentTrackedObject(); AttachToNewTrackedObject(); } /// <summary> /// Adds <paramref name="solver"/> to the list of <see cref="Solvers"/> guaranteeing inspector ordering. /// </summary> public void RegisterSolver(Solver solver) { if (!solvers.Contains(solver)) { solvers.Add(solver); updateSolversList = true; } } /// <summary> /// Removes <paramref name="solver"/> from the list of <see cref="Solvers"/>. /// </summary> public void UnregisterSolver(Solver solver) { solvers.Remove(solver); } protected virtual void DetachFromCurrentTrackedObject() { if (trackingTarget != null) { Destroy(trackingTarget); trackingTarget = null; } } protected virtual void AttachToNewTrackedObject() { currentTrackedHandedness = Handedness.None; controllerRay = null; Transform target = null; if (TrackedTargetType == TrackedObjectType.Head) { target = CameraCache.Main.transform; } else if (TrackedTargetType == TrackedObjectType.ControllerRay) { if (TrackedHandness == Handedness.Both) { currentTrackedHandedness = PreferredTrackedHandedness; controllerRay = PointerUtils.GetPointer<LinePointer>(currentTrackedHandedness); if (controllerRay == null) { // If no pointer found, try again on the opposite hand currentTrackedHandedness = currentTrackedHandedness.GetOppositeHandedness(); controllerRay = PointerUtils.GetPointer<LinePointer>(currentTrackedHandedness); } } else { currentTrackedHandedness = TrackedHandness; controllerRay = PointerUtils.GetPointer<LinePointer>(currentTrackedHandedness); } if (controllerRay != null) { target = controllerRay.transform; } else { currentTrackedHandedness = Handedness.None; } } else if (TrackedTargetType == TrackedObjectType.HandJoint) { if (HandJointService != null) { currentTrackedHandedness = TrackedHandness; if (currentTrackedHandedness == Handedness.Both) { if (HandJointService.IsHandTracked(PreferredTrackedHandedness)) { currentTrackedHandedness = PreferredTrackedHandedness; } else if (HandJointService.IsHandTracked(PreferredTrackedHandedness.GetOppositeHandedness())) { currentTrackedHandedness = PreferredTrackedHandedness.GetOppositeHandedness(); } else { currentTrackedHandedness = Handedness.None; } } target = HandJointService.RequestJointTransform(this.TrackedHandJoint, currentTrackedHandedness); } } else if (TrackedTargetType == TrackedObjectType.CustomOverride) { target = this.transformOverride; } TrackTransform(target); } private void TrackTransform(Transform target) { if (trackingTarget != null || target == null) return; string name = string.Format("SolverHandler Target on {0} with offset {1}, {2}", target.gameObject.name, AdditionalOffset, AdditionalRotation); trackingTarget = new GameObject(name); trackingTarget.hideFlags = HideFlags.HideInHierarchy; trackingTarget.transform.parent = target; trackingTarget.transform.localPosition = Vector3.Scale(AdditionalOffset, trackingTarget.transform.localScale); trackingTarget.transform.localRotation = Quaternion.Euler(AdditionalRotation); } private LinePointer GetControllerRay(Handedness handedness) { return PointerUtils.GetPointer<LinePointer>(handedness); } /// <summary> /// Returns true if the solver handler's transform target is not valid /// </summary> /// <returns>true if not tracking valid hands and/or target, false otherwise</returns> private bool IsInvalidTracking() { if (trackingTarget == null) { return true; } // If we are attached to a pointer (i.e controller ray), // check if pointer's controller is still be tracked if (TrackedTargetType == TrackedObjectType.ControllerRay && (controllerRay == null || !controllerRay.IsTracked)) { return true; } // If we were tracking a particular hand, check that our transform is still valid // The HandJointService does not destroy it's own hand joint tracked GameObjects even when a hand is no longer tracked // Those HandJointService's GameObjects though are the parents of our tracked transform and thus will not be null/destroyed if (TrackedTargetType == TrackedObjectType.HandJoint && !currentTrackedHandedness.IsNone()) { bool trackingLeft = HandJointService.IsHandTracked(Handedness.Left); bool trackingRight = HandJointService.IsHandTracked(Handedness.Right); return (currentTrackedHandedness.IsLeft() && !trackingLeft) || (currentTrackedHandedness.IsRight() && !trackingRight); } return false; } public static bool IsValidHandedness(Handedness hand) { return hand <= Handedness.Both; } public static bool IsValidTrackedObjectType(TrackedObjectType type) { return type == TrackedObjectType.Head || type >= TrackedObjectType.ControllerRay; } #region Obsolete /// <summary> /// Tracked object to calculate position and orientation from. If you want to manually override and use a scene object, use the TransformTarget field. /// </summary> [Obsolete("Use TrackedTargetType instead")] public TrackedObjectType TrackedObjectToReference { get => trackedTargetType; set { if (trackedTargetType != value) { trackedTargetType = value; RefreshTrackedObject(); } } } #endregion } }
using System; using MonoTouch.Foundation; using System.Drawing; using MonoTouch.UIKit; using System.Linq; using etcdMobile.iPhone.Common; using System.Collections.Generic; using etcetera; namespace etcdMobile.iPhone.Keys { public class KeySource : UITableViewSource { private Node _parent; private Preferences _prefs; private Server _server; private IReloadableTableView _tbl; private List<Node> _keys; private UINavigationController _nav; public EventHandler ItemDeleted; public KeySource(UINavigationController nav, Server server, Node parent, IReloadableTableView tbl) { _tbl = tbl; _nav = nav; _server = server; _parent = parent; _tbl.Source = this; _prefs = Globals.Preferences; Refresh(); } public virtual void Refresh() { Refresh (SortType.NameAsc); // pull from SQL Cache } public virtual void Refresh(SortType sortType) // TODO: include parent { if (_parent != null) { _keys = _server.Client.Get (_parent.Key).Node.Nodes; } else { // MARK: CRASH HERE! OVERLOAD ALL GET METHODS // TODO: COULD NOT CONNECT try { var keys = _server.Client.Get(string.Empty); if(keys != null && keys.Node != null && keys.Node.Nodes != null) { _keys = keys.Node.Nodes; } } catch(Exception ex) { Console.WriteLine ("Exception getting keys {0}", ex.Message); } } if (_keys == null || !_keys.Any ()) { _keys = new List<Node> (); } if (_prefs.HideEtcdDir) { _keys.RemoveAll(k => k.Dir && k.KeyName() == "_etcd"); } // MARK: TODO: NULL? switch (sortType) { case SortType.NameAsc: _keys = _keys.OrderBy (k => k.Key).ToList (); break; case SortType.NameDesc: _keys = _keys.OrderByDescending (k => k.Key).ToList (); break; case SortType.TtlAsc: _keys = _keys.OrderBy (k => k.Ttl.HasValue ? k.Ttl.Value : 0).ToList (); break; case SortType.TtlDesc: _keys = _keys.OrderByDescending (k => k.Ttl.HasValue ? k.Ttl.Value : 0).ToList (); break; } _tbl.ReloadData(); } public void Refresh(object sender, EventArgs e) { Refresh (); } public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) { return true; } public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) { if (_prefs.ReadOnly == false && editingStyle == UITableViewCellEditingStyle.Delete) { var key = _keys[indexPath.Row]; var confirm = new UIAlertView ("Delete", StringValues.DeleteKeyMessage, null, "Delete", "Cancel"); confirm.Show (); confirm.Clicked += (sender, e) => { if(e.ButtonIndex == 0) { UIHelper.Try(() => _server.Client.Delete (key.Key)); Refresh(); if (ItemDeleted != null) { ItemDeleted (this, null); } } }; } } public override void WillBeginEditing (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.CellAt(indexPath) as UITableViewCell; if(cell != null) { } } public override void DidEndEditing (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.CellAt(indexPath) as UITableViewCell; if(cell != null) { } } public List<Node> Keys { get { return _keys; } } public int Count { get { return _keys == null ? 0 :_keys.Count;} } public override int RowsInSection (UITableView tableview, int section) { return _keys == null ? 0 : _keys.Count; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { var cell = _keys[indexPath.Row] as Node; if (cell.Dir) { var keyList = new KeyList (_server, cell); _nav.PushViewController (keyList, true); } else { var keyAdd = new KeyAdd (_server, cell); keyAdd.OnSave += Refresh; keyAdd.OnDelete += Refresh; _nav.PushViewController (keyAdd, true); } } public override int NumberOfSections (UITableView tableView) { return 1; } private readonly string _cellName = "KeyValueListCell"; public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { Node cell = _keys[indexPath.Row]; var tblCell = tableView.DequeueReusableCell(_cellName) as KeyListCell; if (tblCell == null) { tblCell = KeyListCell.Create (_nav, cell); } if (cell.Dir) { tblCell.Accessory = UITableViewCellAccessory.DisclosureIndicator; } else { tblCell.Accessory = UITableViewCellAccessory.None; } return tblCell; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Utilities; using System; using System.Globalization; using System.Linq; namespace Avalonia { /// <summary> /// Defines a point. /// </summary> public struct Point { /// <summary> /// The X position. /// </summary> private readonly double _x; /// <summary> /// The Y position. /// </summary> private readonly double _y; /// <summary> /// Initializes a new instance of the <see cref="Point"/> structure. /// </summary> /// <param name="x">The X position.</param> /// <param name="y">The Y position.</param> public Point(double x, double y) { _x = x; _y = y; } /// <summary> /// Gets the X position. /// </summary> public double X => _x; /// <summary> /// Gets the Y position. /// </summary> public double Y => _y; /// <summary> /// Converts the <see cref="Point"/> to a <see cref="Vector"/>. /// </summary> /// <param name="p">The point.</param> public static implicit operator Vector(Point p) { return new Vector(p._x, p._y); } /// <summary> /// Negates a point. /// </summary> /// <param name="a">The point.</param> /// <returns>The negated point.</returns> public static Point operator -(Point a) { return new Point(-a._x, -a._y); } /// <summary> /// Checks for equality between two <see cref="Point"/>s. /// </summary> /// <param name="left">The first point.</param> /// <param name="right">The second point.</param> /// <returns>True if the points are equal; otherwise false.</returns> public static bool operator ==(Point left, Point right) { return left.X == right.X && left.Y == right.Y; } /// <summary> /// Checks for unequality between two <see cref="Point"/>s. /// </summary> /// <param name="left">The first point.</param> /// <param name="right">The second point.</param> /// <returns>True if the points are unequal; otherwise false.</returns> public static bool operator !=(Point left, Point right) { return !(left == right); } /// <summary> /// Adds two points. /// </summary> /// <param name="a">The first point.</param> /// <param name="b">The second point.</param> /// <returns>A point that is the result of the addition.</returns> public static Point operator +(Point a, Point b) { return new Point(a._x + b._x, a._y + b._y); } /// <summary> /// Adds a vector to a point. /// </summary> /// <param name="a">The point.</param> /// <param name="b">The vector.</param> /// <returns>A point that is the result of the addition.</returns> public static Point operator +(Point a, Vector b) { return new Point(a._x + b.X, a._y + b.Y); } /// <summary> /// Subtracts two points. /// </summary> /// <param name="a">The first point.</param> /// <param name="b">The second point.</param> /// <returns>A point that is the result of the subtraction.</returns> public static Point operator -(Point a, Point b) { return new Point(a._x - b._x, a._y - b._y); } /// <summary> /// Subtracts a vector from a point. /// </summary> /// <param name="a">The point.</param> /// <param name="b">The vector.</param> /// <returns>A point that is the result of the subtraction.</returns> public static Point operator -(Point a, Vector b) { return new Point(a._x - b.X, a._y - b.Y); } /// <summary> /// Multiplies a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to multiply</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates multiplied</returns> public static Point operator *(Point p, double k) => new Point(p.X*k, p.Y*k); /// <summary> /// Multiplies a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to multiply</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates multiplied</returns> public static Point operator *(double k, Point p) => new Point(p.X*k, p.Y*k); /// <summary> /// Divides a point by a factor coordinate-wise /// </summary> /// <param name="p">Point to divide by</param> /// <param name="k">Factor</param> /// <returns>Points having its coordinates divided</returns> public static Point operator /(Point p, double k) => new Point(p.X/k, p.Y/k); /// <summary> /// Applies a matrix to a point. /// </summary> /// <param name="point">The point.</param> /// <param name="matrix">The matrix.</param> /// <returns>The resulting point.</returns> public static Point operator *(Point point, Matrix matrix) { return new Point( (point.X * matrix.M11) + (point.Y * matrix.M21) + matrix.M31, (point.X * matrix.M12) + (point.Y * matrix.M22) + matrix.M32); } /// <summary> /// Parses a <see cref="Point"/> string. /// </summary> /// <param name="s">The string.</param> /// <returns>The <see cref="Thickness"/>.</returns> public static Point Parse(string s) { using (var tokenizer = new StringTokenizer(s, CultureInfo.InvariantCulture, exceptionMessage: "Invalid Point")) { return new Point( tokenizer.ReadDouble(), tokenizer.ReadDouble() ); } } /// <summary> /// Checks for equality between a point and an object. /// </summary> /// <param name="obj">The object.</param> /// <returns> /// True if <paramref name="obj"/> is a point that equals the current point. /// </returns> public override bool Equals(object obj) { if (obj is Point) { var other = (Point)obj; return X == other.X && Y == other.Y; } return false; } /// <summary> /// Returns a hash code for a <see cref="Point"/>. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { unchecked { int hash = 17; hash = (hash * 23) + _x.GetHashCode(); hash = (hash * 23) + _y.GetHashCode(); return hash; } } /// <summary> /// Returns the string representation of the point. /// </summary> /// <returns>The string representation of the point.</returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0}, {1}", _x, _y); } /// <summary> /// Transforms the point by a matrix. /// </summary> /// <param name="transform">The transform.</param> /// <returns>The transformed point.</returns> public Point Transform(Matrix transform) { var x = X; var y = Y; var xadd = y * transform.M21 + transform.M31; var yadd = x * transform.M12 + transform.M32; x *= transform.M11; x += xadd; y *= transform.M22; y += yadd; return new Point(x, y); } /// <summary> /// Returns a new point with the specified X coordinate. /// </summary> /// <param name="x">The X coordinate.</param> /// <returns>The new point.</returns> public Point WithX(double x) { return new Point(x, _y); } /// <summary> /// Returns a new point with the specified Y coordinate. /// </summary> /// <param name="y">The Y coordinate.</param> /// <returns>The new point.</returns> public Point WithY(double y) { return new Point(_x, y); } } }
#region File Description //----------------------------------------------------------------------------- // GraphicsDeviceControl.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Drawing; using System.Windows.Forms; using Microsoft.Xna.Framework.Graphics; #endregion namespace ModEditor { // System.Drawing and the XNA Framework both define Color and Rectangle // types. To avoid conflicts, we specify exactly which ones to use. using Color = System.Drawing.Color; using Rectangle = Microsoft.Xna.Framework.Rectangle; using System.ComponentModel.Design; /// <summary> /// Custom control uses the XNA Framework GraphicsDevice to render onto /// a Windows Form. Derived classes can override the Initialize and Draw /// methods to add their own drawing code. /// </summary> public class GraphicsDeviceControl : Control { #region Fields // However many GraphicsDeviceControl instances you have, they all share // the same underlying GraphicsDevice, managed by this helper service. GraphicsDeviceService graphicsDeviceService; #endregion #region Properties /// <summary> /// Gets a GraphicsDevice that can be used to draw onto this control. /// </summary> public GraphicsDevice GraphicsDevice { get { return graphicsDeviceService.GraphicsDevice; } } /// <summary> /// Gets an IServiceProvider containing our IGraphicsDeviceService. /// This can be used with components such as the ContentManager, /// which use this service to look up the GraphicsDevice. /// </summary> public ServiceContainer Services { get { return services; } } ServiceContainer services = new ServiceContainer(); #endregion #region Initialization /// <summary> /// Initializes the control. /// </summary> protected override void OnCreateControl() { // Don't initialize the graphics device if we are running in the designer. if (!DesignMode) { graphicsDeviceService = GraphicsDeviceService.AddRef(Handle, ClientSize.Width, ClientSize.Height); // Register the service, so components like ContentManager can find it. //services.AddService<IGraphicsDeviceService>(graphicsDeviceService); services.AddService(typeof(GraphicsDeviceService), graphicsDeviceService); // Give derived classes a chance to initialize themselves. Initialize(); } base.OnCreateControl(); } /// <summary> /// Disposes the control. /// </summary> protected override void Dispose(bool disposing) { if (graphicsDeviceService != null) { graphicsDeviceService.Release(disposing); graphicsDeviceService = null; } base.Dispose(disposing); } #endregion #region Paint /// <summary> /// Redraws the control in response to a WinForms paint message. /// </summary> protected override void OnPaint(PaintEventArgs e) { string beginDrawError = BeginDraw(); if (string.IsNullOrEmpty(beginDrawError)) { // Draw the control using the GraphicsDevice. Draw(); EndDraw(); } else { // If BeginDraw failed, show an error message using System.Drawing. PaintUsingSystemDrawing(e.Graphics, beginDrawError); } } /// <summary> /// Attempts to begin drawing the control. Returns an error message string /// if this was not possible, which can happen if the graphics device is /// lost, or if we are running inside the Form designer. /// </summary> string BeginDraw() { // If we have no graphics device, we must be running in the designer. if (graphicsDeviceService == null) { return Text + "\n\n" + GetType(); } // Make sure the graphics device is big enough, and is not lost. string deviceResetError = HandleDeviceReset(); if (!string.IsNullOrEmpty(deviceResetError)) { return deviceResetError; } // Many GraphicsDeviceControl instances can be sharing the same // GraphicsDevice. The device backbuffer will be resized to fit the // largest of these controls. But what if we are currently drawing // a smaller control? To avoid unwanted stretching, we set the // viewport to only use the top left portion of the full backbuffer. Viewport viewport = new Viewport(); viewport.X = 0; viewport.Y = 0; viewport.Width = ClientSize.Width; viewport.Height = ClientSize.Height; viewport.MinDepth = 0; viewport.MaxDepth = 1; GraphicsDevice.Viewport = viewport; return null; } /// <summary> /// Ends drawing the control. This is called after derived classes /// have finished their Draw method, and is responsible for presenting /// the finished image onto the screen, using the appropriate WinForms /// control handle to make sure it shows up in the right place. /// </summary> void EndDraw() { try { Rectangle sourceRectangle = new Rectangle(0, 0, ClientSize.Width, ClientSize.Height); GraphicsDevice.Present(sourceRectangle, null, this.Handle); } catch { // Present might throw if the device became lost while we were // drawing. The lost device will be handled by the next BeginDraw, // so we just swallow the exception. } } /// <summary> /// Helper used by BeginDraw. This checks the graphics device status, /// making sure it is big enough for drawing the current control, and /// that the device is not lost. Returns an error string if the device /// could not be reset. /// </summary> string HandleDeviceReset() { bool deviceNeedsReset = false; switch (GraphicsDevice.GraphicsDeviceStatus) { case GraphicsDeviceStatus.Lost: // If the graphics device is lost, we cannot use it at all. return "Graphics device lost"; case GraphicsDeviceStatus.NotReset: // If device is in the not-reset state, we should try to reset it. deviceNeedsReset = true; break; default: // If the device state is ok, check whether it is big enough. PresentationParameters pp = GraphicsDevice.PresentationParameters; deviceNeedsReset = (ClientSize.Width > pp.BackBufferWidth) || (ClientSize.Height > pp.BackBufferHeight); break; } // Do we need to reset the device? if (deviceNeedsReset) { try { graphicsDeviceService.ResetDevice(ClientSize.Width, ClientSize.Height); } catch (Exception e) { return "Graphics device reset failed\n\n" + e; } } return null; } /// <summary> /// If we do not have a valid graphics device (for instance if the device /// is lost, or if we are running inside the Form designer), we must use /// regular System.Drawing method to display a status message. /// </summary> protected virtual void PaintUsingSystemDrawing(Graphics graphics, string text) { graphics.Clear(Color.CornflowerBlue); using (Brush brush = new SolidBrush(Color.Black)) { using (StringFormat format = new StringFormat()) { format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; graphics.DrawString(text, Font, brush, ClientRectangle, format); } } } /// <summary> /// Ignores WinForms paint-background messages. The default implementation /// would clear the control to the current background color, causing /// flickering when our OnPaint implementation then immediately draws some /// other color over the top using the XNA Framework GraphicsDevice. /// </summary> protected override void OnPaintBackground(PaintEventArgs pevent) { } #endregion #region Abstract Methods /// <summary> /// Derived classes override this to initialize their drawing code. /// </summary> protected virtual void Initialize() { } /// <summary> /// Derived classes override this to draw themselves using the GraphicsDevice. /// </summary> protected virtual void Draw() { } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Collections.Generic { /// <summary> /// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>. /// </summary> internal enum InsertionBehavior : byte { /// <summary> /// The default insertion behavior. /// </summary> None = 0, /// <summary> /// Specifies that an existing entry with the same key should be overwritten if encountered. /// </summary> OverwriteExisting = 1, /// <summary> /// Specifies that if an existing entry with the same key is encountered, an exception should be thrown. /// </summary> ThrowOnExisting = 2 } [DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback { private struct Entry { public int hashCode; // Lower 31 bits of hash code, -1 if unused public int next; // Index of next entry, -1 if last public TKey key; // Key of entry public TValue value; // Value of entry } private int[] _buckets; private Entry[] _entries; private int _count; private int _freeList; private int _freeCount; private int _version; private IEqualityComparer<TKey> _comparer; private KeyCollection _keys; private ValueCollection _values; private object _syncRoot; // constants for serialization private const string VersionName = "Version"; // Do not rename (binary serialization) private const string HashSizeName = "HashSize"; // Do not rename (binary serialization). Must save buckets.Length private const string KeyValuePairsName = "KeyValuePairs"; // Do not rename (binary serialization) private const string ComparerName = "Comparer"; // Do not rename (binary serialization) public Dictionary() : this(0, null) { } public Dictionary(int capacity) : this(capacity, null) { } public Dictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { } public Dictionary(int capacity, IEqualityComparer<TKey> comparer) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); if (capacity > 0) Initialize(capacity); _comparer = comparer ?? EqualityComparer<TKey>.Default; if (_comparer == EqualityComparer<string>.Default) { _comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default; } } public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : this(dictionary != null ? dictionary.Count : 0, comparer) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } // It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case, // avoid the enumerator allocation and overhead by looping through the entries array directly. // We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain // back-compat with subclasses that may have overridden the enumerator behavior. if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>)) { Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary; int count = d._count; Entry[] entries = d._entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { Add(entries[i].key, entries[i].value); } } return; } foreach (KeyValuePair<TKey, TValue> pair in dictionary) { Add(pair.Key, pair.Value); } } public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, null) { } public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer) : this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer) { if (collection == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } foreach (KeyValuePair<TKey, TValue> pair in collection) { Add(pair.Key, pair.Value); } } protected Dictionary(SerializationInfo info, StreamingContext context) { // We can't do anything with the keys and values until the entire graph has been deserialized // and we have a resonable estimate that GetHashCode is not going to fail. For the time being, // we'll just cache this. The graph is not valid until OnDeserialization has been called. HashHelpers.SerializationInfoTable.Add(this, info); } public IEqualityComparer<TKey> Comparer { get { return _comparer; } } public int Count { get { return _count - _freeCount; } } public KeyCollection Keys { get { if (_keys == null) _keys = new KeyCollection(this); return _keys; } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { if (_keys == null) _keys = new KeyCollection(this); return _keys; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { if (_keys == null) _keys = new KeyCollection(this); return _keys; } } public ValueCollection Values { get { if (_values == null) _values = new ValueCollection(this); return _values; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { if (_values == null) _values = new ValueCollection(this); return _values; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { if (_values == null) _values = new ValueCollection(this); return _values; } } public TValue this[TKey key] { get { int i = FindEntry(key); if (i >= 0) return _entries[i].value; ThrowHelper.ThrowKeyNotFoundException(key); return default(TValue); } set { bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting); Debug.Assert(modified); } } public void Add(TKey key, TValue value) { bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting); Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown. } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { Add(keyValuePair.Key, keyValuePair.Value); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[i].value, keyValuePair.Value)) { return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[i].value, keyValuePair.Value)) { Remove(keyValuePair.Key); return true; } return false; } public void Clear() { int count = _count; if (count > 0) { int[] buckets = _buckets; for (int i = 0; i < buckets.Length; i++) { buckets[i] = -1; } _count = 0; _freeList = -1; _freeCount = 0; _version++; Array.Clear(_entries, 0, count); } } public bool ContainsKey(TKey key) { return FindEntry(key) >= 0; } public bool ContainsValue(TValue value) { if (value == null) { for (int i = 0; i < _count; i++) { if (_entries[i].hashCode >= 0 && _entries[i].value == null) return true; } } else { EqualityComparer<TValue> c = EqualityComparer<TValue>.Default; for (int i = 0; i < _count; i++) { if (_entries[i].hashCode >= 0 && c.Equals(_entries[i].value, value)) return true; } } return false; } private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = _count; Entry[] entries = _entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } public Enumerator GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } info.AddValue(VersionName, _version); info.AddValue(ComparerName, _comparer, typeof(IEqualityComparer<TKey>)); info.AddValue(HashSizeName, _buckets == null ? 0 : _buckets.Length); // This is the length of the bucket array if (_buckets != null) { var array = new KeyValuePair<TKey, TValue>[Count]; CopyTo(array, 0); info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[])); } } private int FindEntry(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (_buckets != null) { int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF; for (int i = _buckets[hashCode % _buckets.Length]; i >= 0; i = _entries[i].next) { if (_entries[i].hashCode == hashCode && _comparer.Equals(_entries[i].key, key)) return i; } } return -1; } private int Initialize(int capacity) { int size = HashHelpers.GetPrime(capacity); int[] buckets = new int[size]; for (int i = 0; i < buckets.Length; i++) { buckets[i] = -1; } _freeList = -1; _buckets = buckets; _entries = new Entry[size]; return size; } private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (_buckets == null) Initialize(0); int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF; int targetBucket = hashCode % _buckets.Length; int collisionCount = 0; for (int i = _buckets[targetBucket]; i >= 0; i = _entries[i].next) { if (_entries[i].hashCode == hashCode && _comparer.Equals(_entries[i].key, key)) { if (behavior == InsertionBehavior.OverwriteExisting) { _entries[i].value = value; _version++; return true; } if (behavior == InsertionBehavior.ThrowOnExisting) { ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); } return false; } collisionCount++; } int index; if (_freeCount > 0) { index = _freeList; _freeList = _entries[index].next; _freeCount--; } else { if (_count == _entries.Length) { Resize(); targetBucket = hashCode % _buckets.Length; } index = _count; _count++; } _entries[index].hashCode = hashCode; _entries[index].next = _buckets[targetBucket]; _entries[index].key = key; _entries[index].value = value; _buckets[targetBucket] = index; _version++; // If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing // i.e. EqualityComparer<string>.Default. if (collisionCount > HashHelpers.HashCollisionThreshold && _comparer is NonRandomizedStringEqualityComparer) { _comparer = (IEqualityComparer<TKey>)EqualityComparer<string>.Default; Resize(_entries.Length, true); } return true; } public virtual void OnDeserialization(object sender) { SerializationInfo siInfo; HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo); if (siInfo == null) { // We can return immediately if this function is called twice. // Note we remove the serialization info from the table at the end of this method. return; } int realVersion = siInfo.GetInt32(VersionName); int hashsize = siInfo.GetInt32(HashSizeName); _comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>)); if (hashsize != 0) { Initialize(hashsize); KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[]) siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[])); if (array == null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys); } for (int i = 0; i < array.Length; i++) { if (array[i].Key == null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey); } Add(array[i].Key, array[i].Value); } } else { _buckets = null; } _version = realVersion; HashHelpers.SerializationInfoTable.Remove(this); } private void Resize() { Resize(HashHelpers.ExpandPrime(_count), false); } private void Resize(int newSize, bool forceNewHashCodes) { Debug.Assert(newSize >= _entries.Length); int[] buckets = new int[newSize]; for (int i = 0; i < buckets.Length; i++) { buckets[i] = -1; } Entry[] entries = new Entry[newSize]; int count = _count; Array.Copy(_entries, 0, entries, 0, count); if (forceNewHashCodes) { for (int i = 0; i < count; i++) { if (entries[i].hashCode != -1) { entries[i].hashCode = (_comparer.GetHashCode(entries[i].key) & 0x7FFFFFFF); } } } for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { int bucket = entries[i].hashCode % newSize; entries[i].next = buckets[bucket]; buckets[bucket] = i; } } _buckets = buckets; _entries = entries; } // The overload Remove(TKey key, out TValue value) is a copy of this method with one additional // statement to copy the value for entry being removed into the output parameter. // Code has been intentionally duplicated for performance reasons. public bool Remove(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (_buckets != null) { int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF; int bucket = hashCode % _buckets.Length; int last = -1; int i = _buckets[bucket]; while (i >= 0) { ref Entry entry = ref _entries[i]; if (entry.hashCode == hashCode && _comparer.Equals(entry.key, key)) { if (last < 0) { _buckets[bucket] = entry.next; } else { _entries[last].next = entry.next; } entry.hashCode = -1; entry.next = _freeList; if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { entry.key = default(TKey); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { entry.value = default(TValue); } _freeList = i; _freeCount++; _version++; return true; } last = i; i = entry.next; } } return false; } // This overload is a copy of the overload Remove(TKey key) with one additional // statement to copy the value for entry being removed into the output parameter. // Code has been intentionally duplicated for performance reasons. public bool Remove(TKey key, out TValue value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (_buckets != null) { int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF; int bucket = hashCode % _buckets.Length; int last = -1; int i = _buckets[bucket]; while (i >= 0) { ref Entry entry = ref _entries[i]; if (entry.hashCode == hashCode && _comparer.Equals(entry.key, key)) { if (last < 0) { _buckets[bucket] = entry.next; } else { _entries[last].next = entry.next; } value = entry.value; entry.hashCode = -1; entry.next = _freeList; if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { entry.key = default(TKey); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { entry.value = default(TValue); } _freeList = i; _freeCount++; _version++; return true; } last = i; i = entry.next; } } value = default(TValue); return false; } public bool TryGetValue(TKey key, out TValue value) { int i = FindEntry(key); if (i >= 0) { value = _entries[i].value; return true; } value = default(TValue); return false; } public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None); bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { CopyTo(array, index); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[]; if (pairs != null) { CopyTo(pairs, index); } else if (array is DictionaryEntry[]) { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; Entry[] entries = _entries; for (int i = 0; i < _count; i++) { if (entries[i].hashCode >= 0) { dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value); } } } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } try { int count = _count; Entry[] entries = _entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } /// <summary> /// Ensures that the dictionary can hold up to 'capacity' entries without any further expansion of its backing storage /// </summary> public int EnsureCapacity(int capacity) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); if (_entries != null && _entries.Length >= capacity) return _entries.Length; if (_buckets == null) return Initialize(capacity); int newSize = HashHelpers.GetPrime(capacity); Resize(newSize, forceNewHashCodes: false); return newSize; } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } bool IDictionary.IsFixedSize { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } ICollection IDictionary.Keys { get { return (ICollection)Keys; } } ICollection IDictionary.Values { get { return (ICollection)Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { int i = FindEntry((TKey)key); if (i >= 0) { return _entries[i].value; } } return null; } set { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } } private static bool IsCompatibleKey(object key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } return (key is TKey); } void IDictionary.Add(object key, object value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { Add(tempKey, (TValue)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } bool IDictionary.Contains(object key) { if (IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(this, Enumerator.DictEntry); } void IDictionary.Remove(object key) { if (IsCompatibleKey(key)) { Remove((TKey)key); } } public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private Dictionary<TKey, TValue> _dictionary; private int _version; private int _index; private KeyValuePair<TKey, TValue> _current; private int _getEnumeratorRetType; // What should Enumerator.Current return? internal const int DictEntry = 1; internal const int KeyValuePair = 2; internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType) { _dictionary = dictionary; _version = dictionary._version; _index = 0; _getEnumeratorRetType = getEnumeratorRetType; _current = new KeyValuePair<TKey, TValue>(); } public bool MoveNext() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends. // dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue while ((uint)_index < (uint)_dictionary._count) { ref Entry entry = ref _dictionary._entries[_index++]; if (entry.hashCode >= 0) { _current = new KeyValuePair<TKey, TValue>(entry.key, entry.value); return true; } } _index = _dictionary._count + 1; _current = new KeyValuePair<TKey, TValue>(); return false; } public KeyValuePair<TKey, TValue> Current { get { return _current; } } public void Dispose() { } object IEnumerator.Current { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } if (_getEnumeratorRetType == DictEntry) { return new System.Collections.DictionaryEntry(_current.Key, _current.Value); } else { return new KeyValuePair<TKey, TValue>(_current.Key, _current.Value); } } } void IEnumerator.Reset() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; _current = new KeyValuePair<TKey, TValue>(); } DictionaryEntry IDictionaryEnumerator.Entry { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return new DictionaryEntry(_current.Key, _current.Value); } } object IDictionaryEnumerator.Key { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _current.Key; } } object IDictionaryEnumerator.Value { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _current.Value; } } } [DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private Dictionary<TKey, TValue> _dictionary; public KeyCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } _dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(_dictionary); } public void CopyTo(TKey[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < _dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = _dictionary._count; Entry[] entries = _dictionary._entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].key; } } public int Count { get { return _dictionary.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } void ICollection<TKey>.Add(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } void ICollection<TKey>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } bool ICollection<TKey>.Contains(TKey item) { return _dictionary.ContainsKey(item); } bool ICollection<TKey>.Remove(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); return false; } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() { return new Enumerator(_dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < _dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } TKey[] keys = array as TKey[]; if (keys != null) { CopyTo(keys, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = _dictionary._count; Entry[] entries = _dictionary._entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].key; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dictionary).SyncRoot; } } public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> _dictionary; private int _index; private int _version; private TKey _currentKey; internal Enumerator(Dictionary<TKey, TValue> dictionary) { _dictionary = dictionary; _version = dictionary._version; _index = 0; _currentKey = default(TKey); } public void Dispose() { } public bool MoveNext() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } while ((uint)_index < (uint)_dictionary._count) { ref Entry entry = ref _dictionary._entries[_index++]; if (entry.hashCode >= 0) { _currentKey = entry.key; return true; } } _index = _dictionary._count + 1; _currentKey = default(TKey); return false; } public TKey Current { get { return _currentKey; } } object System.Collections.IEnumerator.Current { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _currentKey; } } void System.Collections.IEnumerator.Reset() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; _currentKey = default(TKey); } } } [DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private Dictionary<TKey, TValue> _dictionary; public ValueCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } _dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(_dictionary); } public void CopyTo(TValue[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < _dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = _dictionary._count; Entry[] entries = _dictionary._entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].value; } } public int Count { get { return _dictionary.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } void ICollection<TValue>.Add(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Remove(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); return false; } void ICollection<TValue>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Contains(TValue item) { return _dictionary.ContainsValue(item); } IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() { return new Enumerator(_dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < _dictionary.Count) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); TValue[] values = array as TValue[]; if (values != null) { CopyTo(values, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = _dictionary._count; Entry[] entries = _dictionary._entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].value; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dictionary).SyncRoot; } } public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> _dictionary; private int _index; private int _version; private TValue _currentValue; internal Enumerator(Dictionary<TKey, TValue> dictionary) { _dictionary = dictionary; _version = dictionary._version; _index = 0; _currentValue = default(TValue); } public void Dispose() { } public bool MoveNext() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } while ((uint)_index < (uint)_dictionary._count) { ref Entry entry = ref _dictionary._entries[_index++]; if (entry.hashCode >= 0) { _currentValue = entry.value; return true; } } _index = _dictionary._count + 1; _currentValue = default(TValue); return false; } public TValue Current { get { return _currentValue; } } object System.Collections.IEnumerator.Current { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _currentValue; } } void System.Collections.IEnumerator.Reset() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; _currentValue = default(TValue); } } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using OpenLiveWriter.Interop.Com; using Microsoft.Win32; using OpenLiveWriter.CoreServices.Settings; using System.Security.Principal; namespace OpenLiveWriter.CoreServices { [Flags] public enum RunningObjectTableFlags { /// <summary> /// When set, indicates a strong registration for the object. /// </summary> /// <remarks> /// When an object is registered, the ROT always calls AddRef on the object. For a weak registration /// (ROTFLAGS_REGISTRATIONKEEPSALIVE not set), the ROT will release the object whenever the last strong /// reference to the object is released. For a strong registration (ROTFLAGS_REGISTRATIONKEEPSALIVE set), the /// ROT prevents the object from being destroyed until the object's registration is explicitly revoked. /// </remarks> RegistrationKeepsAlive = 0x1, /// <summary> /// When set, any client can connect to the running object through its entry in the ROT. When not set, only /// clients in the window station that registered the object can connect to it. /// </summary> /// <remarks> /// A server registered as either LocalService or RunAs can set the ROTFLAGS_ALLOWANYCLIENT flag in its call /// to Register to allow any client to connect to it. A server setting this bit must have its executable name /// in the AppID section of the registry that refers to the AppID for the executable. An "activate as /// activator" server (not registered as LocalService or RunAs) must not set this flag in its call to Register. /// </remarks> AllowAnyClient = 0x2, } /// <summary> /// Handy wrapper for the COM Running Object Table. The scope /// for this table is session-wide. /// </summary> public class RunningObjectTable : IDisposable { private static readonly string APP_ID = "{6DC87AF3-AA96-47AD-9F42-E440C61CE4FB}"; private static readonly string EXE_REGISTRY_PATH = @"Software\Classes\AppID\OpenLiveWriter.exe"; private static readonly string APP_ID_REGISTRY_PATH = @"Software\Classes\AppID\" + APP_ID; private static readonly string ALLOW_ANY_CLIENT = "AllowAnyClient"; public static void EnsureComRegistration() { // Are we running with Administrator privileges? If so, we need to write to HKLM. Otherwise, need to write to HKCU. RegistryKey rootKey = IsInAdministratorRole ? Registry.LocalMachine : Registry.CurrentUser; try { // A client calling IRunningObjectTable::Register with the ROTFLAGS_ALLOWANYCLIENT bit must have its // executable name in the AppID section of the registry that refers to the AppID for the executable. var exeRegistrySettings = new RegistrySettingsPersister(rootKey, EXE_REGISTRY_PATH); exeRegistrySettings.Set("AppID", APP_ID); // A RunAs entry must be present because the system prohibits "activate as activator" processes from registering in // the ROT with ROTFLAGS_ALLOWANYCLIENT.This is done for security reasons. var appIdRegistrySettings = new RegistrySettingsPersister(rootKey, APP_ID_REGISTRY_PATH); appIdRegistrySettings.Set("", "OpenLiveWriter.exe"); appIdRegistrySettings.Set("RunAs", "Interactive User"); if (IsInAdministratorRole) { // If we wrote to HKLM, even medium integrity processes can now use ROTFLAGS_ALLOWANYCLIENT. // However, medium integrity processes can't read from HKLM to see if it's set or not, so we // need a duplicate setting to store this information. exeRegistrySettings = new RegistrySettingsPersister(Registry.CurrentUser, EXE_REGISTRY_PATH); exeRegistrySettings.Set("AllowAnyClient", true); } } catch (Exception ex) { Trace.Fail("Exception thrown while setting RunningObjectTable COM registration: \r\n" + ex); if (!RegistryHelper.IsRegistryException(ex)) throw; } } private IRunningObjectTable _rot; public RunningObjectTable() { int result = Ole32.GetRunningObjectTable(0, out _rot); if (result != 0) throw new Win32Exception(result); } ~RunningObjectTable() { Dispose(false); } public void Dispose() { Dispose(true); } /// <summary> /// Releases the Running Object Table instance. /// </summary> protected virtual void Dispose(bool disposing) { if (disposing) { GC.SuppressFinalize(this); if (_rot != null) Marshal.ReleaseComObject(_rot); _rot = null; } } /// <summary> /// Registers the COM object under the given name. The returned /// IDisposable must be disposed in order to remove the object /// from the table, otherwise resource leaks may result (I think). /// </summary> public IDisposable Register(string itemName, object obj) { IMoniker mk = CreateMoniker(itemName); // The ALLOW_ANY_CLIENT setting will be set to true if we've been launched via 'Run as administrator' at // least once because this means we wrote the HKLM registry entries to allow passing the // ROTFLAGS_ALLOWANYCLIENT flag. var exeRegistrySettings = new RegistrySettingsPersister(Registry.CurrentUser, EXE_REGISTRY_PATH); bool allowAnyClient = (bool)exeRegistrySettings.Get(ALLOW_ANY_CLIENT, typeof(bool), false); int rotRegistrationFlags = allowAnyClient ? (int)(RunningObjectTableFlags.RegistrationKeepsAlive | RunningObjectTableFlags.AllowAnyClient) : (int)(RunningObjectTableFlags.RegistrationKeepsAlive); try { int registration = _rot.Register(rotRegistrationFlags, obj, mk); return new RegistrationHandle(this, registration); } catch (COMException ex) { Trace.Fail("Exception thrown from IRunningObjectTable::Register: \r\n" + ex); // If registration failed, try again without ROTFLAGS_ALLOWANYCLIENT because the AllowAnyClient setting might be out of date. exeRegistrySettings.Set(ALLOW_ANY_CLIENT, false); rotRegistrationFlags = (int)(RunningObjectTableFlags.RegistrationKeepsAlive); int registration = _rot.Register(rotRegistrationFlags, obj, mk); return new RegistrationHandle(this, registration); } } private static IMoniker CreateMoniker(string itemName) { IMoniker mk; int result = Ole32.CreateItemMoniker("!", itemName, out mk); if (result != 0) throw new Win32Exception(result); return mk; } /// <summary> /// Attempts to retrieve an item from the ROT; returns null if not found. /// </summary> public object GetObject(string itemName) { try { IMoniker mk = CreateMoniker(itemName); object obj; int hr = _rot.GetObject(mk, out obj); if (hr != HRESULT.S_OK) { Trace.WriteLine(String.Format("ROT.GetObject returned HRESULT 0x{0:x}.", hr)); return null; } return obj; } catch (COMException e) { if (e.ErrorCode == RPC_E.CALL_FAILED_DNE) return null; throw; } } private void Revoke(int registration) { _rot.Revoke(registration); } public static bool IsInAdministratorRole { get { WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); return principal.IsInRole(WindowsBuiltInRole.Administrator); } } private class RegistrationHandle : IDisposable { private RunningObjectTable _rot; private int _registration; public RegistrationHandle(RunningObjectTable rot, int registration) { _rot = rot; _registration = registration; } ~RegistrationHandle() { Debug.Fail("RegistrationHandle was not disposed!!"); // Can't use normal Dispose() because the _rot may already // have been garbage collected by this point IRunningObjectTable rot; int result = Ole32.GetRunningObjectTable(0, out rot); if (result == 0) { rot.Revoke(_registration); Marshal.ReleaseComObject(rot); } } public void Dispose() { GC.SuppressFinalize(this); _rot.Revoke(_registration); } } } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace flaming_octo_meme.Entities { /// <summary> /// A generic game entity with basic drawing functionality. /// </summary> public abstract class SpriteComponent : DrawableGameComponent { #region Fields protected SpriteBatch mSpriteBatch; private Texture2D mBlankTexture; private Vector2 mPosition = Vector2.Zero; private bool mDrawOrigin = false; private bool mDrawBoundingRect = false; #endregion #region Properties /// <summary> /// The sprite's texture. /// </summary> protected Texture2D Texture { get; set; } /// <summary> /// Which parts of the texture to draw. If null, the whole texture is drawn. /// </summary> protected virtual Nullable<Rectangle> SourceRectangle { get; set; } /// <summary> /// The location of the sprite on the screen. /// </summary> public Vector2 Position { get { return mPosition; } set { int w = Game.GraphicsDevice.Viewport.Width; int h = Game.GraphicsDevice.Viewport.Height; if (value.X > w) value.X -= w; else if (value.X < 0) value.X += w; if (value.Y < 0) value.Y += h; else if (value.Y > h) value.Y -= h; mPosition = value; } } /// <summary> /// The bounding rectangle of the sprite, used for collision detection. /// </summary> public abstract Rectangle BoundingRect { get; } /// <summary> /// Specifies the angle (in radians) to rotate the sprite around its center. /// </summary> protected float Rotation { get; set; } /// <summary> /// How the sprite should be tinted. Use Color.White for full color with no tinting. /// </summary> public Color Tint { get; set; } /// <summary> /// The scale factor of the sprite. /// </summary> protected float Scale { get; set; } /// <summary> /// The layer depth of this sprite. By default, 0 represents the /// front layer and 1 represents a back layer. /// </summary> protected float Depth { get; set; } /// <summary> /// Sprite effects to apply when drawing this sprite. /// </summary> protected SpriteEffects Effects { get; set; } /// <summary> /// The center point of the sprite. /// </summary> /* TODO: is this really the center of the sprite? */ protected virtual Vector2 Offset { get { if (SourceRectangle == null) { //Console.WriteLine("A SpriteComponent has a null SourceRectangle!"); if (Texture == null) { Console.WriteLine("A SpriteComponent has a null Texture!"); return Vector2.Zero; } else { return new Vector2(-Texture.Width / 2, -Texture.Height / 2); } } else { return new Vector2(-SourceRectangle.Value.Width / 2, -SourceRectangle.Value.Height / 2); } } } #endregion public SpriteComponent(Game game) : base(game) { Scale = 1; Tint = Color.White; } /// <summary> /// Initializes the component. Override this method to load any non-graphics /// resources and query for any required services. Called after the Game and /// GraphicsDevice are created, but before LoadContent. /// </summary> public override void Initialize() { mSpriteBatch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch; base.Initialize(); } /// <summary> /// Called when graphics resources need to be loaded. Override this method /// to load any component-specific graphics resources. /// </summary> protected override void LoadContent() { mBlankTexture = Game.Content.Load<Texture2D>("blank"); } /// <summary> /// Provides basic drawing functionality for the SpriteComponent, drawing /// it's texture and applying effects such as scale and rotation. /// </summary> /// <param name="gameTime"></param> public override void Draw(GameTime gameTime) { if (Texture == null) { Console.WriteLine("A SpriteComponent has a null Texture!"); return; } mSpriteBatch.Begin(); mSpriteBatch.Draw(Texture, Position, SourceRectangle, Tint, Rotation, -Offset, Scale, Effects, Depth); // Used for debug if (mDrawOrigin == true) { mSpriteBatch.Draw(mBlankTexture, new Rectangle((int)(Position.X), (int)(Position.Y), 5, 5), Color.White); } // Used for debug if (mDrawBoundingRect == true) { DrawBorder(this.BoundingRect, 1, Color.White); if (this is Player) { DrawBorder(((Player)this).BoundingRectSmall, 1, Color.Tomato); } } mSpriteBatch.End(); base.Draw(gameTime); } /// <summary> /// Draws a hollow rectangle. Used for debugging purposes. /// </summary> /// <param name="rectangleToDraw"></param> /// <param name="thicknessOfBorder"></param> /// <param name="borderColor"></param> private void DrawBorder(Rectangle rectangleToDraw, int thicknessOfBorder, Color borderColor) { // Draw top line mSpriteBatch.Draw(mBlankTexture, new Rectangle(rectangleToDraw.X, rectangleToDraw.Y, rectangleToDraw.Width, thicknessOfBorder), borderColor); // Draw left line mSpriteBatch.Draw(mBlankTexture, new Rectangle(rectangleToDraw.X, rectangleToDraw.Y, thicknessOfBorder, rectangleToDraw.Height), borderColor); // Draw right line mSpriteBatch.Draw(mBlankTexture, new Rectangle((rectangleToDraw.X + rectangleToDraw.Width - thicknessOfBorder), rectangleToDraw.Y, thicknessOfBorder, rectangleToDraw.Height), borderColor); // Draw bottom line mSpriteBatch.Draw(mBlankTexture, new Rectangle(rectangleToDraw.X, rectangleToDraw.Y + rectangleToDraw.Height - thicknessOfBorder, rectangleToDraw.Width, thicknessOfBorder), borderColor); } /* TODO: this ambiguous, it is NOT moving to X, Y */ protected void Move(float x, float y) { Position = new Vector2(Position.X + x, Position.Y + y); } } }
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; namespace Avro.IO { /// <summary> /// Write leaf values. /// </summary> public class BinaryEncoder : Encoder { private readonly Stream Stream; /// <summary> /// Initializes a new instance of the <see cref="BinaryEncoder"/> class without a backing /// stream. /// </summary> public BinaryEncoder() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="BinaryEncoder"/> class that writes to /// the provided stream. /// </summary> /// <param name="stream">Stream to write to.</param> public BinaryEncoder(Stream stream) { this.Stream = stream; } /// <summary> /// null is written as zero bytes /// </summary> public void WriteNull() { } /// <summary> /// true is written as 1 and false 0. /// </summary> /// <param name="b">Boolean value to write</param> public void WriteBoolean(bool b) { writeByte((byte)(b ? 1 : 0)); } /// <summary> /// int and long values are written using variable-length, zig-zag coding. /// </summary> /// <param name="value">Value to write</param> public void WriteInt(int value) { WriteLong(value); } /// <summary> /// int and long values are written using variable-length, zig-zag coding. /// </summary> /// <param name="value">Value to write</param> public void WriteLong(long value) { ulong n = (ulong)((value << 1) ^ (value >> 63)); while ((n & ~0x7FUL) != 0) { writeByte((byte)((n & 0x7f) | 0x80)); n >>= 7; } writeByte((byte)n); } /// <summary> /// A float is written as 4 bytes. /// The float is converted into a 32-bit integer using a method equivalent to /// Java's floatToIntBits and then encoded in little-endian format. /// </summary> /// <param name="value"></param> public void WriteFloat(float value) { byte[] buffer = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) Array.Reverse(buffer); writeBytes(buffer); } /// <summary> ///A double is written as 8 bytes. ///The double is converted into a 64-bit integer using a method equivalent to ///Java's doubleToLongBits and then encoded in little-endian format. /// </summary> /// <param name="value"></param> public void WriteDouble(double value) { long bits = BitConverter.DoubleToInt64Bits(value); writeByte((byte)(bits & 0xFF)); writeByte((byte)((bits >> 8) & 0xFF)); writeByte((byte)((bits >> 16) & 0xFF)); writeByte((byte)((bits >> 24) & 0xFF)); writeByte((byte)((bits >> 32) & 0xFF)); writeByte((byte)((bits >> 40) & 0xFF)); writeByte((byte)((bits >> 48) & 0xFF)); writeByte((byte)((bits >> 56) & 0xFF)); } /// <summary> /// Bytes are encoded as a long followed by that many bytes of data. /// </summary> /// <param name="value"></param> public void WriteBytes(byte[] value) { WriteLong(value.Length); writeBytes(value); } /// <summary> /// Bytes are encoded as a long followed by that many bytes of data. /// </summary> /// <param name="value">The byte[] to be read (fully or partially)</param> /// <param name="offset">The offset from the beginning of the byte[] to start writing</param> /// <param name="length">The length of the data to be read from the byte[].</param> public void WriteBytes(byte[] value, int offset, int length) { WriteLong(length); writeBytes(value, offset, length); } /// <summary> /// A string is encoded as a long followed by /// that many bytes of UTF-8 encoded character data. /// </summary> /// <param name="value"></param> public void WriteString(string value) { WriteBytes(System.Text.Encoding.UTF8.GetBytes(value)); } /// <inheritdoc/> public void WriteEnum(int value) { WriteLong(value); } /// <inheritdoc/> public void StartItem() { } /// <inheritdoc/> public void SetItemCount(long value) { if (value > 0) WriteLong(value); } /// <inheritdoc/> public void WriteArrayStart() { } /// <inheritdoc/> public void WriteArrayEnd() { WriteLong(0); } /// <inheritdoc/> public void WriteMapStart() { } /// <inheritdoc/> public void WriteMapEnd() { WriteLong(0); } /// <inheritdoc/> public void WriteUnionIndex(int value) { WriteLong(value); } /// <inheritdoc/> public void WriteFixed(byte[] data) { WriteFixed(data, 0, data.Length); } /// <inheritdoc/> public void WriteFixed(byte[] data, int start, int len) { Stream.Write(data, start, len); } private void writeBytes(byte[] bytes) { Stream.Write(bytes, 0, bytes.Length); } private void writeBytes(byte[] bytes, int offset, int length) { Stream.Write(bytes, offset, length); } private void writeByte(byte b) { Stream.WriteByte(b); } /// <summary> /// Flushes the underlying stream. /// </summary> public void Flush() { Stream.Flush(); } } }
// // ImageHandler.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using Xwt.Drawing; using System.Collections.Generic; using Xwt.CairoBackend; using System.Linq; namespace Xwt.GtkBackend { public class ImageHandler: ImageBackendHandler { public override object LoadFromFile (string file) { return new GtkImage (new Gdk.Pixbuf (file)); } public override object LoadFromStream (System.IO.Stream stream) { using (Gdk.PixbufLoader loader = new Gdk.PixbufLoader (stream)) return new GtkImage (loader.Pixbuf); } public override void SaveToStream (object backend, System.IO.Stream stream, ImageFileType fileType) { var pix = (GtkImage)backend; var buffer = pix.Frames[0].Pixbuf.SaveToBuffer (GetFileType (fileType)); stream.Write (buffer, 0, buffer.Length); } public override object CreateCustomDrawn (ImageDrawCallback drawCallback) { return new GtkImage (drawCallback); } public override object CreateMultiResolutionImage (IEnumerable<object> images) { var refImg = (GtkImage) images.First (); var f = refImg.Frames [0]; var frames = images.Cast<GtkImage> ().Select (img => new GtkImage.ImageFrame (img.Frames[0].Pixbuf, f.Width, f.Height, true)); return new GtkImage (frames); } public override object CreateMultiSizeIcon (IEnumerable<object> images) { var frames = images.Cast<GtkImage> ().SelectMany (img => img.Frames); return new GtkImage (frames); } string GetFileType (ImageFileType type) { switch (type) { case ImageFileType.Bmp: return "bmp"; case ImageFileType.Jpeg: return "jpeg"; case ImageFileType.Png: return "png"; default: throw new NotSupportedException (); } } public override Image GetStockIcon (string id) { return ApplicationContext.Toolkit.WrapImage (Util.ToGtkStock (id)); } public override void SetBitmapPixel (object handle, int x, int y, Xwt.Drawing.Color color) { var pix = ((GtkImage)handle).Frames[0].Pixbuf; unsafe { byte* p = (byte*) pix.Pixels; p += y * pix.Rowstride + x * pix.NChannels; p[0] = (byte)(color.Red * 255); p[1] = (byte)(color.Green * 255); p[2] = (byte)(color.Blue * 255); p[3] = (byte)(color.Alpha * 255); } } public override Xwt.Drawing.Color GetBitmapPixel (object handle, int x, int y) { var pix = ((GtkImage)handle).Frames[0].Pixbuf; unsafe { byte* p = (byte*) pix.Pixels; p += y * pix.Rowstride + x * pix.NChannels; return Xwt.Drawing.Color.FromBytes (p[0], p[1], p[2], p[3]); } } public override void Dispose (object backend) { ((GtkImage)backend).Dispose (); } public override bool HasMultipleSizes (object handle) { return ((GtkImage)handle).HasMultipleSizes; } public override Size GetSize (object handle) { var pix = handle as GtkImage; return pix.DefaultSize; } public override object CopyBitmap (object handle) { var pix = ((GtkImage)handle).Frames[0].Pixbuf; return new GtkImage (pix.Copy ()); } public override void CopyBitmapArea (object srcHandle, int srcX, int srcY, int width, int height, object destHandle, int destX, int destY) { var pixSrc = ((GtkImage)srcHandle).Frames[0].Pixbuf; var pixDst = ((GtkImage)destHandle).Frames[0].Pixbuf; pixSrc.CopyArea (srcX, srcY, width, height, pixDst, destX, destY); } public override object CropBitmap (object handle, int srcX, int srcY, int width, int height) { var pix = ((GtkImage)handle).Frames[0].Pixbuf; Gdk.Pixbuf res = new Gdk.Pixbuf (pix.Colorspace, pix.HasAlpha, pix.BitsPerSample, width, height); res.Fill (0); pix.CopyArea (srcX, srcY, width, height, res, 0, 0); return new GtkImage (res); } public override bool IsBitmap (object handle) { var img = (GtkImage) handle; return !img.HasMultipleSizes; } public override object ConvertToBitmap (object handle, double width, double height, double scaleFactor, ImageFormat format) { var img = (GtkImage) handle; var f = new GtkImage.ImageFrame (img.GetBestFrame (ApplicationContext, scaleFactor, width, height, true), (int)width, (int)height, true); return new GtkImage (new GtkImage.ImageFrame [] { f }); } internal static Gdk.Pixbuf CreateBitmap (string stockId, double width, double height, double scaleFactor) { Gdk.Pixbuf result = null; Gtk.IconSet iconset = Gtk.IconFactory.LookupDefault (stockId); if (iconset != null) { // Find the size that better fits the requested size Gtk.IconSize gsize = Util.GetBestSizeFit (width); result = iconset.RenderIcon (Gtk.Widget.DefaultStyle, Gtk.TextDirection.Ltr, Gtk.StateType.Normal, gsize, null, null, scaleFactor); if (result == null || result.Width < width * scaleFactor) { var gsize2x = Util.GetBestSizeFit (width * scaleFactor, iconset.Sizes); if (gsize2x != Gtk.IconSize.Invalid && gsize2x != gsize) // Don't dispose the previous result since the icon is owned by the IconSet result = iconset.RenderIcon (Gtk.Widget.DefaultStyle, Gtk.TextDirection.Ltr, Gtk.StateType.Normal, gsize2x, null, null); } } if (result == null && Gtk.IconTheme.Default.HasIcon (stockId)) result = Gtk.IconTheme.Default.LoadIcon (stockId, (int)width, (Gtk.IconLookupFlags)0); if (result == null) { return CreateBitmap (Gtk.Stock.MissingImage, width, height, scaleFactor); } return result; } } public class GtkImage: IDisposable { public class ImageFrame { public Gdk.Pixbuf Pixbuf { get; private set; } public int Width { get; private set; } public int Height { get; private set; } public double Scale { get; set; } public bool Owned { get; set; } public ImageFrame (Gdk.Pixbuf pix, bool owned) { Pixbuf = pix; Width = pix.Width; Height = pix.Height; Scale = 1; Owned = owned; } public ImageFrame (Gdk.Pixbuf pix, int width, int height, bool owned) { Pixbuf = pix; Width = width; Height = height; Scale = (double)pix.Width / (double) width; Owned = owned; } public void Dispose () { if (Owned) Pixbuf.Dispose (); } } ImageFrame[] frames; ImageDrawCallback drawCallback; string stockId; public ImageFrame[] Frames { get { return frames; } } public GtkImage (Gdk.Pixbuf img) { this.frames = new ImageFrame [] { new ImageFrame (img, true) }; } public GtkImage (string stockId) { this.stockId = stockId; } public GtkImage (IEnumerable<Gdk.Pixbuf> frames) { this.frames = frames.Select (p => new ImageFrame (p, true)).ToArray (); } public GtkImage (IEnumerable<ImageFrame> frames) { this.frames = frames.ToArray (); } public GtkImage (ImageDrawCallback drawCallback) { this.drawCallback = drawCallback; } public void Dispose () { if (frames != null) { foreach (var f in frames) f.Dispose (); } } public Size DefaultSize { get { if (frames != null) return new Size (frames[0].Pixbuf.Width, frames[0].Pixbuf.Height); else return new Size (16, 16); } } public bool HasMultipleSizes { get { return frames != null && frames.Length > 1 || drawCallback != null || stockId != null; } } Gdk.Pixbuf FindFrame (int width, int height, double scaleFactor) { if (frames == null) return null; if (frames.Length == 1) return frames [0].Pixbuf; Gdk.Pixbuf best = null; int bestSizeMatch = 0; double bestResolutionMatch = 0; foreach (var f in frames) { int sizeMatch; if (f.Width == width && f.Height == height) { if (f.Scale == scaleFactor) return f.Pixbuf; // Exact match sizeMatch = 2; // Exact size } else if (f.Width >= width && f.Height >= height) sizeMatch = 1; // Bigger size else sizeMatch = 0; // Smaller size var resolutionMatch = ((double)f.Pixbuf.Width * (double)f.Pixbuf.Height) / ((double)width * (double)height * scaleFactor); if ( best == null || (bestResolutionMatch < 1 && resolutionMatch > bestResolutionMatch) || (bestResolutionMatch >= 1 && resolutionMatch >= 1 && resolutionMatch <= bestResolutionMatch && (sizeMatch >= bestSizeMatch))) { best = f.Pixbuf; bestSizeMatch = sizeMatch; bestResolutionMatch = resolutionMatch; } } return best; } public Gdk.Pixbuf ToPixbuf (ApplicationContext actx, double width, double height) { return GetBestFrame (actx, 1, width, height, true); } public Gdk.Pixbuf ToPixbuf (ApplicationContext actx, Gtk.Widget w) { return GetBestFrame (actx, Util.GetScaleFactor (w), DefaultSize.Width, DefaultSize.Height, true); } public Gdk.Pixbuf GetBestFrame (ApplicationContext actx, Gtk.Widget w, double width, double height, bool forceExactSize) { return GetBestFrame (actx, Util.GetScaleFactor (w), width, height, forceExactSize); } public Gdk.Pixbuf GetBestFrame (ApplicationContext actx, double scaleFactor, double width, double height, bool forceExactSize) { var f = FindFrame ((int)width, (int)height, scaleFactor); if (f == null || (forceExactSize && (f.Width != (int)width || f.Height != (int)height))) return RenderFrame (actx, scaleFactor, width, height); else return f; } Gdk.Pixbuf RenderFrame (ApplicationContext actx, double scaleFactor, double width, double height) { var swidth = Math.Max ((int)(width * scaleFactor), 1); var sheight = Math.Max ((int)(height * scaleFactor), 1); using (var sf = new Cairo.ImageSurface (Cairo.Format.ARGB32, swidth, sheight)) using (var ctx = new Cairo.Context (sf)) { ImageDescription idesc = new ImageDescription () { Alpha = 1, Size = new Size (width, height) }; ctx.Scale (scaleFactor, scaleFactor); Draw (actx, ctx, scaleFactor, 0, 0, idesc); var f = new ImageFrame (ImageBuilderBackend.CreatePixbuf (sf), Math.Max((int)width,1), Math.Max((int)height,1), true); AddFrame (f); return f.Pixbuf; } } void AddFrame (ImageFrame frame) { if (frames == null) frames = new ImageFrame[] { frame }; else { Array.Resize (ref frames, frames.Length + 1); frames [frames.Length - 1] = frame; } } public void Draw (ApplicationContext actx, Cairo.Context ctx, double scaleFactor, double x, double y, ImageDescription idesc) { if (stockId != null) { ImageFrame frame = null; if (frames != null) frame = frames.FirstOrDefault (f => f.Width == (int) idesc.Size.Width && f.Height == (int) idesc.Size.Height && f.Scale == scaleFactor); if (frame == null) { frame = new ImageFrame (ImageHandler.CreateBitmap (stockId, idesc.Size.Width, idesc.Size.Height, scaleFactor), (int)idesc.Size.Width, (int)idesc.Size.Height, false); frame.Scale = scaleFactor; AddFrame (frame); } DrawPixbuf (ctx, frame.Pixbuf, x, y, idesc); } else if (drawCallback != null) { CairoContextBackend c = new CairoContextBackend (scaleFactor) { Context = ctx }; if (actx != null) { actx.InvokeUserCode (delegate { drawCallback (c, new Rectangle (x, y, idesc.Size.Width, idesc.Size.Height)); }); } else drawCallback (c, new Rectangle (x, y, idesc.Size.Width, idesc.Size.Height)); } else { DrawPixbuf (ctx, GetBestFrame (actx, scaleFactor, idesc.Size.Width, idesc.Size.Height, false), x, y, idesc); } } void DrawPixbuf (Cairo.Context ctx, Gdk.Pixbuf img, double x, double y, ImageDescription idesc) { ctx.Save (); ctx.Translate (x, y); ctx.Scale (idesc.Size.Width / (double)img.Width, idesc.Size.Height / (double)img.Height); Gdk.CairoHelper.SetSourcePixbuf (ctx, img, 0, 0); #pragma warning disable 618 using (var p = ctx.Source) { var pattern = p as Cairo.SurfacePattern; if (pattern != null) { if (idesc.Size.Width > img.Width || idesc.Size.Height > img.Height) { // Fixes blur issue when rendering on an image surface pattern.Filter = Cairo.Filter.Fast; } else pattern.Filter = Cairo.Filter.Good; } } #pragma warning restore 618 if (idesc.Alpha >= 1) ctx.Paint (); else ctx.PaintWithAlpha (idesc.Alpha); ctx.Restore (); } } public class ImageBox: GtkDrawingArea { ImageDescription image; ApplicationContext actx; float yalign = 0.5f, xalign = 0.5f; public ImageBox (ApplicationContext actx, ImageDescription img): this (actx) { Image = img; } public ImageBox (ApplicationContext actx) { this.SetHasWindow (false); this.SetAppPaintable (true); this.actx = actx; } public ImageDescription Image { get { return image; } set { image = value; SetSizeRequest ((int)image.Size.Width, (int)image.Size.Height); QueueResize (); } } public float Yalign { get { return yalign; } set { yalign = value; QueueDraw (); } } public float Xalign { get { return xalign; } set { xalign = value; QueueDraw (); } } protected override void OnSizeRequested (ref Gtk.Requisition requisition) { base.OnSizeRequested (ref requisition); if (!image.IsNull) { requisition.Width = (int) image.Size.Width; requisition.Height = (int) image.Size.Height; } } protected override bool OnDrawn (Cairo.Context cr) { if (image.IsNull) return true; int x = (int)(((float)Allocation.Width - (float)image.Size.Width) * xalign); int y = (int)(((float)Allocation.Height - (float)image.Size.Height) * yalign); if (x < 0) x = 0; if (y < 0) y = 0; ((GtkImage)image.Backend).Draw (actx, cr, Util.GetScaleFactor (this), x, y, image); return base.OnDrawn (cr); } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Xml.Serialization; using System.Collections.Generic; using NPOI.OpenXmlFormats.Spreadsheet.Document; using System.Xml; using NPOI.OpenXml4Net.Util; using System.IO; namespace NPOI.OpenXmlFormats.Spreadsheet { public enum ExternalLinkItem : int { none = 0, externalBook=1, ddeLink, extLst, oleLink } [Serializable] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true, ElementName = "externalLink")] public partial class CT_ExternalLink { private object itemField; public ExternalLinkItem itemType { get; set; } [XmlElement("ddeLink", typeof(CT_DdeLink))] [XmlElement("extLst", typeof(CT_ExtensionList))] [XmlElement("externalBook", typeof(CT_ExternalBook))] [XmlElement("oleLink", typeof(CT_OleLink))] public object Item { get { return this.itemField; } set { this.itemField = value; } } private CT_ExternalBook externalBookField; public CT_ExternalBook externalBook { get { return externalBookField; } set { externalBookField = value; } } private CT_DdeLink ddeLinkField; public CT_DdeLink ddlLink { get { return ddeLinkField; } set { ddeLinkField = value; } } private CT_OleLink oleLinkField; public CT_OleLink oleLink { get { return oleLinkField; } set { oleLinkField = value; } } private CT_ExtensionList extLstField; public CT_ExtensionList extLst { get { return extLstField; } set { extLstField = value; } } public static CT_ExternalLink Parse(XmlNode node, XmlNamespaceManager namespaceManager) { if (node == null) return null; CT_ExternalLink ctObj = new CT_ExternalLink(); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "externalBook") { ctObj.externalBookField = CT_ExternalBook.Parse(childNode, namespaceManager); ctObj.itemField = ctObj.externalBookField; ctObj.itemType = ExternalLinkItem.externalBook; } else if (childNode.LocalName == "ddeLink") { ctObj.ddeLinkField = CT_DdeLink.Parse(childNode, namespaceManager); ctObj.itemField = ctObj.ddeLinkField; ctObj.itemType = ExternalLinkItem.ddeLink; } else if (childNode.LocalName == "oleLink") { ctObj.oleLinkField = CT_OleLink.Parse(childNode, namespaceManager); ctObj.itemField = ctObj.oleLinkField; ctObj.itemType = ExternalLinkItem.oleLink; } else if (childNode.LocalName == "extLst") { ctObj.extLstField = CT_ExtensionList.Parse(childNode, namespaceManager); ctObj.itemField = ctObj.extLstField; ctObj.itemType = ExternalLinkItem.extLst; } } return ctObj; } internal void Write(StreamWriter sw) { sw.Write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"); sw.Write(@"<externalLink xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x14"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"">"); if (this.externalBookField != null) this.externalBookField.Write(sw, "externalBook"); if (this.ddeLinkField != null) this.ddeLinkField.Write(sw, "ddeLink"); if (this.extLstField != null) this.extLstField.Write(sw, "extLst"); if (this.oleLinkField != null) this.oleLinkField.Write(sw, "oleLink"); sw.Write("</externalLink>"); } public void AddNewExternalBook() { this.externalBookField = new CT_ExternalBook(); } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_DdeLink { private List<CT_DdeItem> ddeItemsField = null; // 0..1 private string ddeServiceField; // 1..1 private string ddeTopicField; // 1..1 [XmlArray("ddeItems")] [XmlArrayItem("ddeItem")] public List<CT_DdeItem> ddeItems { get { return this.ddeItemsField; } set { this.ddeItemsField = value; } } [XmlAttribute] public string ddeService { get { return this.ddeServiceField; } set { this.ddeServiceField = value; } } [XmlAttribute] public string ddeTopic { get { return this.ddeTopicField; } set { this.ddeTopicField = value; } } internal static CT_DdeLink Parse(XmlNode node, XmlNamespaceManager namespaceManager) { throw new NotImplementedException(); } internal void Write(StreamWriter sw, string p) { throw new NotImplementedException(); } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_DdeItem { private CT_DdeValues valuesField; private string nameField; private bool oleField; private bool adviseField; private bool preferPicField; public CT_DdeItem() { this.nameField = "0"; this.oleField = false; this.adviseField = false; this.preferPicField = false; } public CT_DdeValues values { get { return this.valuesField; } set { this.valuesField = value; } } [XmlAttribute] [DefaultValueAttribute("0")] public string name { get { return this.nameField; } set { this.nameField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool ole { get { return this.oleField; } set { this.oleField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool advise { get { return this.adviseField; } set { this.adviseField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool preferPic { get { return this.preferPicField; } set { this.preferPicField = value; } } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_DdeValues { private CT_DdeValue[] valueField; private uint rowsField; private uint colsField; public CT_DdeValues() { this.rowsField = ((uint)(1)); this.colsField = ((uint)(1)); } [XmlElement("value")] public CT_DdeValue[] value { get { return this.valueField; } set { this.valueField = value; } } [XmlAttribute] [DefaultValueAttribute(typeof(uint), "1")] public uint rows { get { return this.rowsField; } set { this.rowsField = value; } } [XmlAttribute] [DefaultValueAttribute(typeof(uint), "1")] public uint cols { get { return this.colsField; } set { this.colsField = value; } } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_DdeValue { private string valField; private ST_DdeValueType tField; public CT_DdeValue() { this.tField = ST_DdeValueType.n; } public string val { get { return this.valField; } set { this.valField = value; } } [XmlAttribute] [DefaultValueAttribute(ST_DdeValueType.n)] public ST_DdeValueType t { get { return this.tField; } set { this.tField = value; } } } [Serializable] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=false)] public enum ST_DdeValueType { nil, b, n, e, str, } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_ExternalBook { private CT_ExternalSheetNames sheetNamesField; private CT_ExternalDefinedNames definedNamesField; private CT_ExternalSheetDataSet sheetDataSetField; private string idField; [XmlArrayItem("sheetName", IsNullable=false)] public CT_ExternalSheetNames sheetNames { get { return this.sheetNamesField; } set { this.sheetNamesField = value; } } [XmlArrayItem("definedName", IsNullable=false)] public CT_ExternalDefinedNames definedNames { get { return this.definedNamesField; } set { this.definedNamesField = value; } } [XmlArrayItem("sheetData", IsNullable=false)] public CT_ExternalSheetDataSet sheetDataSet { get { return this.sheetDataSetField; } set { this.sheetDataSetField = value; } } [XmlAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://schemas.openxmlformats.org/officeDocument/2006/relationships")] public string id { get { return this.idField; } set { this.idField = value; } } internal static CT_ExternalBook Parse(XmlNode node, XmlNamespaceManager namespaceManager) { if (node == null) return null; CT_ExternalBook ctObj = new CT_ExternalBook(); ctObj.idField = XmlHelper.ReadString(node.Attributes["id", namespaceManager.LookupNamespace("r")]); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "sheetNames") ctObj.sheetNamesField = CT_ExternalSheetNames.Parse(childNode, namespaceManager); else if (childNode.LocalName == "definedNames") ctObj.definedNamesField = CT_ExternalDefinedNames.Parse(childNode, namespaceManager); else if (childNode.LocalName == "sheetDataSet") ctObj.sheetDataSetField = CT_ExternalSheetDataSet.Parse(childNode, namespaceManager); } return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}", nodeName)); XmlHelper.WriteAttribute(sw, "r:id", this.idField); sw.Write(">"); if (this.sheetNamesField != null) this.sheetNamesField.Write(sw, "sheetNames"); if (this.definedNamesField != null) this.definedNamesField.Write(sw, "definedNames"); if (this.sheetDataSetField != null) this.sheetDataSetField.Write(sw, "sheetDataSet"); sw.Write(string.Format("</{0}>", nodeName)); } } [Serializable] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_ExternalSheetName { private string valField; [XmlAttribute] public string val { get { return this.valField; } set { this.valField = value; } } internal static CT_ExternalSheetName Parse(XmlNode node, XmlNamespaceManager namespaceManager) { CT_ExternalSheetName name = new CT_ExternalSheetName(); name.val = XmlHelper.ReadString(node.Attributes["val"]); return name; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}", nodeName)); XmlHelper.WriteAttribute(sw, "val", this.valField); sw.Write("/>"); } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_ExternalDefinedName { private string nameField; private string refersToField; private uint sheetIdField; private bool sheetIdFieldSpecified; [XmlAttribute] public string name { get { return this.nameField; } set { this.nameField = value; } } [XmlAttribute] public string refersTo { get { return this.refersToField; } set { this.refersToField = value; } } [XmlAttribute] public uint sheetId { get { return this.sheetIdField; } set { this.sheetIdFieldSpecified = true; this.sheetIdField = value; } } [XmlIgnore] public bool sheetIdSpecified { get { return this.sheetIdFieldSpecified; } set { this.sheetIdFieldSpecified = value; } } public bool IsSetSheetId() { return this.sheetIdFieldSpecified && this.sheetIdField != 0; } internal static CT_ExternalDefinedName Parse(XmlNode node, XmlNamespaceManager namespaceManager) { CT_ExternalDefinedName name = new CT_ExternalDefinedName(); name.nameField = XmlHelper.ReadString(node.Attributes["name"]); name.refersToField = XmlHelper.ReadString(node.Attributes["refersTo"]); name.sheetIdFieldSpecified = node.Attributes["sheetId"] != null; if (name.sheetIdFieldSpecified) { name.sheetIdField = XmlHelper.ReadUInt(node.Attributes["sheetId"]); } return name; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}", nodeName)); XmlHelper.WriteAttribute(sw, "name", this.nameField); XmlHelper.WriteAttribute(sw, "refersTo", this.refersToField); if(this.sheetIdFieldSpecified) XmlHelper.WriteAttribute(sw, "sheetId", this.sheetIdField); sw.Write("/>"); } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_ExternalSheetData { public CT_ExternalSheetData () { rowField = new List<CT_ExternalRow>(); } private List<CT_ExternalRow> rowField; private uint sheetIdField; private bool refreshErrorField; [XmlElement("row")] public CT_ExternalRow[] row { get { return this.rowField.ToArray(); } set { this.rowField.Clear(); this.rowField.AddRange(value); } } [XmlAttribute] public uint sheetId { get { return this.sheetIdField; } set { this.sheetIdField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool refreshError { get { return this.refreshErrorField; } set { this.refreshErrorField = value; } } internal static CT_ExternalSheetData Parse(XmlNode node, XmlNamespaceManager namespaceManager) { CT_ExternalSheetData sheetData = new CT_ExternalSheetData(); sheetData.refreshErrorField = XmlHelper.ReadBool(node.Attributes["refreshError"]); sheetData.sheetIdField = XmlHelper.ReadUInt(node.Attributes["sheetId"]); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "row") sheetData.rowField.Add(CT_ExternalRow.Parse(childNode, namespaceManager)); } return sheetData; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}", nodeName)); XmlHelper.WriteAttribute(sw, "sheetId", this.sheetIdField,true); if(this.refreshError) XmlHelper.WriteAttribute(sw, "refreshError", this.refreshErrorField); sw.Write(">"); foreach (CT_ExternalRow ctObj in this.rowField) { ctObj.Write(sw, "row"); } sw.Write(string.Format("</{0}>", nodeName)); } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_ExternalRow { public CT_ExternalRow() { cellField = new List<CT_ExternalCell>(); } private List<CT_ExternalCell> cellField; private uint rField; [XmlElement("cell")] public CT_ExternalCell[] cell { get { return this.cellField.ToArray(); } set { this.cellField.Clear(); this.cellField.AddRange(value); } } [XmlAttribute] public uint r { get { return this.rField; } set { this.rField = value; } } internal static CT_ExternalRow Parse(XmlNode node, XmlNamespaceManager namespaceManager) { CT_ExternalRow row = new CT_ExternalRow(); row.r = XmlHelper.ReadUInt(node.Attributes["r"]); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "cell") row.cellField.Add(CT_ExternalCell.Parse(childNode, namespaceManager)); } return row; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}", nodeName)); XmlHelper.WriteAttribute(sw, "r", this.rField); sw.Write(">"); foreach (CT_ExternalCell ctObj in this.cellField) { ctObj.Write(sw, "cell"); } sw.Write(string.Format("</{0}>", nodeName)); } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_ExternalCell { private string vField; private string rField; private ST_CellType tField; private uint vmField; public CT_ExternalCell() { this.tField = ST_CellType.n; this.vmField = ((uint)(0)); } public string v { get { return this.vField; } set { this.vField = value; } } [XmlAttribute] public string r { get { return this.rField; } set { this.rField = value; } } [XmlAttribute] [DefaultValueAttribute(ST_CellType.n)] public ST_CellType t { get { return this.tField; } set { this.tField = value; } } [XmlAttribute] [DefaultValueAttribute(typeof(uint), "0")] public uint vm { get { return this.vmField; } set { this.vmField = value; } } internal static CT_ExternalCell Parse(XmlNode node, XmlNamespaceManager namespaceManager) { CT_ExternalCell ctObj = new CT_ExternalCell(); ctObj.rField = XmlHelper.ReadString(node.Attributes["r"]); if (node.Attributes["t"] != null) ctObj.tField = (ST_CellType)Enum.Parse(typeof(ST_CellType), node.Attributes["t"].Value); ctObj.vm = XmlHelper.ReadUInt(node.Attributes["vm"]); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "v") ctObj.v = childNode.InnerText; } return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}", nodeName)); XmlHelper.WriteAttribute(sw, "r", this.rField); if (this.t != ST_CellType.n) XmlHelper.WriteAttribute(sw, "t", this.tField.ToString()); XmlHelper.WriteAttribute(sw, "vm", this.vmField); if (this.v == null) { sw.Write("/>"); } else { sw.Write(">"); sw.Write(string.Format("<v>{0}</v>", XmlHelper.EncodeXml(this.v))); sw.Write(string.Format("</{0}>", nodeName)); } } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_OleLink { private List<CT_OleItem> oleItemsField; private string idField; private string progIdField; public List<CT_OleItem> oleItems { get { return this.oleItemsField; } set { this.oleItemsField = value; } } public string id { get { return this.idField; } set { this.idField = value; } } [XmlAttribute] public string progId { get { return this.progIdField; } set { this.progIdField = value; } } internal static CT_OleLink Parse(XmlNode node, XmlNamespaceManager namespaceManager) { CT_OleLink ctObj = new CT_OleLink(); ctObj.idField = XmlHelper.ReadString(node.Attributes["r:id"]); ctObj.progIdField = XmlHelper.ReadString(node.Attributes["progId"]); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "oleItems") { ctObj.oleItemsField = new List<CT_OleItem>(); foreach (XmlNode subNode in childNode.ChildNodes) { ctObj.oleItems.Add(CT_OleItem.Parse(subNode)); } } } return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}", nodeName)); XmlHelper.WriteAttribute(sw, "r:id", this.idField); XmlHelper.WriteAttribute(sw, "progId", this.progIdField); sw.Write(">"); if (this.oleItemsField.Count > 0) { sw.Write("<oleItems>"); foreach (CT_OleItem ctObj in this.oleItemsField) { ctObj.Write(sw, "oleItem"); } sw.Write("</oleItems>"); } sw.Write(string.Format("</{0}>", nodeName)); } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_OleItem { private string nameField; private bool iconField; private bool adviseField; private bool preferPicField; public CT_OleItem() { this.iconField = false; this.adviseField = false; this.preferPicField = false; } [XmlAttribute] public string name { get { return this.nameField; } set { this.nameField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool icon { get { return this.iconField; } set { this.iconField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool advise { get { return this.adviseField; } set { this.adviseField = value; } } [XmlAttribute] [DefaultValueAttribute(false)] public bool preferPic { get { return this.preferPicField; } set { this.preferPicField = value; } } internal static CT_OleItem Parse(XmlNode node) { var ctObj = new CT_OleItem(); ctObj.name = XmlHelper.ReadString(node.Attributes["name"]); ctObj.advise = XmlHelper.ReadBool(node.Attributes["advise"]); ctObj.icon = XmlHelper.ReadBool(node.Attributes["icon"]); ctObj.preferPic = XmlHelper.ReadBool(node.Attributes["preferPic"]); return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}", nodeName)); XmlHelper.WriteAttribute(sw, "name", this.name); XmlHelper.WriteAttribute(sw, "advise", this.advise); XmlHelper.WriteAttribute(sw, "icon", this.iconField, false); XmlHelper.WriteAttribute(sw, "preferPic", this.preferPic); sw.Write(string.Format("/>", nodeName)); } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_ExternalSheetNames { public CT_ExternalSheetNames() { this.sheetNameField = new List<CT_ExternalSheetName>(); } private List<CT_ExternalSheetName> sheetNameField; [XmlElement("sheetName")] public CT_ExternalSheetName[] sheetName { get { return this.sheetNameField.ToArray(); } set { this.sheetNameField.Clear(); this.sheetNameField.AddRange(value); } } internal static CT_ExternalSheetNames Parse(XmlNode node, XmlNamespaceManager namespaceManager) { CT_ExternalSheetNames ctObj = new CT_ExternalSheetNames(); foreach (XmlNode childNode in node.ChildNodes) { ctObj.sheetNameField.Add(CT_ExternalSheetName.Parse(childNode, namespaceManager)); } return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}>", nodeName)); foreach (CT_ExternalSheetName ctObj in this.sheetNameField) { ctObj.Write(sw, "sheetName"); } sw.Write(string.Format("</{0}>", nodeName)); } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_ExternalDefinedNames { public CT_ExternalDefinedNames() { definedNameField = new List<CT_ExternalDefinedName>(); } private List<CT_ExternalDefinedName> definedNameField; [XmlElement("definedName")] public CT_ExternalDefinedName[] definedName { get { return this.definedNameField.ToArray(); } set { this.definedNameField.Clear(); this.definedNameField.AddRange(value); } } internal static CT_ExternalDefinedNames Parse(XmlNode node, XmlNamespaceManager namespaceManager) { CT_ExternalDefinedNames ctObj = new CT_ExternalDefinedNames(); foreach (XmlNode childNode in node.ChildNodes) { ctObj.definedNameField.Add(CT_ExternalDefinedName.Parse(childNode, namespaceManager)); } return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}>", nodeName)); foreach (CT_ExternalDefinedName ctObj in this.definedNameField) { ctObj.Write(sw, "definedName"); } sw.Write(string.Format("</{0}>", nodeName)); } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_ExternalSheetDataSet { public CT_ExternalSheetDataSet() { sheetDataField = new List<CT_ExternalSheetData>(); } private List<CT_ExternalSheetData> sheetDataField; [XmlElement("sheetData")] public CT_ExternalSheetData[] sheetData { get { return this.sheetDataField.ToArray(); } set { this.sheetDataField.Clear(); this.sheetDataField.AddRange(value); } } internal static CT_ExternalSheetDataSet Parse(XmlNode node, XmlNamespaceManager namespaceManager) { CT_ExternalSheetDataSet ctObj = new CT_ExternalSheetDataSet(); foreach (XmlNode childNode in node.ChildNodes) { ctObj.sheetDataField.Add(CT_ExternalSheetData.Parse(childNode, namespaceManager)); } return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}", nodeName)); sw.Write(">"); foreach (CT_ExternalSheetData ctObj in this.sheetDataField) { ctObj.Write(sw, "sheetData"); } sw.Write(string.Format("</{0}>", nodeName)); } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_DdeItems { private CT_DdeItem[] ddeItemField; [XmlElement("ddeItem")] public CT_DdeItem[] ddeItem { get { return this.ddeItemField; } set { this.ddeItemField = value; } } } [Serializable] [DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/spreadsheetml/2006/main", IsNullable=true)] public partial class CT_OleItems { private CT_OleItem[] oleItemField; [XmlElement("oleItem")] public CT_OleItem[] oleItem { get { return this.oleItemField; } set { this.oleItemField = value; } } } }
using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Drecogrizer.Controls.Media; using Drecogrizer.iOS.Media; using UIKit; [assembly: Xamarin.Forms.Dependency(typeof(TouchMediaPicker))] namespace Drecogrizer.iOS.Media { /// <summary> /// Implementation for Media /// </summary> public class TouchMediaPicker : IMedia { /// <summary> /// image type /// </summary> public const string TypeImage = "public.image"; private UIImagePickerControllerDelegate pickerDelegate; private UIPopoverController popover; /// <summary> /// Implementation /// </summary> public TouchMediaPicker() { IsCameraAvailable = UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera); var availableCameraMedia = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.Camera) ?? new string[0]; var avalaibleLibraryMedia = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary) ?? new string[0]; IsPickPhotoSupported = availableCameraMedia.Concat(avalaibleLibraryMedia).Any(type => type == TypeImage); IsTakePhotoSupported = IsPickPhotoSupported; } /// <inheritdoc /> public bool IsTakePhotoSupported { get; } /// <inheritdoc /> public bool IsCameraAvailable { get; } /// <inheritdoc /> public bool IsPickPhotoSupported { get; } /// <summary> /// Picks a photo from the default gallery /// </summary> /// <returns>Media file or null if canceled</returns> public Task<MediaFile> PickPhotoAsync() { if (!IsPickPhotoSupported) throw new NotSupportedException(); return GetMediaAsync(UIImagePickerControllerSourceType.PhotoLibrary, TypeImage); } /// <summary> /// Take a photo async with specified options /// </summary> /// <param name="options">Camera Media Options</param> /// <returns>Media file of photo or null if canceled</returns> public Task<MediaFile> TakePhotoAsync(CameraCameraMediaOptions options) { if (!IsTakePhotoSupported) throw new NotSupportedException(); if (!IsCameraAvailable) throw new NotSupportedException(); VerifyCameraOptions(options); return GetMediaAsync(UIImagePickerControllerSourceType.Camera, TypeImage, options); } public void Dispose() { popover.Dispose(); pickerDelegate.Dispose(); } private void VerifyOptions(CameraMediaOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (options.Directory != null && Path.IsPathRooted(options.Directory)) { throw new ArgumentException("options.Directory must be a relative path", nameof(options)); } } private void VerifyCameraOptions(CameraCameraMediaOptions options) { VerifyOptions(options); if (!Enum.IsDefined(typeof(DeviceCamera), options.DefaultDeviceCamera)) { throw new ArgumentException("options.Camera is not a member of DeviceCamera"); } } private static MediaPickerController SetupController(MediaPickerDelegate mpDelegate, UIImagePickerControllerSourceType sourceType, string mediaType, CameraCameraMediaOptions options) { var picker = new MediaPickerController(mpDelegate) { MediaTypes = new[] {mediaType}, SourceType = sourceType }; if (sourceType == UIImagePickerControllerSourceType.Camera) { picker.CameraDevice = GetUICameraDevice(options.DefaultDeviceCamera); picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo; } return picker; } private Task<MediaFile> GetMediaAsync(UIImagePickerControllerSourceType sourceType, string mediaType, CameraCameraMediaOptions options=null) { var viewController = GetViewController(); while (viewController.PresentedViewController != null) { viewController = viewController.PresentedViewController; } var ndelegate = new MediaPickerDelegate(viewController, sourceType, options); var od = Interlocked.CompareExchange(ref pickerDelegate, ndelegate, null); if (od != null) { throw new InvalidOperationException("Only one operation can be active at at time"); } var picker = SetupController(ndelegate, sourceType, mediaType, options); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && sourceType == UIImagePickerControllerSourceType.PhotoLibrary) { ndelegate.Popover = new UIPopoverController(picker) { Delegate = new MediaPickerPopoverDelegate(ndelegate, picker) }; ndelegate.DisplayPopover(); } else viewController.PresentViewController(picker, true, null); return ndelegate.Task.ContinueWith(t => { if (popover != null) { popover.Dispose(); popover = null; } Interlocked.Exchange(ref pickerDelegate, null); return t; }).Unwrap(); } private static UIViewController GetViewController() { var window = UIApplication.SharedApplication.KeyWindow; if (window == null) { throw new InvalidOperationException("There's no current active window"); } var viewController = window.RootViewController; if (viewController == null) { window = UIApplication.SharedApplication.Windows.OrderByDescending(w => w.WindowLevel) .FirstOrDefault(w => w.RootViewController != null); if (window == null) { throw new InvalidOperationException("Could not find current view controller"); } viewController = window.RootViewController; } return viewController; } private static UIImagePickerControllerCameraDevice GetUICameraDevice(DeviceCamera device) { switch (device) { case DeviceCamera.Front: return UIImagePickerControllerCameraDevice.Front; case DeviceCamera.Rear: return UIImagePickerControllerCameraDevice.Rear; default: throw new NotSupportedException(); } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H02_Continent (editable child object).<br/> /// This is a generated base class of <see cref="H02_Continent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="H03_SubContinentObjects"/> of type <see cref="H03_SubContinentColl"/> (1:M relation to <see cref="H04_SubContinent"/>)<br/> /// This class is an item of <see cref="H01_ContinentColl"/> collection. /// </remarks> [Serializable] public partial class H02_Continent : BusinessBase<H02_Continent> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID"); /// <summary> /// Gets the Continents ID. /// </summary> /// <value>The Continents ID.</value> public int Continent_ID { get { return GetProperty(Continent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Continent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name"); /// <summary> /// Gets or sets the Continents Name. /// </summary> /// <value>The Continents Name.</value> public string Continent_Name { get { return GetProperty(Continent_NameProperty); } set { SetProperty(Continent_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="H03_Continent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<H03_Continent_Child> H03_Continent_SingleObjectProperty = RegisterProperty<H03_Continent_Child>(p => p.H03_Continent_SingleObject, "H03 Continent Single Object", RelationshipTypes.Child); /// <summary> /// Gets the H03 Continent Single Object ("self load" child property). /// </summary> /// <value>The H03 Continent Single Object.</value> public H03_Continent_Child H03_Continent_SingleObject { get { return GetProperty(H03_Continent_SingleObjectProperty); } private set { LoadProperty(H03_Continent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="H03_Continent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<H03_Continent_ReChild> H03_Continent_ASingleObjectProperty = RegisterProperty<H03_Continent_ReChild>(p => p.H03_Continent_ASingleObject, "H03 Continent ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the H03 Continent ASingle Object ("self load" child property). /// </summary> /// <value>The H03 Continent ASingle Object.</value> public H03_Continent_ReChild H03_Continent_ASingleObject { get { return GetProperty(H03_Continent_ASingleObjectProperty); } private set { LoadProperty(H03_Continent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="H03_SubContinentObjects"/> property. /// </summary> public static readonly PropertyInfo<H03_SubContinentColl> H03_SubContinentObjectsProperty = RegisterProperty<H03_SubContinentColl>(p => p.H03_SubContinentObjects, "H03 SubContinent Objects", RelationshipTypes.Child); /// <summary> /// Gets the H03 Sub Continent Objects ("self load" child property). /// </summary> /// <value>The H03 Sub Continent Objects.</value> public H03_SubContinentColl H03_SubContinentObjects { get { return GetProperty(H03_SubContinentObjectsProperty); } private set { LoadProperty(H03_SubContinentObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="H02_Continent"/> object. /// </summary> /// <returns>A reference to the created <see cref="H02_Continent"/> object.</returns> internal static H02_Continent NewH02_Continent() { return DataPortal.CreateChild<H02_Continent>(); } /// <summary> /// Factory method. Loads a <see cref="H02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="H02_Continent"/> object.</returns> internal static H02_Continent GetH02_Continent(SafeDataReader dr) { H02_Continent obj = new H02_Continent(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H02_Continent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public H02_Continent() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="H02_Continent"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(H03_Continent_SingleObjectProperty, DataPortal.CreateChild<H03_Continent_Child>()); LoadProperty(H03_Continent_ASingleObjectProperty, DataPortal.CreateChild<H03_Continent_ReChild>()); LoadProperty(H03_SubContinentObjectsProperty, DataPortal.CreateChild<H03_SubContinentColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="H02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID")); LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> internal void FetchChildren() { LoadProperty(H03_Continent_SingleObjectProperty, H03_Continent_Child.GetH03_Continent_Child(Continent_ID)); LoadProperty(H03_Continent_ASingleObjectProperty, H03_Continent_ReChild.GetH03_Continent_ReChild(Continent_ID)); LoadProperty(H03_SubContinentObjectsProperty, H03_SubContinentColl.GetH03_SubContinentColl(Continent_ID)); } /// <summary> /// Inserts a new <see cref="H02_Continent"/> object in the database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddH02_Continent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(Continent_IDProperty, (int) cmd.Parameters["@Continent_ID"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="H02_Continent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateH02_Continent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="H02_Continent"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteH02_Continent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(H03_Continent_SingleObjectProperty, DataPortal.CreateChild<H03_Continent_Child>()); LoadProperty(H03_Continent_ASingleObjectProperty, DataPortal.CreateChild<H03_Continent_ReChild>()); LoadProperty(H03_SubContinentObjectsProperty, DataPortal.CreateChild<H03_SubContinentColl>()); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.AzureStack.Management.Commerce.Admin { using Microsoft.AzureStack; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Commerce; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Commerce Admin Client /// </summary> public partial class CommerceAdminClient : ServiceClient<CommerceAdminClient>, ICommerceAdminClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Subscription credentials which uniquely identify Microsoft Azure /// subscription.The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the ISubscriberUsageAggregatesOperations. /// </summary> public virtual ISubscriberUsageAggregatesOperations SubscriberUsageAggregates { get; private set; } /// <summary> /// Initializes a new instance of the CommerceAdminClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected CommerceAdminClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the CommerceAdminClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected CommerceAdminClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the CommerceAdminClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected CommerceAdminClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the CommerceAdminClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected CommerceAdminClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the CommerceAdminClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CommerceAdminClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the CommerceAdminClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CommerceAdminClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the CommerceAdminClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CommerceAdminClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the CommerceAdminClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CommerceAdminClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { SubscriberUsageAggregates = new SubscriberUsageAggregatesOperations(this); BaseUri = new System.Uri("https://management.local.azurestack.external"); ApiVersion = "2015-06-01-preview"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using Signum.Engine; using Signum.Engine.Basics; using Signum.Engine.DynamicQuery; using Signum.Engine.Maps; using Signum.Engine.Operations; using Signum.Entities; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Signum.Test.Environment { public static class MusicLogic { [AutoExpressionField] public static IQueryable<AlbumEntity> Albums(this IAuthorEntity e) => As.Expression(() => Database.Query<AlbumEntity>().Where(a => a.Author == e)); public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Include<AlbumEntity>() .WithExpressionFrom((IAuthorEntity au) => au.Albums()) .WithQuery(() => a => new { Entity = a, a.Id, a.Name, a.Author, a.Label, a.Year }); AlbumGraph.Register(); sb.Include<NoteWithDateEntity>() .WithSave(NoteWithDateOperation.Save) .WithQuery(() => a => new { Entity = a, a.Id, a.Text, a.Target, a.CreationTime, }); sb.Include<ConfigEntity>() .WithSave(ConfigOperation.Save); MinimumExtensions.IncludeFunction(sb.Schema.Assets); sb.Include<ArtistEntity>() .WithSave(ArtistOperation.Save) .WithVirtualMList(a => a.Nominations, n => (Lite<ArtistEntity>)n.Author) .WithQuery(() => a => new { Entity = a, a.Id, a.Name, a.IsMale, a.Sex, a.Dead, a.LastAward, }); new Graph<ArtistEntity>.Execute(ArtistOperation.AssignPersonalAward) { CanExecute = a => a.LastAward != null ? "Artist already has an award" : null, Execute = (a, para) => a.LastAward = new PersonalAwardEntity() { Category = "Best Artist", Year = DateTime.Now.Year, Result = AwardResult.Won }.Execute(AwardOperation.Save) }.Register(); sb.Include<BandEntity>() .WithQuery(() => a => new { Entity = a, a.Id, a.Name, a.LastAward, }); new Graph<BandEntity>.Execute(BandOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (b, _) => { using (OperationLogic.AllowSave<ArtistEntity>()) { b.Save(); } } }.Register(); sb.Include<LabelEntity>() .WithSave(LabelOperation.Save) .WithQuery(() => a => new { Entity = a, a.Id, a.Name, }); sb.Include<FolderEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Name }); RegisterAwards(sb); QueryLogic.Queries.Register(typeof(IAuthorEntity), () => DynamicQueryCore.Manual(async (request, description, cancellationToken) => { var one = await (from a in Database.Query<ArtistEntity>() select new { Entity = (IAuthorEntity)a, a.Id, Type = "Artist", a.Name, Lonely = a.Lonely(), LastAward = a.LastAward }) .ToDQueryable(description) .AllQueryOperationsAsync(request, cancellationToken); var two = await (from a in Database.Query<BandEntity>() select new { Entity = (IAuthorEntity)a, a.Id, Type = "Band", a.Name, Lonely = a.Lonely(), LastAward = a.LastAward }) .ToDQueryable(description) .AllQueryOperationsAsync(request, cancellationToken); return one.Concat(two).OrderBy(request.Orders).TryPaginate(request.Pagination); }) .Column(a => a.LastAward, cl => cl.Implementations = Implementations.ByAll) .ColumnProperyRoutes(a => a.Id, PropertyRoute.Construct((ArtistEntity a) => a.Id), PropertyRoute.Construct((BandEntity a) => a.Id)), entityImplementations: Implementations.By(typeof(ArtistEntity), typeof(BandEntity))); Validator.PropertyValidator((NoteWithDateEntity n) => n.Text) .IsApplicableValidator<NotNullValidatorAttribute>(n => Corruption.Strict); } } private static void RegisterAwards(SchemaBuilder sb) { new Graph<AwardEntity>.Execute(AwardOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (a, _) => { } }.Register(); sb.Include<AmericanMusicAwardEntity>() .WithQuery(() => a => new { Entity = a, a.Id, a.Year, a.Category, a.Result, }); sb.Include<GrammyAwardEntity>() .WithQuery(() => a => new { Entity = a, a.Id, a.Year, a.Category, a.Result }); sb.Include<PersonalAwardEntity>() .WithQuery(() => a => new { Entity = a, a.Id, a.Year, a.Category, a.Result }); sb.Include<AwardNominationEntity>() .WithQuery(() => a => new { Entity = a, a.Id, a.Award, a.Author }); } } public class AlbumGraph : Graph<AlbumEntity, AlbumState> { public static void Register() { GetState = f => f.State; new Execute(AlbumOperation.Save) { FromStates = { AlbumState.New }, ToStates = { AlbumState.Saved }, CanBeNew = true, CanBeModified = true, Execute = (album, _) => { album.State = AlbumState.Saved; album.Save(); }, }.Register(); new Execute(AlbumOperation.Modify) { FromStates = { AlbumState.Saved }, ToStates = { AlbumState.Saved }, CanBeModified = true, Execute = (album, _) => { }, }.Register(); new ConstructFrom<BandEntity>(AlbumOperation.CreateAlbumFromBand) { ToStates = { AlbumState.Saved }, Construct = (BandEntity band, object?[]? args) => new AlbumEntity { Author = band, Name = args.GetArg<string>(), Year = args.GetArg<int>(), State = AlbumState.Saved, Label = args.GetArg<LabelEntity>() }.Save() }.Register(); new ConstructFrom<AlbumEntity>(AlbumOperation.Clone) { ToStates = { AlbumState.New }, Construct = (g, args) => { return new AlbumEntity { Author = g.Author, Label = g.Label, BonusTrack = new SongEmbedded { Name = "Clone bonus track" } }; } }.Register(); new ConstructFromMany<AlbumEntity>(AlbumOperation.CreateGreatestHitsAlbum) { ToStates = { AlbumState.New }, Construct = (albumLites, _) => { List<AlbumEntity> albums = albumLites.Select(a => a.RetrieveAndRemember()).ToList(); if (albums.Select(a => a.Author).Distinct().Count() > 1) throw new ArgumentException("All album authors must be the same in order to create a Greatest Hits Album"); return new AlbumEntity() { Author = albums.FirstEx().Author, Year = DateTime.Now.Year, Songs = albums.SelectMany(a => a.Songs).ToMList() }; } }.Register(); new ConstructFromMany<AlbumEntity>(AlbumOperation.CreateEmptyGreatestHitsAlbum) { ToStates = { AlbumState.New }, Construct = (albumLites, _) => { List<AlbumEntity> albums = albumLites.Select(a => a.RetrieveAndRemember()).ToList(); if (albums.Select(a => a.Author).Distinct().Count() > 1) throw new ArgumentException("All album authors must be the same in order to create a Greatest Hits Album"); return new AlbumEntity() { Author = albums.FirstEx().Author, Year = DateTime.Now.Year, }; } }.Register(); new Delete(AlbumOperation.Delete) { FromStates = { AlbumState.Saved }, Delete = (album, _) => album.Delete() }.Register(); } } }
// 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, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using Microsoft.VisualStudio.TestTools.UnitTesting; using TestRunnerInterop; namespace DebuggerUITestsRunner { public abstract class DebugProjectUITests { #region UI test boilerplate public VsTestInvoker _vs => new VsTestInvoker( VsTestContext.Instance, // Remote container (DLL) name "Microsoft.PythonTools.Tests.DebuggerUITests", // Remote class name $"DebuggerUITests.{nameof(DebugProjectUITests)}" ); public TestContext TestContext { get; set; } [TestInitialize] public void TestInitialize() => VsTestContext.Instance.TestInitialize(TestContext.DeploymentDirectory); [TestCleanup] public void TestCleanup() => VsTestContext.Instance.TestCleanup(); [ClassCleanup] public static void ClassCleanup() => VsTestContext.Instance.Dispose(); #endregion protected abstract bool UseVsCodeDebugger { get; } protected abstract string Interpreter { get; } [TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)] [TestCategory("Installed")] public void DebugPythonProject() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.DebugPythonProject), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void DebugPythonProjectSubFolderStartupFileSysPath() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.DebugPythonProjectSubFolderStartupFileSysPath), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void DebugPythonProjectWithClearingPythonPath() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.DebugPythonProjectWithClearingPythonPath), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void DebugPythonProjectWithoutClearingPythonPath() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.DebugPythonProjectWithoutClearingPythonPath), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void DebugPythonCustomInterpreter() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.DebugPythonCustomInterpreter), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void DebugPythonCustomInterpreterMissing() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.DebugPythonCustomInterpreterMissing), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void PendingBreakPointLocation() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.PendingBreakPointLocation), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P2_FAILING_UI_TEST)] [TestCategory("Installed")] public void BoundBreakpoint() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.BoundBreakpoint), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void Step() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.Step), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void Step3() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.Step3), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void Step5() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.Step5), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void StepMultiProc() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.StepMultiProc), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P2)] [TestCategory("Installed")] public void SetNextLine() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.SetNextLine), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)] [TestCategory("Installed")] public void TerminateProcess() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.TerminateProcess), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P2)] [TestCategory("Installed")] public void EnumModules() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.EnumModules), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P2)] [TestCategory("Installed")] public void MainThread() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.MainThread), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P2_FAILING_UI_TEST)] [TestCategory("Installed")] public void ExpressionEvaluation() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.ExpressionEvaluation), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void SimpleException() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.SimpleException), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void SimpleException2() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.SimpleException2), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void SimpleExceptionUnhandled() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.SimpleExceptionUnhandled), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void ExceptionInImportLibNotReported() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.ExceptionInImportLibNotReported), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void Breakpoints() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.Breakpoints), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P2)] [TestCategory("Installed")] public void BreakpointsDisable() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.BreakpointsDisable), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P2)] [TestCategory("Installed")] public void BreakpointsDisableReenable() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.BreakpointsDisableReenable), UseVsCodeDebugger, Interpreter); } [Ignore] // Not reliable enough right now [TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)] [TestCategory("Installed")] public void LaunchWithErrorsDontRun() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.LaunchWithErrorsDontRun), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P2)] [TestCategory("Installed")] public void StartWithDebuggingNoProject() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.StartWithDebuggingNoProject), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void StartWithoutDebuggingNoProject() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.StartWithoutDebuggingNoProject), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void StartWithDebuggingNotInProject() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.StartWithDebuggingNotInProject), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)] [TestCategory("Installed")] public void StartWithoutDebuggingNotInProject() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.StartWithoutDebuggingNotInProject), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void StartWithDebuggingInProject() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.StartWithDebuggingInProject), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P2)] [TestCategory("Installed")] public void StartWithDebuggingSubfolderInProject() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.StartWithDebuggingSubfolderInProject), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)] [TestCategory("Installed")] public void StartWithoutDebuggingInProject() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.StartWithoutDebuggingInProject), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void StartWithDebuggingNoScript() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.StartWithDebuggingNoScript), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void StartWithoutDebuggingNoScript() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.StartWithoutDebuggingNoScript), UseVsCodeDebugger, Interpreter); } [TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)] [TestCategory("Installed")] public void WebProjectLauncherNoStartupFile() { _vs.RunTest(nameof(DebuggerUITests.DebugProjectUITests.WebProjectLauncherNoStartupFile), UseVsCodeDebugger, Interpreter); } } [TestClass] public class DebugProjectUITestsLegacyPtvsd : DebugProjectUITests { protected override bool UseVsCodeDebugger => false; protected override string Interpreter => ""; // Use the existing global default } public abstract class DebugProjectUITestsDebugPy : DebugProjectUITests { protected override bool UseVsCodeDebugger => true; } [TestClass] public class DebugProjectUITestsDebugPy27 : DebugProjectUITestsDebugPy { protected override string Interpreter => "Python27|Python27_x64"; } [TestClass] public class DebugProjectUITestsDebugPy37 : DebugProjectUITestsDebugPy { protected override string Interpreter => "Python37|Python37_x64"; } }
// // XmlReader.cs // // Authors: // Jason Diamond ([email protected]) // Gonzalo Paniagua Javier ([email protected]) // Atsushi Enomoto ([email protected]) // // (C) 2001, 2002 Jason Diamond http://injektilo.org/ // (c) 2002 Ximian, Inc. (http://www.ximian.com) // (C) 2003 Atsushi Enomoto // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Text; using Mono.System.Xml.Schema; // only required for NET_2_0 (SchemaInfo) using Mono.System.Xml.Serialization; // only required for NET_2_0 (SchemaInfo) using Mono.Xml.Schema; // only required for NET_2_0 using Mono.Xml; // only required for NET_2_0 #if NET_4_5 using System.Threading; using System.Threading.Tasks; #endif namespace Mono.System.Xml { #if NET_2_0 public abstract class XmlReader : IDisposable #else public abstract class XmlReader #endif { private StringBuilder readStringBuffer; private XmlReaderBinarySupport binary; #if NET_2_0 private XmlReaderSettings settings; #endif #region Constructor protected XmlReader () { } #endregion #region Properties public abstract int AttributeCount { get; } public abstract string BaseURI { get; } internal XmlReaderBinarySupport Binary { get { return binary; } } internal XmlReaderBinarySupport.CharGetter BinaryCharGetter { get { return binary != null ? binary.Getter : null; } set { if (binary == null) binary = new XmlReaderBinarySupport (this); binary.Getter = value; } } #if NET_2_0 // To enable it internally in sys.xml, just insert these // two lines into Read(): // // #if NET_2_0 // if (Binary != null) // Binary.Reset (); // #endif // public virtual bool CanReadBinaryContent { get { return false; } } public virtual bool CanReadValueChunk { get { return false; } } #else internal virtual bool CanReadBinaryContent { get { return false; } } internal virtual bool CanReadValueChunk { get { return false; } } #endif public virtual bool CanResolveEntity { get { return false; } } public abstract int Depth { get; } public abstract bool EOF { get; } public virtual bool HasAttributes { get { return AttributeCount > 0; } } #if NET_4_0 public virtual bool HasValue { get { switch (NodeType) { case XmlNodeType.Attribute: case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.XmlDeclaration: return true; } return false; } } #else public abstract bool HasValue { get; } #endif public abstract bool IsEmptyElement { get; } #if NET_2_0 public virtual bool IsDefault { get { return false; } } public virtual string this [int i] { get { return GetAttribute (i); } } public virtual string this [string name] { get { return GetAttribute (name); } } public virtual string this [string name, string namespaceURI] { get { return GetAttribute (name, namespaceURI); } } #else public abstract bool IsDefault { get; } public abstract string this [int i] { get; } public abstract string this [string name] { get; } public abstract string this [string localName, string namespaceName] { get; } #endif public abstract string LocalName { get; } #if NET_2_0 public virtual string Name { get { return Prefix.Length > 0 ? String.Concat (Prefix, ":", LocalName) : LocalName; } } #else public abstract string Name { get; } #endif public abstract string NamespaceURI { get; } public abstract XmlNameTable NameTable { get; } public abstract XmlNodeType NodeType { get; } public abstract string Prefix { get; } #if NET_2_0 public virtual char QuoteChar { get { return '\"'; } } #else public abstract char QuoteChar { get; } #endif public abstract ReadState ReadState { get; } #if NET_2_0 public virtual IXmlSchemaInfo SchemaInfo { get { return null; } } public virtual XmlReaderSettings Settings { get { return settings; } } #endif public abstract string Value { get; } #if NET_2_0 public virtual string XmlLang { get { return String.Empty; } } public virtual XmlSpace XmlSpace { get { return XmlSpace.None; } } #else public abstract string XmlLang { get; } public abstract XmlSpace XmlSpace { get; } #endif #endregion #region Methods #if NET_4_5 public virtual void Close () { if (asyncRunning) throw new InvalidOperationException ("An asynchronous operation is already in progress."); } #else public abstract void Close (); #endif #if NET_2_0 private static XmlNameTable PopulateNameTable ( XmlReaderSettings settings) { XmlNameTable nameTable = settings.NameTable; if (nameTable == null) nameTable = new NameTable (); return nameTable; } private static XmlParserContext PopulateParserContext ( XmlReaderSettings settings, string baseUri) { XmlNameTable nt = PopulateNameTable (settings); return new XmlParserContext (nt, new XmlNamespaceManager (nt), null, null, null, null, baseUri, null, XmlSpace.None, null); } private static XmlNodeType GetNodeType ( XmlReaderSettings settings) { ConformanceLevel level = settings != null ? settings.ConformanceLevel : ConformanceLevel.Auto; return level == ConformanceLevel.Fragment ? XmlNodeType.Element : XmlNodeType.Document; } public static XmlReader Create (Stream input) { return Create (input, null); } public static XmlReader Create (string inputUri) { return Create (inputUri, null); } public static XmlReader Create (TextReader input) { return Create (input, null); } public static XmlReader Create (string inputUri, XmlReaderSettings settings) { return Create (inputUri, settings, null); } public static XmlReader Create (Stream input, XmlReaderSettings settings) { return Create (input, settings, String.Empty); } public static XmlReader Create (TextReader input, XmlReaderSettings settings) { return Create (input, settings, String.Empty); } static XmlReaderSettings PopulateSettings (XmlReaderSettings src) { XmlReaderSettings copy; if (src == null) copy = new XmlReaderSettings (); else copy = src.Clone (); #if NET_4_5 copy.SetReadOnly (); #endif return copy; } static XmlReaderSettings PopulateSettings (XmlReader reader, XmlReaderSettings src) { XmlReaderSettings copy; if (src == null) copy = new XmlReaderSettings (); else copy = src.Clone (); #if NET_4_5 if (reader.Settings != null) copy.Async = reader.Settings.Async; copy.SetReadOnly (); #endif return copy; } public static XmlReader Create (Stream input, XmlReaderSettings settings, string baseUri) { settings = PopulateSettings (settings); return Create (input, settings, PopulateParserContext (settings, baseUri)); } public static XmlReader Create (TextReader input, XmlReaderSettings settings, string baseUri) { settings = PopulateSettings (settings); return Create (input, settings, PopulateParserContext (settings, baseUri)); } public static XmlReader Create (XmlReader reader, XmlReaderSettings settings) { settings = PopulateSettings (reader, settings); XmlReader r = CreateFilteredXmlReader (reader, settings); r.settings = settings; return r; } public static XmlReader Create (string inputUri, XmlReaderSettings settings, XmlParserContext inputContext) { settings = PopulateSettings (settings); bool closeInputBak = settings.CloseInput; try { settings.CloseInput = true; // forced. See XmlReaderCommonTests.CreateFromUrlClose(). if (inputContext == null) inputContext = PopulateParserContext (settings, inputUri); XmlTextReader xtr = new XmlTextReader (false, settings.XmlResolver, inputUri, GetNodeType (settings), inputContext); XmlReader ret = CreateCustomizedTextReader (xtr, settings); return ret; } finally { settings.CloseInput = closeInputBak; } } public static XmlReader Create (Stream input, XmlReaderSettings settings, XmlParserContext inputContext) { settings = PopulateSettings (settings); if (inputContext == null) inputContext = PopulateParserContext (settings, String.Empty); return CreateCustomizedTextReader (new XmlTextReader (input, GetNodeType (settings), inputContext), settings); } public static XmlReader Create (TextReader input, XmlReaderSettings settings, XmlParserContext inputContext) { settings = PopulateSettings (settings); if (inputContext == null) inputContext = PopulateParserContext (settings, String.Empty); return CreateCustomizedTextReader (new XmlTextReader (inputContext.BaseURI, input, GetNodeType (settings), inputContext), settings); } private static XmlReader CreateCustomizedTextReader (XmlTextReader reader, XmlReaderSettings settings) { reader.XmlResolver = settings.XmlResolver; // Normalization is set true by default. reader.Normalization = true; reader.EntityHandling = EntityHandling.ExpandEntities; if (settings.ProhibitDtd) reader.ProhibitDtd = true; if (!settings.CheckCharacters) reader.CharacterChecking = false; // I guess it might be changed in 2.0 RTM to set true // as default, or just disappear. It goes against // XmlTextReader's default usage and users will have // to close input manually (that's annoying). Moreover, // MS XmlTextReader consumes text input more than // actually read and users can acquire those extra // consumption by GetRemainder() that returns different // TextReader. reader.CloseInput = settings.CloseInput; // I would like to support it in detail later; // MSDN description looks source of confusion. We don't // need examples, but precise list of how it works. reader.Conformance = settings.ConformanceLevel; reader.AdjustLineInfoOffset (settings.LineNumberOffset, settings.LinePositionOffset); if (settings.NameTable != null) reader.SetNameTable (settings.NameTable); XmlReader r = CreateFilteredXmlReader (reader, settings); r.settings = settings; return r; } private static XmlReader CreateFilteredXmlReader (XmlReader reader, XmlReaderSettings settings) { ConformanceLevel conf = ConformanceLevel.Auto; if (reader is XmlTextReader) conf = ((XmlTextReader) reader).Conformance; else if (reader.Settings != null) conf = reader.Settings.ConformanceLevel; else conf = settings.ConformanceLevel; if (settings.ConformanceLevel != ConformanceLevel.Auto && conf != settings.ConformanceLevel) throw new InvalidOperationException (String.Format ("ConformanceLevel cannot be overwritten by a wrapping XmlReader. The source reader has {0}, while {1} is specified.", conf, settings.ConformanceLevel)); settings.ConformanceLevel = conf; reader = CreateValidatingXmlReader (reader, settings); if ( settings.IgnoreComments || settings.IgnoreProcessingInstructions || settings.IgnoreWhitespace) return new XmlFilterReader (reader, settings); else { reader.settings = settings; return reader; } } private static XmlReader CreateValidatingXmlReader (XmlReader reader, XmlReaderSettings settings) { XmlValidatingReader xvr = null; switch (settings.ValidationType) { // Auto and XDR are obsoleted in 2.0 and therefore ignored. default: return reader; case ValidationType.DTD: xvr = new XmlValidatingReader (reader); xvr.XmlResolver = settings.XmlResolver; xvr.ValidationType = ValidationType.DTD; break; case ValidationType.Schema: return new XmlSchemaValidatingReader (reader, settings); } // Actually I don't think they are treated in DTD validation though... if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessIdentityConstraints) == 0) throw new NotImplementedException (); //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessInlineSchema) != 0) // throw new NotImplementedException (); //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessSchemaLocation) != 0) // throw new NotImplementedException (); //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ReportValidationWarnings) == 0) // throw new NotImplementedException (); return xvr != null ? xvr : reader; } #if NET_4_0 public void Dispose () #else void IDisposable.Dispose() #endif { Dispose (false); } bool disposed = false; protected virtual void Dispose (bool disposing) { disposed = true; if (ReadState != ReadState.Closed) Close (); } #endif public abstract string GetAttribute (int i); public abstract string GetAttribute (string name); public abstract string GetAttribute (string name, string namespaceURI); public static bool IsName (string str) { return str != null && XmlChar.IsName (str); } public static bool IsNameToken (string str) { return str != null && XmlChar.IsNmToken (str); } public virtual bool IsStartElement () { return (MoveToContent () == XmlNodeType.Element); } public virtual bool IsStartElement (string name) { if (!IsStartElement ()) return false; return (Name == name); } public virtual bool IsStartElement (string localname, string ns) { if (!IsStartElement ()) return false; return (LocalName == localname && NamespaceURI == ns); } public abstract string LookupNamespace (string prefix); #if NET_2_0 public virtual void MoveToAttribute (int i) { if (i >= AttributeCount) throw new ArgumentOutOfRangeException (); MoveToFirstAttribute (); for (int a = 0; a < i; a++) MoveToNextAttribute (); } #else public abstract void MoveToAttribute (int i); #endif public abstract bool MoveToAttribute (string name); public abstract bool MoveToAttribute (string name, string ns); private bool IsContent (XmlNodeType nodeType) { /* MS doc says: * (non-white space text, CDATA, Element, EndElement, EntityReference, or EndEntity) */ switch (nodeType) { case XmlNodeType.Text: return true; case XmlNodeType.CDATA: return true; case XmlNodeType.Element: return true; case XmlNodeType.EndElement: return true; case XmlNodeType.EntityReference: return true; case XmlNodeType.EndEntity: return true; } return false; } public virtual XmlNodeType MoveToContent () { switch (ReadState) { case ReadState.Initial: case ReadState.Interactive: break; default: return NodeType; } if (NodeType == XmlNodeType.Attribute) MoveToElement (); do { if (IsContent (NodeType)) return NodeType; Read (); } while (!EOF); return XmlNodeType.None; } public abstract bool MoveToElement (); public abstract bool MoveToFirstAttribute (); public abstract bool MoveToNextAttribute (); public abstract bool Read (); public abstract bool ReadAttributeValue (); public virtual string ReadElementString () { if (MoveToContent () != XmlNodeType.Element) { string error = String.Format ("'{0}' is an invalid node type.", NodeType.ToString ()); throw XmlError (error); } string result = String.Empty; if (!IsEmptyElement) { Read (); result = ReadString (); if (NodeType != XmlNodeType.EndElement) { string error = String.Format ("'{0}' is an invalid node type.", NodeType.ToString ()); throw XmlError (error); } } Read (); return result; } public virtual string ReadElementString (string name) { if (MoveToContent () != XmlNodeType.Element) { string error = String.Format ("'{0}' is an invalid node type.", NodeType.ToString ()); throw XmlError (error); } if (name != Name) { string error = String.Format ("The {0} tag from namespace {1} is expected.", Name, NamespaceURI); throw XmlError (error); } string result = String.Empty; if (!IsEmptyElement) { Read (); result = ReadString (); if (NodeType != XmlNodeType.EndElement) { string error = String.Format ("'{0}' is an invalid node type.", NodeType.ToString ()); throw XmlError (error); } } Read (); return result; } public virtual string ReadElementString (string localname, string ns) { if (MoveToContent () != XmlNodeType.Element) { string error = String.Format ("'{0}' is an invalid node type.", NodeType.ToString ()); throw XmlError (error); } if (localname != LocalName || NamespaceURI != ns) { string error = String.Format ("The {0} tag from namespace {1} is expected.", LocalName, NamespaceURI); throw XmlError (error); } string result = String.Empty; if (!IsEmptyElement) { Read (); result = ReadString (); if (NodeType != XmlNodeType.EndElement) { string error = String.Format ("'{0}' is an invalid node type.", NodeType.ToString ()); throw XmlError (error); } } Read (); return result; } public virtual void ReadEndElement () { if (MoveToContent () != XmlNodeType.EndElement) { string error = String.Format ("'{0}' is an invalid node type.", NodeType.ToString ()); throw XmlError (error); } Read (); } public virtual string ReadInnerXml () { if (ReadState != ReadState.Interactive || NodeType == XmlNodeType.EndElement) return String.Empty; if (IsEmptyElement) { Read (); return String.Empty; } StringWriter sw = new StringWriter (); XmlTextWriter xtw = new XmlTextWriter (sw); if (NodeType == XmlNodeType.Element) { int startDepth = Depth; Read (); while (startDepth < Depth) { if (ReadState != ReadState.Interactive) throw XmlError ("Unexpected end of the XML reader."); xtw.WriteNode (this, false); } // reader is now end element, then proceed once more. Read (); } else xtw.WriteNode (this, false); return sw.ToString (); } public virtual string ReadOuterXml () { if (ReadState != ReadState.Interactive || NodeType == XmlNodeType.EndElement) return String.Empty; switch (NodeType) { case XmlNodeType.Element: case XmlNodeType.Attribute: StringWriter sw = new StringWriter (); XmlTextWriter xtw = new XmlTextWriter (sw); xtw.WriteNode (this, false); return sw.ToString (); default: Skip (); return String.Empty; } } public virtual void ReadStartElement () { if (MoveToContent () != XmlNodeType.Element) { string error = String.Format ("'{0}' is an invalid node type.", NodeType.ToString ()); throw XmlError (error); } Read (); } public virtual void ReadStartElement (string name) { if (MoveToContent () != XmlNodeType.Element) { string error = String.Format ("'{0}' is an invalid node type.", NodeType.ToString ()); throw XmlError (error); } if (name != Name) { string error = String.Format ("The {0} tag from namespace {1} is expected.", Name, NamespaceURI); throw XmlError (error); } Read (); } public virtual void ReadStartElement (string localname, string ns) { if (MoveToContent () != XmlNodeType.Element) { string error = String.Format ("'{0}' is an invalid node type.", NodeType.ToString ()); throw XmlError (error); } if (localname != LocalName || NamespaceURI != ns) { string error = String.Format ("Expecting {0} tag from namespace {1}, got {2} and {3} instead", localname, ns, LocalName, NamespaceURI); throw XmlError (error); } Read (); } public virtual string ReadString () { if (readStringBuffer == null) readStringBuffer = new StringBuilder (); readStringBuffer.Length = 0; MoveToElement (); switch (NodeType) { default: return String.Empty; case XmlNodeType.Element: if (IsEmptyElement) return String.Empty; do { Read (); switch (NodeType) { case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: readStringBuffer.Append (Value); continue; } break; } while (true); break; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: do { switch (NodeType) { case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: readStringBuffer.Append (Value); Read (); continue; } break; } while (true); break; } string ret = readStringBuffer.ToString (); readStringBuffer.Length = 0; return ret; } #if NET_2_0 public virtual Type ValueType { get { return typeof (string); } } public virtual bool ReadToDescendant (string name) { if (ReadState == ReadState.Initial) { MoveToContent (); if (IsStartElement (name)) return true; } if (NodeType != XmlNodeType.Element || IsEmptyElement) return false; int depth = Depth; for (Read (); depth < Depth; Read ()) if (NodeType == XmlNodeType.Element && name == Name) return true; return false; } public virtual bool ReadToDescendant (string localName, string namespaceURI) { if (ReadState == ReadState.Initial) { MoveToContent (); if (IsStartElement (localName, namespaceURI)) return true; } if (NodeType != XmlNodeType.Element || IsEmptyElement) return false; int depth = Depth; for (Read (); depth < Depth; Read ()) if (NodeType == XmlNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI) return true; return false; } public virtual bool ReadToFollowing (string name) { while (Read ()) if (NodeType == XmlNodeType.Element && name == Name) return true; return false; } public virtual bool ReadToFollowing (string localName, string namespaceURI) { while (Read ()) if (NodeType == XmlNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI) return true; return false; } public virtual bool ReadToNextSibling (string name) { if (ReadState != ReadState.Interactive) return false; MoveToElement (); int depth = Depth; Skip (); for (; !EOF && depth <= Depth; Skip ()) if (NodeType == XmlNodeType.Element && name == Name) return true; return false; } public virtual bool ReadToNextSibling (string localName, string namespaceURI) { if (ReadState != ReadState.Interactive) return false; int depth = Depth; Skip (); for (; !EOF && depth <= Depth; Skip ()) if (NodeType == XmlNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI) return true; return false; } public virtual XmlReader ReadSubtree () { if (NodeType != XmlNodeType.Element) throw new InvalidOperationException (String.Format ("ReadSubtree() can be invoked only when the reader is positioned on an element. Current node is {0}. {1}", NodeType, GetLocation ())); return new SubtreeXmlReader (this); } private string ReadContentString () { // The latter condition indicates that this XmlReader is on an attribute value // (HasAttributes is to indicate it is on attribute value). if (NodeType == XmlNodeType.Attribute || NodeType != XmlNodeType.Element && HasAttributes) return Value; return ReadContentString (true); } private string ReadContentString (bool isText) { if (isText) { switch (NodeType) { case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: case XmlNodeType.CDATA: break; case XmlNodeType.Element: throw new InvalidOperationException (String.Format ("Node type {0} is not supported in this operation.{1}", NodeType, GetLocation ())); default: return String.Empty; } } string value = String.Empty; do { switch (NodeType) { case XmlNodeType.Element: if (isText) return value; throw XmlError ("Child element is not expected in this operation."); case XmlNodeType.EndElement: return value; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: value += Value; break; } } while (Read ()); throw XmlError ("Unexpected end of document."); } string GetLocation () { IXmlLineInfo li = this as IXmlLineInfo; return li != null && li.HasLineInfo () ? String.Format (" {0} (line {1}, column {2})", BaseURI, li.LineNumber, li.LinePosition) : String.Empty; } [MonoTODO] public virtual object ReadElementContentAsObject () { return ReadElementContentAs (ValueType, null); } [MonoTODO] public virtual object ReadElementContentAsObject (string localName, string namespaceURI) { return ReadElementContentAs (ValueType, null, localName, namespaceURI); } [MonoTODO] public virtual object ReadContentAsObject () { return ReadContentAs (ValueType, null); } #if NET_4_5 public virtual DateTimeOffset ReadContentAsDateTimeOffset () { return XmlConvert.ToDateTimeOffset (ReadContentString ()); } #endif public virtual object ReadElementContentAs (Type returnType, IXmlNamespaceResolver namespaceResolver) { bool isEmpty = IsEmptyElement; ReadStartElement (); object obj = ValueAs (isEmpty ? String.Empty : ReadContentString (false), returnType, namespaceResolver, false); if (!isEmpty) ReadEndElement (); return obj; } public virtual object ReadElementContentAs (Type returnType, IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI) { bool isEmpty = IsEmptyElement; ReadStartElement (localName, namespaceURI); if (isEmpty) return ValueAs (String.Empty, returnType, namespaceResolver, false); object obj = ReadContentAs (returnType, namespaceResolver); ReadEndElement (); return obj; } public virtual object ReadContentAs (Type returnType, IXmlNamespaceResolver namespaceResolver) { return ValueAs (ReadContentString (), returnType, namespaceResolver, false); } private object ValueAs (string text, Type type, IXmlNamespaceResolver resolver, bool isArrayItem) { try { if (type == typeof (object)) return text; if (type.IsArray && !isArrayItem) { var elemType = type.GetElementType (); var sarr = text.Split ((string []) null, StringSplitOptions.RemoveEmptyEntries); var ret = Array.CreateInstance (elemType, sarr.Length); for (int i = 0; i < ret.Length; i++) ret.SetValue (ValueAs (sarr [i], elemType, resolver, true), i); return ret; } if (type == typeof (XmlQualifiedName)) { if (resolver != null) return XmlQualifiedName.Parse (text, resolver, true); else return XmlQualifiedName.Parse (text, this, true); } if (type == typeof (Uri)) return XmlConvert.ToUri (text); if (type == typeof (TimeSpan)) return XmlConvert.ToTimeSpan (text); if (type == typeof (DateTimeOffset)) return XmlConvert.ToDateTimeOffset (text); switch (Type.GetTypeCode (type)) { case TypeCode.Boolean: return XQueryConvert.StringToBoolean (text); case TypeCode.DateTime: return XQueryConvert.StringToDateTime (text); case TypeCode.Decimal: return XQueryConvert.StringToDecimal (text); case TypeCode.Double: return XQueryConvert.StringToDouble (text); case TypeCode.Int32: return XQueryConvert.StringToInt (text); case TypeCode.Int64: return XQueryConvert.StringToInteger (text); case TypeCode.Single: return XQueryConvert.StringToFloat (text); case TypeCode.String: return text; } } catch (Exception ex) { throw XmlError (String.Format ("Current text value '{0}' is not acceptable for specified type '{1}'. {2}", text, type, ex != null ? ex.Message : String.Empty), ex); } throw new ArgumentException (String.Format ("Specified type '{0}' is not supported.", type)); } public virtual bool ReadElementContentAsBoolean () { try { return XQueryConvert.StringToBoolean (ReadElementContentAsString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual DateTime ReadElementContentAsDateTime () { try { return XQueryConvert.StringToDateTime (ReadElementContentAsString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual decimal ReadElementContentAsDecimal () { try { return XQueryConvert.StringToDecimal (ReadElementContentAsString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual double ReadElementContentAsDouble () { try { return XQueryConvert.StringToDouble (ReadElementContentAsString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual float ReadElementContentAsFloat () { try { return XQueryConvert.StringToFloat (ReadElementContentAsString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual int ReadElementContentAsInt () { try { return XQueryConvert.StringToInt (ReadElementContentAsString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual long ReadElementContentAsLong () { try { return XQueryConvert.StringToInteger (ReadElementContentAsString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual string ReadElementContentAsString () { bool isEmpty = IsEmptyElement; // unlike ReadStartElement() it rejects non-content nodes (this check is done before MoveToContent()) if (NodeType != XmlNodeType.Element) throw new InvalidOperationException (String.Format ("'{0}' is an element node.", NodeType)); ReadStartElement (); if (isEmpty) return String.Empty; string s = ReadContentString (false); ReadEndElement (); return s; } public virtual bool ReadElementContentAsBoolean (string localName, string namespaceURI) { try { return XQueryConvert.StringToBoolean (ReadElementContentAsString (localName, namespaceURI)); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual DateTime ReadElementContentAsDateTime (string localName, string namespaceURI) { try { return XQueryConvert.StringToDateTime (ReadElementContentAsString (localName, namespaceURI)); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual decimal ReadElementContentAsDecimal (string localName, string namespaceURI) { try { return XQueryConvert.StringToDecimal (ReadElementContentAsString (localName, namespaceURI)); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual double ReadElementContentAsDouble (string localName, string namespaceURI) { try { return XQueryConvert.StringToDouble (ReadElementContentAsString (localName, namespaceURI)); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual float ReadElementContentAsFloat (string localName, string namespaceURI) { try { return XQueryConvert.StringToFloat (ReadElementContentAsString (localName, namespaceURI)); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual int ReadElementContentAsInt (string localName, string namespaceURI) { try { return XQueryConvert.StringToInt (ReadElementContentAsString (localName, namespaceURI)); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual long ReadElementContentAsLong (string localName, string namespaceURI) { try { return XQueryConvert.StringToInteger (ReadElementContentAsString (localName, namespaceURI)); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual string ReadElementContentAsString (string localName, string namespaceURI) { bool isEmpty = IsEmptyElement; // unlike ReadStartElement() it rejects non-content nodes (this check is done before MoveToContent()) if (NodeType != XmlNodeType.Element) throw new InvalidOperationException (String.Format ("'{0}' is an element node.", NodeType)); ReadStartElement (localName, namespaceURI); if (isEmpty) return String.Empty; string s = ReadContentString (false); ReadEndElement (); return s; } public virtual bool ReadContentAsBoolean () { try { return XQueryConvert.StringToBoolean (ReadContentString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual DateTime ReadContentAsDateTime () { try { return XQueryConvert.StringToDateTime (ReadContentString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual decimal ReadContentAsDecimal () { try { return XQueryConvert.StringToDecimal (ReadContentString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual double ReadContentAsDouble () { try { return XQueryConvert.StringToDouble (ReadContentString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual float ReadContentAsFloat () { try { return XQueryConvert.StringToFloat (ReadContentString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual int ReadContentAsInt () { try { return XQueryConvert.StringToInt (ReadContentString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual long ReadContentAsLong () { try { return XQueryConvert.StringToInteger (ReadContentString ()); } catch (FormatException ex) { throw XmlError ("Typed value is invalid.", ex); } } public virtual string ReadContentAsString () { return ReadContentString (); } public virtual int ReadContentAsBase64 ( byte [] buffer, int index, int count) { CheckSupport (); return binary.ReadContentAsBase64 ( buffer, index, count); } public virtual int ReadContentAsBinHex ( byte [] buffer, int index, int count) { CheckSupport (); return binary.ReadContentAsBinHex ( buffer, index, count); } public virtual int ReadElementContentAsBase64 ( byte [] buffer, int index, int count) { CheckSupport (); return binary.ReadElementContentAsBase64 ( buffer, index, count); } public virtual int ReadElementContentAsBinHex ( byte [] buffer, int index, int count) { CheckSupport (); return binary.ReadElementContentAsBinHex ( buffer, index, count); } private void CheckSupport () { // Default implementation expects both. if (!CanReadBinaryContent || !CanReadValueChunk) throw new NotSupportedException (); if (binary == null) binary = new XmlReaderBinarySupport (this); } #endif public virtual int ReadValueChunk (char [] buffer, int index, int count) { if (!CanReadValueChunk) throw new NotSupportedException (); if (binary == null) binary = new XmlReaderBinarySupport (this); return binary.ReadValueChunk (buffer, index, count); } public abstract void ResolveEntity (); public virtual void Skip () { if (ReadState != ReadState.Interactive) return; MoveToElement (); if (NodeType != XmlNodeType.Element || IsEmptyElement) { Read (); return; } int depth = Depth; while (Read () && depth < Depth) ; if (NodeType == XmlNodeType.EndElement) Read (); } private XmlException XmlError (string message) { return new XmlException (this as IXmlLineInfo, BaseURI, message); } #if NET_2_0 private XmlException XmlError (string message, Exception innerException) { return new XmlException (this as IXmlLineInfo, BaseURI, message); } #endif #endregion #if NET_4_5 #region .NET 4.5 Async Methods bool asyncRunning; bool asyncError; void StartAsync () { if (disposed) throw new ObjectDisposedException ("element disposed"); if (!settings.Async) throw new InvalidOperationException ("Set XmlReaderSettings.Async to true if you want to use Async Methods."); lock (this) { if (asyncRunning) { asyncError = true; throw new InvalidOperationException ("An asynchronous operation is already in progress."); } asyncRunning = true; } } void EndAsync () { if (asyncError) { throw new InvalidOperationException ("Noticed an async error in an other thread!"); } asyncRunning = false; } public virtual Task<bool> ReadAsync () { StartAsync (); return Task.Run (() => { try { return Read (); } finally { EndAsync (); } }); } public virtual Task<string> GetValueAsync () { StartAsync (); return Task.Run (() => { try { return Value; } finally { EndAsync (); } }); } public virtual Task<string> ReadInnerXmlAsync () { StartAsync (); return Task.Run (() => { try { return ReadInnerXml (); } finally { EndAsync (); } }); } public virtual Task<string> ReadOuterXmlAsync () { StartAsync (); return Task.Run (() => { try { return ReadOuterXml (); } finally { EndAsync (); } }); } public virtual Task<string> ReadContentAsStringAsync () { StartAsync (); return Task.Run (() => { try { return ReadContentAsString (); } finally { EndAsync (); } }); } public virtual Task<int> ReadContentAsBase64Async (byte[] buffer, int index, int count) { StartAsync (); return Task.Run (() => { try { return ReadContentAsBase64 (buffer, index, count); } finally { EndAsync (); } }); } public virtual Task<int> ReadContentAsBinHexAsync (byte[] buffer, int index, int count) { StartAsync (); return Task.Run (() => { try { return ReadContentAsBinHex (buffer, index, count); } finally { EndAsync (); } }); } public virtual Task<int> ReadElementContentAsBase64Async (byte[] buffer, int index, int count) { StartAsync (); return Task.Run (() => { try { return ReadElementContentAsBase64 (buffer, index, count); } finally { EndAsync (); } }); } public virtual Task<int> ReadElementContentAsBinHexAsync (byte[] buffer, int index, int count) { StartAsync (); return Task.Run (() => { try { return ReadElementContentAsBinHex (buffer, index, count); } finally { EndAsync (); } }); } public virtual Task<int> ReadValueChunkAsync (char[] buffer, int index, int count) { StartAsync (); return Task.Run (() => { try { return ReadValueChunk (buffer, index, count); } finally { EndAsync (); } }); } public virtual Task<object> ReadContentAsAsync (Type returnType, IXmlNamespaceResolver namespaceResolver) { StartAsync (); return Task.Run (() => { try { return ReadContentAs (returnType, namespaceResolver); } finally { EndAsync (); } }); } public virtual Task<object> ReadContentAsObjectAsync () { StartAsync (); return Task.Run (() => { try { return ReadContentAsObject (); } finally { EndAsync (); } }); } public virtual Task<object> ReadElementContentAsAsync (Type returnType, IXmlNamespaceResolver namespaceResolver) { StartAsync (); return Task.Run (() => { try { return ReadElementContentAs (returnType, namespaceResolver); } finally { EndAsync (); } }); } public virtual Task<object> ReadElementContentAsObjectAsync () { StartAsync (); return Task.Run (() => { try { return ReadElementContentAsObject (); } finally { EndAsync (); } }); } public virtual Task<string> ReadElementContentAsStringAsync () { StartAsync (); return Task.Run (() => { try { return ReadElementContentAsString (); } finally { EndAsync (); } }); } public virtual Task<XmlNodeType> MoveToContentAsync () { StartAsync (); return Task.Run (() => { try { return MoveToContent (); } finally { EndAsync (); } }); } public virtual Task SkipAsync () { StartAsync (); return Task.Run (() => { try { Skip (); } finally { EndAsync (); } }); } #endregion #endif } }
using System; using System.Collections.Generic; using System.Linq; using GraphQL.Types; using OrchardCore.ContentManagement.GraphQL.Settings; using OrchardCore.ContentManagement.Metadata.Models; namespace OrchardCore.ContentManagement.GraphQL.Options { public class GraphQLContentOptions { public IEnumerable<GraphQLContentTypeOption> ContentTypeOptions { get; set; } = Enumerable.Empty<GraphQLContentTypeOption>(); public IEnumerable<GraphQLContentPartOption> PartOptions { get; set; } = Enumerable.Empty<GraphQLContentPartOption>(); public IEnumerable<GraphQLField> HiddenFields { get; set; } = Enumerable.Empty<GraphQLField>(); public GraphQLContentOptions ConfigureContentType(string contentType, Action<GraphQLContentTypeOption> action) { var option = new GraphQLContentTypeOption(contentType); action(option); ContentTypeOptions = ContentTypeOptions.Union(new[] { option }); return this; } public GraphQLContentOptions ConfigurePart<TContentPart>(Action<GraphQLContentPartOption> action) where TContentPart : ContentPart { var option = new GraphQLContentPartOption<TContentPart>(); action(option); PartOptions = PartOptions.Union(new[] { option }); return this; } public GraphQLContentOptions ConfigurePart(string partName, Action<GraphQLContentPartOption> action) { var option = new GraphQLContentPartOption(partName); action(option); PartOptions = PartOptions.Union(new[] { option }); return this; } public GraphQLContentOptions IgnoreField<IGraphType>(string fieldName) where IGraphType : IObjectGraphType { HiddenFields = HiddenFields.Union(new[] { new GraphQLField<IGraphType>(fieldName), }); return this; } public GraphQLContentOptions IgnoreField(Type fieldType, string fieldName) { HiddenFields = HiddenFields.Union(new[] { new GraphQLField(fieldType, fieldName), }); return this; } /// <summary> /// Collapsing works at a hierarchy /// /// If the Content Type is marked at collapsed, then all parts are collapsed. /// If the Content Type is not marked collapsed, then it falls down to the content type under it. /// If the Content Part at a top level is marked collapsed, then it will trump above. /// </summary> /// <param name="definition"></param> /// <returns></returns> internal bool ShouldCollapse(ContentTypePartDefinition definition) { if (IsCollapsedByDefault(definition)) { return true; } var settings = definition.GetSettings<GraphQLContentTypePartSettings>(); if (settings.Collapse) { return true; } return false; } public bool IsCollapsedByDefault(ContentTypePartDefinition definition) { var contentType = definition.ContentTypeDefinition.Name; var partName = definition.PartDefinition.Name; if (contentType == partName) { return true; } var contentTypeOption = ContentTypeOptions.FirstOrDefault(ctp => ctp.ContentType == contentType); if (contentTypeOption != null) { if (contentTypeOption.Collapse) { return true; } var contentTypePartOption = contentTypeOption.PartOptions.FirstOrDefault(p => p.Name == partName); if (contentTypePartOption != null) { if (contentTypePartOption.Collapse) { return true; } } } var contentPartOption = PartOptions.FirstOrDefault(p => p.Name == partName); if (contentPartOption != null) { if (contentPartOption.Collapse) { return true; } } return false; } internal bool ShouldSkip(ContentTypePartDefinition definition) { if (IsHiddenByDefault(definition)) { return true; } var settings = definition.GetSettings<GraphQLContentTypePartSettings>(); if (settings.Hidden) { return true; } return false; } internal bool ShouldSkip(Type fieldType, string fieldName) { return HiddenFields .Any(x => x.FieldType == fieldType && x.FieldName.Equals(fieldName, StringComparison.OrdinalIgnoreCase)); } public bool IsHiddenByDefault(ContentTypePartDefinition definition) { var contentType = definition.ContentTypeDefinition.Name; var partName = definition.PartDefinition.Name; var contentTypeOption = ContentTypeOptions.FirstOrDefault(ctp => ctp.ContentType == contentType); if (contentTypeOption != null) { if (contentTypeOption.Hidden) { return true; } var contentTypePartOption = contentTypeOption.PartOptions.FirstOrDefault(p => p.Name == partName); if (contentTypePartOption != null) { if (contentTypePartOption.Hidden) { return true; } } } var contentPartOption = PartOptions.FirstOrDefault(p => p.Name == partName); if (contentPartOption != null) { if (contentPartOption.Hidden) { return true; } } return false; } } }
namespace _03.Friends_in_Need { using System; using System.Collections.Generic; using System.Text; public class Graph<T> { private readonly HashSet<Node<T>> visited; public Graph() { this.Nodes = new Dictionary<T, Node<T>>(); this.visited = new HashSet<Node<T>>(); } public IDictionary<T, Node<T>> Nodes { get; private set; } public void AddNode(T name) { var node = new Node<T>(name); if (Nodes.ContainsKey(name)) { throw new ArgumentException(string.Format("Node with name {0} is existing in the graph.", name)); } Nodes.Add(name, node); } public void AddNode(Node<T> node) { if (this.Nodes.ContainsKey(node.Name)) { throw new ArgumentException(string.Format("Node with name {0} is existing in the graph.", node.Name)); } this.Nodes.Add(node.Name, node); } public void AddConnection(T fromNode, T toNode, int distance, bool twoWay) { if (!Nodes.ContainsKey(fromNode)) { this.AddNode(fromNode); } if (!Nodes.ContainsKey(toNode)) { this.AddNode(toNode); } Nodes[fromNode].AddConnection(Nodes[toNode], distance, twoWay); } public List<Node<T>> FindShortestDistanceToAllNodes(T startNodeName) { if (!Nodes.ContainsKey(startNodeName)) { throw new ArgumentOutOfRangeException(string.Format("{0} is not containing in the graph.", startNodeName)); } SetShortestDistances(Nodes[startNodeName]); var nodes = new List<Node<T>>(); foreach (var item in Nodes) { if (!item.Key.Equals(startNodeName)) { nodes.Add(item.Value); } } return nodes; } private void SetShortestDistances(Node<T> startNode) { var queue = new PriorityQueue<Node<T>>(); // set to all nodes DijkstraDistance to PositiveInfinity foreach (var node in Nodes) { if (!startNode.Name.Equals(node.Key)) { node.Value.DijkstraDistance = double.PositiveInfinity; //queue.Enqueue(node.Value); } } startNode.DijkstraDistance = 0.0d; queue.Enqueue(startNode); while (queue.Count != 0) { Node<T> currentNode = queue.Dequeue(); if (double.IsPositiveInfinity(currentNode.DijkstraDistance)) { break; } foreach (var neighbour in Nodes[currentNode.Name].Connections) { double subDistance = currentNode.DijkstraDistance + neighbour.Distance; if (subDistance < neighbour.Target.DijkstraDistance) { neighbour.Target.DijkstraDistance = subDistance; queue.Enqueue(neighbour.Target); } } } } public void SetAllDijkstraDistanceValue(double value) { foreach (var node in Nodes) { node.Value.DijkstraDistance = value; } } public double GetSumOfAllDijkstraDistance() { foreach (var item in Nodes) { if (!visited.Contains(item.Value)) { EmployDfs(item.Value); } } double sum = 0; foreach (var node in Nodes) { sum += node.Value.DijkstraDistance; } return sum; } public void EmployDfs(Node<T> node) { visited.Add(node); foreach (var item in node.Connections) { if (!visited.Contains(item.Target)) { EmployDfs(item.Target); } node.DijkstraDistance += item.Target.DijkstraDistance; } if (node.DijkstraDistance == 0) { node.DijkstraDistance++; } } public void EmployBfs(T nodeName) { var nodes = new Queue<Node<T>>(); Node<T> node = Nodes[nodeName]; nodes.Enqueue(node); while (nodes.Count != 0) { Node<T> currentNode = nodes.Dequeue(); currentNode.DijkstraDistance++; foreach (var connection in Nodes[currentNode.Name].Connections) { nodes.Enqueue(connection.Target); } } } public List<Edge<T>> PrimeMinimumSpanningTree(T startNodeName) { if (!Nodes.ContainsKey(startNodeName)) { throw new ArgumentOutOfRangeException(string.Format("{0} is not containing in the graph.", startNodeName)); } var mpdTree = new List<Edge<T>>(); var queue = new PriorityQueue<Edge<T>>(); Node<T> node = Nodes[startNodeName]; foreach (var edge in node.Connections) { queue.Enqueue(edge); } visited.Add(node); while (queue.Count > 0) { Edge<T> edge = queue.Dequeue(); if (!visited.Contains(edge.Target)) { node = edge.Target; visited.Add(node); //we "visit" this node mpdTree.Add(edge); foreach (var item in node.Connections) { if (!mpdTree.Contains(item)) { if (!visited.Contains(item.Target)) { queue.Enqueue(item); } } } } } visited.Clear(); return mpdTree; } public override string ToString() { var result = new StringBuilder(); foreach (var node in this.Nodes) { result.Append("(" + node.Key + ") -> "); foreach (var conection in node.Value.Connections) { result.Append("(" + conection.Target + ") with:" + conection.Distance + " "); } result.AppendLine(); } return result.ToString(); } } }
//------------------------------------------------------------------------------ // <copyright file="BindingNavigator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Globalization; using System.Runtime.InteropServices; [ ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), DefaultProperty("BindingSource"), DefaultEvent("RefreshItems"), Designer("System.Windows.Forms.Design.BindingNavigatorDesigner, " + AssemblyRef.SystemDesign), SRDescription(SR.DescriptionBindingNavigator) ] /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator"]/* /> public class BindingNavigator : ToolStrip, ISupportInitialize { private BindingSource bindingSource; private ToolStripItem moveFirstItem; private ToolStripItem movePreviousItem; private ToolStripItem moveNextItem; private ToolStripItem moveLastItem; private ToolStripItem addNewItem; private ToolStripItem deleteItem; private ToolStripItem positionItem; private ToolStripItem countItem; private String countItemFormat = SR.GetString(SR.BindingNavigatorCountItemFormat); private EventHandler onRefreshItems = null; private bool initializing = false; private bool addNewItemUserEnabled = true; private bool deleteItemUserEnabled = true; /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.BindingNavigator"]/*' /> /// <devdoc> /// Creates an empty BindingNavigator tool strip. /// Call AddStandardItems() to add standard tool strip items. /// </devdoc> [EditorBrowsable(EditorBrowsableState.Never)] public BindingNavigator() : this(false) { } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.BindingNavigator1"]/*' /> /// <devdoc> /// Creates a BindingNavigator strip containing standard items, bound to the specified BindingSource. /// </devdoc> public BindingNavigator(BindingSource bindingSource) : this(true) { BindingSource = bindingSource; } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.BindingNavigator3"]/*' /> /// <devdoc> /// Creates an empty BindingNavigator tool strip, and adds the strip to the specified container. /// Call AddStandardItems() to add standard tool strip items. /// </devdoc> [EditorBrowsable(EditorBrowsableState.Never)] public BindingNavigator(IContainer container) : this(false) { if (container == null) { throw new ArgumentNullException("container"); } container.Add(this); } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.BindingNavigator4"]/*' /> /// <devdoc> /// Creates a BindingNavigator strip, optionally containing a set of standard tool strip items. /// </devdoc> public BindingNavigator(bool addStandardItems) { if (addStandardItems) { AddStandardItems(); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.BeginInit"]/*' /> /// <devdoc> /// ISupportInitialize support. Disables updates to tool strip items during initialization. /// </devdoc> public void BeginInit() { initializing = true; } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.EndInit"]/*' /> /// <devdoc> /// ISupportInitialize support. Enables updates to tool strip items after initialization. /// </devdoc> public void EndInit() { initializing = false; RefreshItemsInternal(); } /// <devdoc> /// Unhooks the BindingNavigator from the BindingSource. /// </devdoc> protected override void Dispose(bool disposing) { if (disposing) { BindingSource = null; // ...unwires from events of any prior BindingSource } base.Dispose(disposing); } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.AddStandardItems"]/*' /> /// <devdoc> /// Adds standard set of tool strip items to a BindingNavigator tool strip, for basic /// navigation operations such as Move First, Move Next, Add New, etc. /// /// This method is called by the Windows Form Designer when a new BindingNavigator is /// added to a Form. When creating a BindingNavigator programmatically, this method /// must be called explicitly. /// /// Override this method in derived classes to define additional or alternative standard items. /// To ensure optimal design-time support for your derived class, make sure each item has a /// meaningful value in its Name property. At design time, this will be used to generate a unique /// name for the corresponding member variable. The item's Name property will then be updated /// to match the name given to the member variable. /// /// Note: This method does NOT remove any previous items from the strip, or suspend /// layout while items are being added. Those are responsibilities of the caller. /// </devdoc> public virtual void AddStandardItems() { // // Create items // MoveFirstItem = new System.Windows.Forms.ToolStripButton(); MovePreviousItem = new System.Windows.Forms.ToolStripButton(); MoveNextItem = new System.Windows.Forms.ToolStripButton(); MoveLastItem = new System.Windows.Forms.ToolStripButton(); PositionItem = new System.Windows.Forms.ToolStripTextBox(); CountItem = new System.Windows.Forms.ToolStripLabel(); AddNewItem = new System.Windows.Forms.ToolStripButton(); DeleteItem = new System.Windows.Forms.ToolStripButton(); ToolStripSeparator separator1 = new System.Windows.Forms.ToolStripSeparator(); ToolStripSeparator separator2 = new System.Windows.Forms.ToolStripSeparator(); ToolStripSeparator separator3 = new System.Windows.Forms.ToolStripSeparator(); // // Set up strings // // Hacky workaround for VSWhidbey 407243 // Default to lowercase for null name, because C# dev is more likely to create controls programmatically than // vb dev. char ch = string.IsNullOrEmpty(Name) || char.IsLower(Name[0]) ? 'b' : 'B'; MoveFirstItem.Name = ch + "indingNavigatorMoveFirstItem"; MovePreviousItem.Name = ch + "indingNavigatorMovePreviousItem"; MoveNextItem.Name = ch + "indingNavigatorMoveNextItem"; MoveLastItem.Name = ch + "indingNavigatorMoveLastItem"; PositionItem.Name = ch + "indingNavigatorPositionItem"; CountItem.Name = ch + "indingNavigatorCountItem"; AddNewItem.Name = ch + "indingNavigatorAddNewItem"; DeleteItem.Name = ch + "indingNavigatorDeleteItem"; separator1.Name = ch + "indingNavigatorSeparator"; separator2.Name = ch + "indingNavigatorSeparator"; separator3.Name = ch + "indingNavigatorSeparator"; MoveFirstItem.Text = SR.GetString(SR.BindingNavigatorMoveFirstItemText); MovePreviousItem.Text = SR.GetString(SR.BindingNavigatorMovePreviousItemText); MoveNextItem.Text = SR.GetString(SR.BindingNavigatorMoveNextItemText); MoveLastItem.Text = SR.GetString(SR.BindingNavigatorMoveLastItemText); AddNewItem.Text = SR.GetString(SR.BindingNavigatorAddNewItemText); DeleteItem.Text = SR.GetString(SR.BindingNavigatorDeleteItemText); CountItem.ToolTipText = SR.GetString(SR.BindingNavigatorCountItemTip); PositionItem.ToolTipText = SR.GetString(SR.BindingNavigatorPositionItemTip); CountItem.AutoToolTip = false; PositionItem.AutoToolTip = false; PositionItem.AccessibleName = SR.GetString(SR.BindingNavigatorPositionAccessibleName); // // Set up images // Bitmap moveFirstImage = new Bitmap(typeof(BindingNavigator), "BindingNavigator.MoveFirst.bmp"); Bitmap movePreviousImage = new Bitmap(typeof(BindingNavigator), "BindingNavigator.MovePrevious.bmp"); Bitmap moveNextImage = new Bitmap(typeof(BindingNavigator), "BindingNavigator.MoveNext.bmp"); Bitmap moveLastImage = new Bitmap(typeof(BindingNavigator), "BindingNavigator.MoveLast.bmp"); Bitmap addNewImage = new Bitmap(typeof(BindingNavigator), "BindingNavigator.AddNew.bmp"); Bitmap deleteImage = new Bitmap(typeof(BindingNavigator), "BindingNavigator.Delete.bmp"); moveFirstImage.MakeTransparent(System.Drawing.Color.Magenta); movePreviousImage.MakeTransparent(System.Drawing.Color.Magenta); moveNextImage.MakeTransparent(System.Drawing.Color.Magenta); moveLastImage.MakeTransparent(System.Drawing.Color.Magenta); addNewImage.MakeTransparent(System.Drawing.Color.Magenta); deleteImage.MakeTransparent(System.Drawing.Color.Magenta); MoveFirstItem.Image = moveFirstImage; MovePreviousItem.Image = movePreviousImage; MoveNextItem.Image = moveNextImage; MoveLastItem.Image = moveLastImage; AddNewItem.Image = addNewImage; DeleteItem.Image = deleteImage; MoveFirstItem.RightToLeftAutoMirrorImage = true; MovePreviousItem.RightToLeftAutoMirrorImage = true; MoveNextItem.RightToLeftAutoMirrorImage = true; MoveLastItem.RightToLeftAutoMirrorImage = true; AddNewItem.RightToLeftAutoMirrorImage = true; DeleteItem.RightToLeftAutoMirrorImage = true; MoveFirstItem.DisplayStyle = ToolStripItemDisplayStyle.Image; MovePreviousItem.DisplayStyle = ToolStripItemDisplayStyle.Image; MoveNextItem.DisplayStyle = ToolStripItemDisplayStyle.Image; MoveLastItem.DisplayStyle = ToolStripItemDisplayStyle.Image; AddNewItem.DisplayStyle = ToolStripItemDisplayStyle.Image; DeleteItem.DisplayStyle = ToolStripItemDisplayStyle.Image; // // Set other random properties // PositionItem.AutoSize = false; PositionItem.Width = 50; // // Add items to strip // Items.AddRange(new ToolStripItem[] { MoveFirstItem, MovePreviousItem, separator1, PositionItem, CountItem, separator2, MoveNextItem, MoveLastItem, separator3, AddNewItem, DeleteItem, }); } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.BindingSource"]/*' /> /// <devdoc> /// The BindingSource who's list we are currently navigating, or null. /// </devdoc> [ DefaultValue(null), SRCategory(SR.CatData), SRDescription(SR.BindingNavigatorBindingSourcePropDescr), TypeConverter(typeof(ReferenceConverter)), SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly") ] public BindingSource BindingSource { get { return bindingSource; } set { WireUpBindingSource(ref bindingSource, value); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.MoveFirstItem"]/*' /> /// <devdoc> /// The ToolStripItem that triggers the 'Move first' action, or null. /// </devdoc> [ TypeConverter(typeof(ReferenceConverter)), SRCategory(SR.CatItems), SRDescription(SR.BindingNavigatorMoveFirstItemPropDescr) ] public ToolStripItem MoveFirstItem { get { if (moveFirstItem != null && moveFirstItem.IsDisposed) { moveFirstItem = null; } return moveFirstItem; } set { WireUpButton(ref moveFirstItem, value, new EventHandler(OnMoveFirst)); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.MovePreviousItem"]/*' /> /// <devdoc> /// The ToolStripItem that triggers the 'Move previous' action, or null. /// </devdoc> [ TypeConverter(typeof(ReferenceConverter)), SRCategory(SR.CatItems), SRDescription(SR.BindingNavigatorMovePreviousItemPropDescr) ] public ToolStripItem MovePreviousItem { get { if (movePreviousItem != null && movePreviousItem.IsDisposed) { movePreviousItem = null; } return movePreviousItem; } set { WireUpButton(ref movePreviousItem, value, new EventHandler(OnMovePrevious)); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.MoveNextItem"]/*' /> /// <devdoc> /// The ToolStripItem that triggers the 'Move next' action, or null. /// </devdoc> [ TypeConverter(typeof(ReferenceConverter)), SRCategory(SR.CatItems), SRDescription(SR.BindingNavigatorMoveNextItemPropDescr) ] public ToolStripItem MoveNextItem { get { if (moveNextItem != null && moveNextItem.IsDisposed) { moveNextItem = null; } return moveNextItem; } set { WireUpButton(ref moveNextItem, value, new EventHandler(OnMoveNext)); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.MoveLastItem"]/*' /> /// <devdoc> /// The ToolStripItem that triggers the 'Move last' action, or null. /// </devdoc> [ TypeConverter(typeof(ReferenceConverter)), SRCategory(SR.CatItems), SRDescription(SR.BindingNavigatorMoveLastItemPropDescr) ] public ToolStripItem MoveLastItem { get { if (moveLastItem != null && moveLastItem.IsDisposed) { moveLastItem = null; } return moveLastItem; } set { WireUpButton(ref moveLastItem, value, new EventHandler(OnMoveLast)); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.AddNewItem"]/*' /> /// <devdoc> /// The ToolStripItem that triggers the 'Add new' action, or null. /// </devdoc> [ TypeConverter(typeof(ReferenceConverter)), SRCategory(SR.CatItems), SRDescription(SR.BindingNavigatorAddNewItemPropDescr) ] public ToolStripItem AddNewItem { get { if (addNewItem != null && addNewItem.IsDisposed) { addNewItem = null; } return addNewItem; } set { if (addNewItem != value && value != null) { value.InternalEnabledChanged += new System.EventHandler(OnAddNewItemEnabledChanged); addNewItemUserEnabled = value.Enabled; } WireUpButton(ref addNewItem, value, new EventHandler(OnAddNew)); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.DeleteItem"]/*' /> /// <devdoc> /// The ToolStripItem that triggers the 'Delete' action, or null. /// </devdoc> [ TypeConverter(typeof(ReferenceConverter)), SRCategory(SR.CatItems), SRDescription(SR.BindingNavigatorDeleteItemPropDescr) ] public ToolStripItem DeleteItem { get { if (deleteItem != null && deleteItem.IsDisposed) { deleteItem = null; } return deleteItem; } set { if (deleteItem != value && value != null) { value.InternalEnabledChanged += new System.EventHandler(OnDeleteItemEnabledChanged); deleteItemUserEnabled = value.Enabled; } WireUpButton(ref deleteItem, value, new EventHandler(OnDelete)); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.PositionItem"]/*' /> /// <devdoc> /// The ToolStripItem that displays the current position, or null. /// </devdoc> [ TypeConverter(typeof(ReferenceConverter)), SRCategory(SR.CatItems), SRDescription(SR.BindingNavigatorPositionItemPropDescr) ] public ToolStripItem PositionItem { get { if (positionItem != null && positionItem.IsDisposed) { positionItem = null; } return positionItem; } set { WireUpTextBox(ref positionItem, value, new KeyEventHandler(OnPositionKey), new EventHandler(OnPositionLostFocus)); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.CountItem"]/*' /> /// <devdoc> /// The ToolStripItem that displays the total number of items, or null. /// </devdoc> [ TypeConverter(typeof(ReferenceConverter)), SRCategory(SR.CatItems), SRDescription(SR.BindingNavigatorCountItemPropDescr) ] public ToolStripItem CountItem { get { if (countItem != null && countItem.IsDisposed) { countItem = null; } return countItem; } set { WireUpLabel(ref countItem, value); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.CountItemFormat"]/*' /> /// <devdoc> /// Formatting to apply to count displayed in the CountItem tool strip item. /// </devdoc> [ SRCategory(SR.CatAppearance), SRDescription(SR.BindingNavigatorCountItemFormatPropDescr) ] public String CountItemFormat { get { return countItemFormat; } set { if (countItemFormat != value) { countItemFormat = value; RefreshItemsInternal(); } } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.RefreshItems"]/*' /> /// <devdoc> /// Event raised when the state of the tool strip items needs to be /// refreshed to reflect the current state of the data. /// </devdoc> [ SRCategory(SR.CatBehavior), SRDescription(SR.BindingNavigatorRefreshItemsEventDescr) ] public event EventHandler RefreshItems { add { onRefreshItems += value; } remove { onRefreshItems -= value; } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.RefreshItemsCore"]/*' /> /// <devdoc> /// Refreshes the state of the standard items to reflect the current state of the data. /// </devdoc> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void RefreshItemsCore() { int count, position; bool allowNew, allowRemove; // Get state info from the binding source (if any) if (bindingSource == null) { count = 0; position = 0; allowNew = false; allowRemove = false; } else { count = bindingSource.Count; position = bindingSource.Position + 1; allowNew = (bindingSource as IBindingList).AllowNew; allowRemove = (bindingSource as IBindingList).AllowRemove; } // Enable or disable items (except when in design mode) if (!DesignMode) { if (MoveFirstItem != null) moveFirstItem.Enabled = (position > 1); if (MovePreviousItem != null) movePreviousItem.Enabled = (position > 1); if (MoveNextItem != null) moveNextItem.Enabled = (position < count); if (MoveLastItem != null) moveLastItem.Enabled = (position < count); if (AddNewItem != null) { System.EventHandler handler = new System.EventHandler(OnAddNewItemEnabledChanged); addNewItem.InternalEnabledChanged -= handler; addNewItem.Enabled = (addNewItemUserEnabled && allowNew); addNewItem.InternalEnabledChanged += handler; } if (DeleteItem != null) { System.EventHandler handler = new System.EventHandler(OnDeleteItemEnabledChanged); deleteItem.InternalEnabledChanged -= handler; deleteItem.Enabled = (deleteItemUserEnabled && allowRemove && count > 0); deleteItem.InternalEnabledChanged += handler; } if (PositionItem != null) positionItem.Enabled = (position > 0 && count > 0); if (CountItem != null) countItem.Enabled = (count > 0); } // Update current position indicator if (positionItem != null) { positionItem.Text = position.ToString(CultureInfo.CurrentCulture); } // Update record count indicator if (countItem != null) { countItem.Text = DesignMode ? CountItemFormat : String.Format(CultureInfo.CurrentCulture, CountItemFormat, count); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.OnRefreshItems"]/*' /> /// <devdoc> /// Called when the state of the tool strip items needs to be refreshed to reflect the current state of the data. /// Calls <see cref='RefreshItemsCore'> to refresh the state of the standard items, then raises the RefreshItems event. /// </devdoc> protected virtual void OnRefreshItems() { // Refresh all the standard items RefreshItemsCore(); // Raise the public event if (onRefreshItems != null) { onRefreshItems(this, EventArgs.Empty); } } /// <include file='doc\BindingNavigator.uex' path='docs/doc[@for="BindingNavigator.Validate"]/*' /> /// <devdoc> /// Triggers form validation. Used by the BindingNavigator's standard items when clicked. If a validation error occurs /// on the form, focus remains on the active control and the standard item does not perform its standard click action. /// Custom items may also use this method to trigger form validation and check for success before performing an action. /// </devdoc> public bool Validate() { bool validatedControlAllowsFocusChange; return this.ValidateActiveControl(out validatedControlAllowsFocusChange); } /// <devdoc> /// Accept new row position entered into PositionItem. /// </devdoc> private void AcceptNewPosition() { // If no position item or binding source, do nothing if (positionItem == null || bindingSource == null) { return; } // Default to old position, in case new position turns out to be garbage int newPosition = bindingSource.Position; try { // Read new position from item text (and subtract one!) newPosition = Convert.ToInt32(positionItem.Text, CultureInfo.CurrentCulture) - 1; } catch (System.FormatException) { // Ignore bad user input } catch (System.OverflowException) { // Ignore bad user input } // If user has managed to enter a valid number, that is not the same as the current position, try // navigating to that position. Let the BindingSource validate the new position to keep it in range. if (newPosition != bindingSource.Position) { bindingSource.Position = newPosition; } // Update state of all items to reflect final position. If the user entered a bad position, // this will effectively reset the Position item back to showing the current position. RefreshItemsInternal(); } /// <devdoc> /// Cancel new row position entered into PositionItem. /// </devdoc> private void CancelNewPosition() { // Just refresh state of all items to reflect current position // (causing position item's new value to get blasted away) RefreshItemsInternal(); } /// <devdoc> /// Navigates to first item in BindingSource's list when the MoveFirstItem is clicked. /// </devdoc> private void OnMoveFirst(object sender, EventArgs e) { if (Validate()) { if (bindingSource != null) { bindingSource.MoveFirst(); RefreshItemsInternal(); } } } /// <devdoc> /// Navigates to previous item in BindingSource's list when the MovePreviousItem is clicked. /// </devdoc> private void OnMovePrevious(object sender, EventArgs e) { if (Validate()) { if (bindingSource != null) { bindingSource.MovePrevious(); RefreshItemsInternal(); } } } /// <devdoc> /// Navigates to next item in BindingSource's list when the MoveNextItem is clicked. /// </devdoc> private void OnMoveNext(object sender, EventArgs e) { if (Validate()) { if (bindingSource != null) { bindingSource.MoveNext(); RefreshItemsInternal(); } } } /// <devdoc> /// Navigates to last item in BindingSource's list when the MoveLastItem is clicked. /// </devdoc> private void OnMoveLast(object sender, EventArgs e) { if (Validate()) { if (bindingSource != null) { bindingSource.MoveLast(); RefreshItemsInternal(); } } } /// <devdoc> /// Adds new item to BindingSource's list when the AddNewItem is clicked. /// </devdoc> private void OnAddNew(object sender, EventArgs e) { if (Validate()) { if (bindingSource != null) { bindingSource.AddNew(); RefreshItemsInternal(); } } } /// <devdoc> /// Deletes current item from BindingSource's list when the DeleteItem is clicked. /// </devdoc> private void OnDelete(object sender, EventArgs e) { if (Validate()) { if (bindingSource != null) { bindingSource.RemoveCurrent(); RefreshItemsInternal(); } } } /// <devdoc> /// Navigates to specific item in BindingSource's list when a value is entered into the PositionItem. /// </devdoc> private void OnPositionKey(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Enter: AcceptNewPosition(); break; case Keys.Escape: CancelNewPosition(); break; } } /// <devdoc> /// Navigates to specific item in BindingSource's list when a value is entered into the PositionItem. /// </devdoc> private void OnPositionLostFocus(object sender, EventArgs e) { AcceptNewPosition(); } /// <devdoc> /// Refresh tool strip items when something changes in the BindingSource. /// </devdoc> private void OnBindingSourceStateChanged(object sender, EventArgs e) { RefreshItemsInternal(); } /// <devdoc> /// Refresh tool strip items when something changes in the BindingSource's list. /// </devdoc> private void OnBindingSourceListChanged(object sender, ListChangedEventArgs e) { RefreshItemsInternal(); } /// <devdoc> /// Refresh the state of the items when the state of the data changes. /// </devdoc> private void RefreshItemsInternal() { // Block all updates during initialization if (initializing) { return; } // Call method that updates the items (overridable) OnRefreshItems(); } private void ResetCountItemFormat() { countItemFormat = SR.GetString(SR.BindingNavigatorCountItemFormat); } private bool ShouldSerializeCountItemFormat() { return countItemFormat != SR.GetString(SR.BindingNavigatorCountItemFormat); } private void OnAddNewItemEnabledChanged(object sender, EventArgs e) { if (AddNewItem != null) { addNewItemUserEnabled = addNewItem.Enabled; } } private void OnDeleteItemEnabledChanged(object sender, EventArgs e) { if (DeleteItem != null) { deleteItemUserEnabled = deleteItem.Enabled; } } /// <devdoc> /// Wire up some member variable to the specified button item, hooking events /// on the new button and unhooking them from the previous button, if required. /// </devdoc> private void WireUpButton(ref ToolStripItem oldButton, ToolStripItem newButton, EventHandler clickHandler) { if (oldButton == newButton) { return; } if (oldButton != null) { oldButton.Click -= clickHandler; } if (newButton != null) { newButton.Click += clickHandler; } oldButton = newButton; RefreshItemsInternal(); } /// <devdoc> /// Wire up some member variable to the specified text box item, hooking events /// on the new text box and unhooking them from the previous text box, if required. /// </devdoc> private void WireUpTextBox(ref ToolStripItem oldTextBox, ToolStripItem newTextBox, KeyEventHandler keyUpHandler, EventHandler lostFocusHandler) { if (oldTextBox != newTextBox) { ToolStripControlHost oldCtrl = oldTextBox as ToolStripControlHost; ToolStripControlHost newCtrl = newTextBox as ToolStripControlHost; if (oldCtrl != null) { oldCtrl.KeyUp -= keyUpHandler; oldCtrl.LostFocus -= lostFocusHandler; } if (newCtrl != null) { newCtrl.KeyUp += keyUpHandler; newCtrl.LostFocus += lostFocusHandler; } oldTextBox = newTextBox; RefreshItemsInternal(); } } /// <devdoc> /// Wire up some member variable to the specified label item, hooking events /// on the new label and unhooking them from the previous label, if required. /// </devdoc> private void WireUpLabel(ref ToolStripItem oldLabel, ToolStripItem newLabel) { if (oldLabel != newLabel) { oldLabel = newLabel; RefreshItemsInternal(); } } /// <devdoc> /// Wire up some member variable to the specified binding source, hooking events /// on the new binding source and unhooking them from the previous one, if required. /// </devdoc> private void WireUpBindingSource(ref BindingSource oldBindingSource, BindingSource newBindingSource) { if (oldBindingSource != newBindingSource) { if (oldBindingSource != null) { oldBindingSource.PositionChanged -= new EventHandler(OnBindingSourceStateChanged); oldBindingSource.CurrentChanged -= new EventHandler(OnBindingSourceStateChanged); oldBindingSource.CurrentItemChanged -= new EventHandler(OnBindingSourceStateChanged); oldBindingSource.DataSourceChanged -= new EventHandler(OnBindingSourceStateChanged); oldBindingSource.DataMemberChanged -= new EventHandler(OnBindingSourceStateChanged); oldBindingSource.ListChanged -= new ListChangedEventHandler(OnBindingSourceListChanged); } if (newBindingSource != null) { newBindingSource.PositionChanged += new EventHandler(OnBindingSourceStateChanged); newBindingSource.CurrentChanged += new EventHandler(OnBindingSourceStateChanged); newBindingSource.CurrentItemChanged += new EventHandler(OnBindingSourceStateChanged); newBindingSource.DataSourceChanged += new EventHandler(OnBindingSourceStateChanged); newBindingSource.DataMemberChanged += new EventHandler(OnBindingSourceStateChanged); newBindingSource.ListChanged += new ListChangedEventHandler(OnBindingSourceListChanged); } oldBindingSource = newBindingSource; RefreshItemsInternal(); } } } }
using UnityEngine; using System.Collections.Generic; using PlayFab.ClientModels; using PlayFab; public static class PF_Bridge { // signature & callback for rasing errors, the enum can be useful for tracking what API call threw the error. public delegate void PlayFabErrorHandler(string details, PlayFabAPIMethods method, MessageDisplayStyle displayStyle); public static event PlayFabErrorHandler OnPlayFabCallbackError; // called after a successful API callback (useful for stopping the spinner) public delegate void CallbackSuccess(string details, PlayFabAPIMethods method, MessageDisplayStyle displayStyle); public static event CallbackSuccess OnPlayfabCallbackSuccess; public static string IAB_CurrencyCode = ""; public static int IAB_Price = 0; /// <summary> /// The standard way to notify listeners that a PF call has completed successfully /// </summary> /// <param name="details"> a string that can be used so send any additional custom information </param> /// <param name="method"> enum that maps to the call that just completed successfully </param> /// <param name="style"> error will throw the standard error box, none will eat the message and output to console </param> public static void RaiseCallbackSuccess(string details, PlayFabAPIMethods method, MessageDisplayStyle style) { if (OnPlayfabCallbackSuccess != null) OnPlayfabCallbackSuccess(details, method, style); } /// <summary> /// The standard way to notify listeners that a PF call has failed /// </summary> /// <param name="details"> a string that can be used so send any additional custom information </param> /// <param name="method"> enum that maps to the call that just completed successfully </param> /// <param name="style"> error will throw the standard error box, none will eat the message and output to console </param> public static void RaiseCallbackError(string details, PlayFabAPIMethods method, MessageDisplayStyle style) { if (OnPlayFabCallbackError != null) OnPlayFabCallbackError(details, method, style); } /// <summary> /// Standard, reusable error callback /// </summary> /// <param name="error">Error.</param> public static void PlayFabErrorCallback(PlayFab.PlayFabError error) { if (OnPlayFabCallbackError != null) OnPlayFabCallbackError(error.ErrorMessage, PlayFabAPIMethods.Generic, MessageDisplayStyle.error); } public static bool VerifyErrorFreeCloudScriptResult(ExecuteCloudScriptResult result) { if (result.Error != null) OnPlayFabCallbackError(string.Format("{0}: ERROR: [{1}] -- {2}", result.FunctionName, result.Error.Error, result.Error.Message), PlayFabAPIMethods.ExecuteCloudScript, MessageDisplayStyle.error); return result.Error == null; } /// <summary> /// Validates the android IAP completed through the GooglePlay store. /// </summary> public static void ValidateAndroidPurcahse(string json, string sig) { var request = new ValidateGooglePlayPurchaseRequest { Signature = sig, ReceiptJson = json }; DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.ValidateIAP); PlayFabClientAPI.ValidateGooglePlayPurchase(request, result => { RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.ValidateIAP, MessageDisplayStyle.none); }, PlayFabErrorCallback); } public static void ValidateIosPurchase(string receipt) { var request = new ValidateIOSReceiptRequest { CurrencyCode = IAB_CurrencyCode, PurchasePrice = IAB_Price, ReceiptData = receipt }; DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.ValidateIAP); PlayFabClientAPI.ValidateIOSReceipt(request, result => { RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.ValidateIAP, MessageDisplayStyle.none); }, PlayFabErrorCallback); } // Used for sending analytics data back into PlayFab public enum CustomEventTypes { none, Client_LevelUp, Client_LevelComplete, Client_PlayerDied, Client_BossKill, Client_UnicornFreed, Client_StoreVisit, Client_SaleClicked, Client_BattleAborted, Client_RegisteredAccount, Client_FriendAdded, Client_AdWatched } /// <summary> /// Logs the custom event. /// </summary> /// <param name="eventName">Event name.</param> /// <param name="eventData">Event data.</param> public static void LogCustomEvent(CustomEventTypes eventName, Dictionary<string, object> eventData) { var request = new WriteClientPlayerEventRequest(); request.Body = eventData; request.EventName = eventName.ToString(); PlayFabClientAPI.WritePlayerEvent(request, null, PlayFabErrorCallback); /* EXAMPLE OF eventData new Dictionary<string,object >() { {"monsters_killed", obj.kills}, {"gold_won", obj.currency}, {"result", "win" } }; */ } } public class UpdatedVCBalance { public string VirtualCurrency { get; set; } public int Balance { get; set; } } public class OutgoingAPICounter { public float outgoingGameTime; public PlayFabAPIMethods method; } //[Flags] // need to add in Po2 numbers //http://stackoverflow.com/questions/1030090/how-do-you-pass-multiple-enum-values-in-c // think about how to log to console / ui log maybe another enum for this // could aslo add something like errorWithRetry, public enum MessageDisplayStyle { none, success, context, error } //TODO uncomment this out when we // An enum that maps to the PlayFab calls for tracking messages passed around the app //#region API Enum public enum PlayFabAPIMethods { Null, Generic, GenericLogin, GenericCloudScript, ExecuteCloudScript, RegisterPlayFabUser, LoginWithPlayFab, LoginWithDeviceId, LoginWithFacebook, GetAccountInfo, GetCDNConent, GetTitleData_General, GetTitleData_Specific, GetEvents, GetActiveEvents, GetTitleNews, GetCloudScriptUrl, GetAllUsersCharacters, GetCharacterData, GetCharacterReadOnlyData, GetUserStatistics, GetCharacterStatistics, GetPlayerLeaderboard, GetFriendsLeaderboard, GetMyPlayerRank, GetUserData, GetUserInventory, GetOffersCatalog, UpdateUserStatistics, UpdateCharacterStatistics, GetStoreItems, GrantCharacterToUser, DeleteCharacter, UpdateDisplayName, SendAccountRecoveryEmail, SavePlayerInfo, RetriveQuestItems, RegisterForPush, AddUsernamePassword, LinkDeviceID, LinkFacebookId, LinkGameCenterId, UnlinkAndroidDeviceID, UnlinkIOSDeviceID, UnlinkFacebookId, UnlinkGameCenterId, UnlockContainerItem, UpdateUserData, AddFriend, RemoveFriend, RedeemCoupon, SetFriendTags, GetFriendList, GetCharacterLeaderboard, GetLeaderboardAroundCharacter, ConsumeOffer, ValidateIAP, ConsumeItemUse, UnlockContainer, MakePurchase, } //#endregion
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AsUInt64() { var test = new VectorAs__AsUInt64(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorAs__AsUInt64 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector256<UInt64> value; value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector256<UInt64> value; value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<byte> byteResult = value.As<UInt64, byte>(); ValidateResult(byteResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<double> doubleResult = value.As<UInt64, double>(); ValidateResult(doubleResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<short> shortResult = value.As<UInt64, short>(); ValidateResult(shortResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<int> intResult = value.As<UInt64, int>(); ValidateResult(intResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<long> longResult = value.As<UInt64, long>(); ValidateResult(longResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<sbyte> sbyteResult = value.As<UInt64, sbyte>(); ValidateResult(sbyteResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<float> floatResult = value.As<UInt64, float>(); ValidateResult(floatResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<ushort> ushortResult = value.As<UInt64, ushort>(); ValidateResult(ushortResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<uint> uintResult = value.As<UInt64, uint>(); ValidateResult(uintResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); Vector256<ulong> ulongResult = value.As<UInt64, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector256<UInt64> value; value = Vector256.Create(TestLibrary.Generator.GetUInt64()); object byteResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsByte)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<byte>)(byteResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); object doubleResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsDouble)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<double>)(doubleResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); object shortResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt16)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<short>)(shortResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); object intResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt32)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<int>)(intResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); object longResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt64)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<long>)(longResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); object sbyteResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsSByte)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<sbyte>)(sbyteResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); object floatResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsSingle)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<float>)(floatResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); object ushortResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt16)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<ushort>)(ushortResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); object uintResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt32)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<uint>)(uintResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt64()); object ulongResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt64)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector256<T> result, Vector256<UInt64> value, [CallerMemberName] string method = "") where T : struct { UInt64[] resultElements = new UInt64[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref resultElements[0]), result); UInt64[] valueElements = new UInt64[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(UInt64[] resultElements, UInt64[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt64>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.SIP.Message { /// <summary> /// Implements SIP "sec-mechanism" value. Defined in RFC 3329. /// </summary> /// <remarks> /// <code> /// RFC 3329 Syntax: /// sec-mechanism = mechanism-name *(SEMI mech-parameters) /// mechanism-name = ( "digest" / "tls" / "ipsec-ike" / "ipsec-man" / token ) /// mech-parameters = ( preference / digest-algorithm / digest-qop / digest-verify / extension ) /// preference = "q" EQUAL qvalue /// qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] ) /// digest-algorithm = "d-alg" EQUAL token /// digest-qop = "d-qop" EQUAL token /// digest-verify = "d-ver" EQUAL LDQUOT 32LHEX RDQUOT /// extension = generic-param /// </code> /// </remarks> public class SIP_t_SecMechanism : SIP_t_ValueWithParams { private string m_Mechanism = ""; /// <summary> /// Default constructor. /// </summary> public SIP_t_SecMechanism() { } #region method Parse /// <summary> /// Parses "sec-mechanism" from specified value. /// </summary> /// <param name="value">SIP "sec-mechanism" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if(value == null){ throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "sec-mechanism" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* sec-mechanism = mechanism-name *(SEMI mech-parameters) mechanism-name = ( "digest" / "tls" / "ipsec-ike" / "ipsec-man" / token ) mech-parameters = ( preference / digest-algorithm / digest-qop / digest-verify / extension ) preference = "q" EQUAL qvalue qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] ) digest-algorithm = "d-alg" EQUAL token digest-qop = "d-qop" EQUAL token digest-verify = "d-ver" EQUAL LDQUOT 32LHEX RDQUOT extension = generic-param */ if(reader == null){ throw new ArgumentNullException("reader"); } // mechanism-name string word = reader.ReadWord(); if(word == null){ throw new SIP_ParseException("Invalid 'sec-mechanism', 'mechanism-name' is missing !"); } // Parse parameters ParseParameters(reader); } #endregion #region method ToStringValue /// <summary> /// Converts this to valid "sec-mechanism" value. /// </summary> /// <returns>Returns "sec-mechanism" value.</returns> public override string ToStringValue() { /* sec-mechanism = mechanism-name *(SEMI mech-parameters) mechanism-name = ( "digest" / "tls" / "ipsec-ike" / "ipsec-man" / token ) mech-parameters = ( preference / digest-algorithm / digest-qop / digest-verify / extension ) preference = "q" EQUAL qvalue qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] ) digest-algorithm = "d-alg" EQUAL token digest-qop = "d-qop" EQUAL token digest-verify = "d-ver" EQUAL LDQUOT 32LHEX RDQUOT extension = generic-param */ StringBuilder retVal = new StringBuilder(); // mechanism-name retVal.Append(m_Mechanism); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion #region Properties Implementation /// <summary> /// Gets or sets security mechanism name. Defined values: "digest","tls","ipsec-ike","ipsec-man". /// </summary> /// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception> /// <exception cref="ArgumentException">Is raised when invalid Mechanism value is passed.</exception> public string Mechanism { get{ return m_Mechanism; } set{ if(value == null){ throw new ArgumentNullException("Mechanism"); } if(value == ""){ throw new ArgumentException("Property Mechanism value may not be '' !"); } if(!TextUtils.IsToken(value)){ throw new ArgumentException("Property Mechanism value must be 'token' !"); } m_Mechanism = value; } } /// <summary> /// Gets or sets 'q' parameter value. Value -1 means not specified. /// </summary> public double Q { get{ if(!this.Parameters.Contains("qvalue")){ return -1; } else{ return double.Parse(this.Parameters["qvalue"].Value,System.Globalization.NumberStyles.Any); } } set{ if(value < 0 || value > 2){ throw new ArgumentException("Property QValue value must be between 0.0 and 2.0 !"); } if(value < 0){ this.Parameters.Remove("qvalue"); } else{ this.Parameters.Set("qvalue",value.ToString()); } } } /// <summary> /// Gets or sets 'd-alg' parameter value. Value null means not specified. /// </summary> public string D_Alg { get{ SIP_Parameter parameter = this.Parameters["d-alg"]; if(parameter != null){ return parameter.Value; } else{ return null; } } set{ if(string.IsNullOrEmpty(value)){ this.Parameters.Remove("d-alg"); } else{ this.Parameters.Set("d-alg",value); } } } /// <summary> /// Gets or sets 'd-qop' parameter value. Value null means not specified. /// </summary> public string D_Qop { get{ SIP_Parameter parameter = this.Parameters["d-qop"]; if(parameter != null){ return parameter.Value; } else{ return null; } } set{ if(string.IsNullOrEmpty(value)){ this.Parameters.Remove("d-qop"); } else{ this.Parameters.Set("d-qop",value); } } } /// <summary> /// Gets or sets 'd-ver' parameter value. Value null means not specified. /// </summary> public string D_Ver { get{ SIP_Parameter parameter = this.Parameters["d-ver"]; if(parameter != null){ return parameter.Value; } else{ return null; } } set{ if(string.IsNullOrEmpty(value)){ this.Parameters.Remove("d-ver"); } else{ this.Parameters.Set("d-ver",value); } } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; using System.ServiceModel.Channels; using System.Threading.Tasks; using SessionIdleManager = System.ServiceModel.Channels.ServiceChannel.SessionIdleManager; namespace System.ServiceModel.Dispatcher { internal class ListenerHandler : CommunicationObject { private static Action<object> s_initiateChannelPump = new Action<object>(ListenerHandler.InitiateChannelPump); private static AsyncCallback s_waitCallback = Fx.ThunkCallback(new AsyncCallback(ListenerHandler.WaitCallback)); private readonly ChannelDispatcher _channelDispatcher; private ListenerChannel _channel; private SessionIdleManager _idleManager; private bool _acceptedNull; private bool _doneAccepting; private EndpointDispatcherTable _endpoints; private readonly IListenerBinder _listenerBinder; private IDefaultCommunicationTimeouts _timeouts; internal ListenerHandler(IListenerBinder listenerBinder, ChannelDispatcher channelDispatcher, IDefaultCommunicationTimeouts timeouts) { _listenerBinder = listenerBinder; if (!((_listenerBinder != null))) { Fx.Assert("ListenerHandler.ctor: (this.listenerBinder != null)"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("listenerBinder"); } _channelDispatcher = channelDispatcher; if (!((_channelDispatcher != null))) { Fx.Assert("ListenerHandler.ctor: (this.channelDispatcher != null)"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher"); } _timeouts = timeouts; _endpoints = channelDispatcher.EndpointDispatcherTable; } internal ChannelDispatcher ChannelDispatcher { get { return _channelDispatcher; } } internal ListenerChannel Channel { get { return _channel; } } protected override TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } protected override TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } internal EndpointDispatcherTable Endpoints { get { return _endpoints; } set { _endpoints = value; } } new internal object ThisLock { get { return base.ThisLock; } } protected internal override Task OnCloseAsync(TimeSpan timeout) { this.OnClose(timeout); return TaskHelpers.CompletedTask(); } protected internal override Task OnOpenAsync(TimeSpan timeout) { this.OnOpen(timeout); return TaskHelpers.CompletedTask(); } protected override void OnOpen(TimeSpan timeout) { } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new CompletedAsyncResult(callback, state); } protected override void OnEndOpen(IAsyncResult result) { CompletedAsyncResult.End(result); } protected override void OnOpened() { base.OnOpened(); _channelDispatcher.Channels.IncrementActivityCount(); NewChannelPump(); } internal void NewChannelPump() { ActionItem.Schedule(ListenerHandler.s_initiateChannelPump, this); } private static void InitiateChannelPump(object state) { ListenerHandler listenerHandler = state as ListenerHandler; listenerHandler.ChannelPump(); } private void ChannelPump() { IChannelListener listener = _listenerBinder.Listener; for (; ;) { if (_acceptedNull || (listener.State == CommunicationState.Faulted)) { this.DoneAccepting(); break; } this.Dispatch(); } } private static void WaitCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; }; ListenerHandler listenerHandler = (ListenerHandler)result.AsyncState; IChannelListener listener = listenerHandler._listenerBinder.Listener; listenerHandler.Dispatch(); } private void AbortChannels() { IChannel[] channels = _channelDispatcher.Channels.ToArray(); for (int index = 0; index < channels.Length; index++) { channels[index].Abort(); } } private void CloseChannel(IChannel channel, TimeSpan timeout) { try { if (channel.State != CommunicationState.Closing && channel.State != CommunicationState.Closed) { CloseChannelState state = new CloseChannelState(this, channel); if (channel is ISessionChannel<IDuplexSession>) { IDuplexSession duplexSession = ((ISessionChannel<IDuplexSession>)channel).Session; IAsyncResult result = duplexSession.BeginCloseOutputSession(timeout, Fx.ThunkCallback(new AsyncCallback(CloseOutputSessionCallback)), state); if (result.CompletedSynchronously) duplexSession.EndCloseOutputSession(result); } else { IAsyncResult result = channel.BeginClose(timeout, Fx.ThunkCallback(new AsyncCallback(CloseChannelCallback)), state); if (result.CompletedSynchronously) channel.EndClose(result); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.HandleError(e); if (channel is ISessionChannel<IDuplexSession>) { channel.Abort(); } } } private static void CloseChannelCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } CloseChannelState state = (CloseChannelState)result.AsyncState; try { state.Channel.EndClose(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } state.ListenerHandler.HandleError(e); } } public void CloseInput(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // Close all datagram channels IChannel[] channels = _channelDispatcher.Channels.ToArray(); for (int index = 0; index < channels.Length; index++) { IChannel channel = channels[index]; if (!this.IsSessionChannel(channel)) { try { channel.Close(timeoutHelper.RemainingTime()); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.HandleError(e); } } } } private static void CloseOutputSessionCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } CloseChannelState state = (CloseChannelState)result.AsyncState; try { ((ISessionChannel<IDuplexSession>)state.Channel).Session.EndCloseOutputSession(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } state.ListenerHandler.HandleError(e); state.Channel.Abort(); } } private void CloseChannels(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); IChannel[] channels = _channelDispatcher.Channels.ToArray(); for (int index = 0; index < channels.Length; index++) CloseChannel(channels[index], timeoutHelper.RemainingTime()); } private void Dispatch() { ListenerChannel channel = _channel; SessionIdleManager idleManager = _idleManager; _channel = null; _idleManager = null; try { if (channel != null) { ChannelHandler handler = new ChannelHandler(_listenerBinder.MessageVersion, channel.Binder, this, idleManager); if (!channel.Binder.HasSession) { _channelDispatcher.Channels.Add(channel.Binder.Channel); } if (channel.Binder is DuplexChannelBinder) { DuplexChannelBinder duplexChannelBinder = channel.Binder as DuplexChannelBinder; duplexChannelBinder.ChannelHandler = handler; duplexChannelBinder.DefaultCloseTimeout = this.DefaultCloseTimeout; if (_timeouts == null) duplexChannelBinder.DefaultSendTimeout = ServiceDefaults.SendTimeout; else duplexChannelBinder.DefaultSendTimeout = _timeouts.SendTimeout; } ChannelHandler.Register(handler); channel = null; idleManager = null; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.HandleError(e); } finally { if (channel != null) { channel.Binder.Channel.Abort(); if (idleManager != null) { idleManager.CancelTimer(); } } } } private void AcceptedNull() { _acceptedNull = true; } private void DoneAccepting() { lock (this.ThisLock) { if (!_doneAccepting) { _doneAccepting = true; _channelDispatcher.Channels.DecrementActivityCount(); } } } private bool IsSessionChannel(IChannel channel) { return (channel is ISessionChannel<IDuplexSession> || channel is ISessionChannel<IInputSession> || channel is ISessionChannel<IOutputSession>); } private void CancelPendingIdleManager() { SessionIdleManager idleManager = _idleManager; if (idleManager != null) { idleManager.CancelTimer(); } } protected override void OnAbort() { // if there's an idle manager that has not been transferred to the channel handler, cancel it CancelPendingIdleManager(); // Start aborting incoming channels _channelDispatcher.Channels.CloseInput(); // Abort existing channels this.AbortChannels(); // Wait for channels to finish aborting _channelDispatcher.Channels.Abort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // if there's an idle manager that has not been cancelled, cancel it CancelPendingIdleManager(); // Start aborting incoming channels _channelDispatcher.Channels.CloseInput(); // Start closing existing channels this.CloseChannels(timeoutHelper.RemainingTime()); // Wait for channels to finish closing return _channelDispatcher.Channels.BeginClose(timeoutHelper.RemainingTime(), callback, state); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // if there's an idle manager that has not been cancelled, cancel it CancelPendingIdleManager(); // Start aborting incoming channels _channelDispatcher.Channels.CloseInput(); // Start closing existing channels this.CloseChannels(timeoutHelper.RemainingTime()); // Wait for channels to finish closing _channelDispatcher.Channels.Close(timeoutHelper.RemainingTime()); } protected override void OnEndClose(IAsyncResult result) { _channelDispatcher.Channels.EndClose(result); } private bool HandleError(Exception e) { return _channelDispatcher.HandleError(e); } internal class CloseChannelState { private ListenerHandler _listenerHandler; private IChannel _channel; internal CloseChannelState(ListenerHandler listenerHandler, IChannel channel) { _listenerHandler = listenerHandler; _channel = channel; } internal ListenerHandler ListenerHandler { get { return _listenerHandler; } } internal IChannel Channel { get { return _channel; } } } } internal class ListenerChannel { private IChannelBinder _binder; public ListenerChannel(IChannelBinder binder) { _binder = binder; } public IChannelBinder Binder { get { return _binder; } } } }
using System; using FluentScheduler.Model; using Moq; using NUnit.Framework; namespace FluentScheduler.Tests.UnitTests.ScheduleTests { [TestFixture] public class WeeksTests { [Test] public void Should_Add_Specified_Weeks_To_Next_Run_Date() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks(); var input = new DateTime(2000, 1, 1); var scheduledTime = schedule.CalculateNextRun(input); var expectedTime = new DateTime(2000, 1, 15); Assert.AreEqual(scheduledTime, expectedTime); } [Test] public void Should_Default_To_00_00_If_At_Is_Not_Defined() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks(); var input = new DateTime(2000, 1, 1, 1, 23, 25); var scheduledTime = schedule.CalculateNextRun(input); Assert.AreEqual(scheduledTime.Hour, 0); Assert.AreEqual(scheduledTime.Minute, 0); Assert.AreEqual(scheduledTime.Second, 0); } [Test] public void Should_Set_Specific_Hour_And_Minute_If_At_Method_Is_Called() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().At(3, 15); var input = new DateTime(2000, 1, 1); var scheduledTime = schedule.CalculateNextRun(input); Assert.AreEqual(scheduledTime.Date, input.Date); Assert.AreEqual(scheduledTime.Hour, 3); Assert.AreEqual(scheduledTime.Minute, 15); Assert.AreEqual(scheduledTime.Second, 0); } [Test] public void Should_Override_Existing_Minutes_And_Seconds_If_At_Method_Is_Called() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().At(3, 15); var input = new DateTime(2000, 1, 1, 5, 23, 25); var scheduledTime = schedule.CalculateNextRun(input); Assert.AreEqual(scheduledTime.Date, input.Date.AddDays(14)); Assert.AreEqual(scheduledTime.Hour, 3); Assert.AreEqual(scheduledTime.Minute, 15); Assert.AreEqual(scheduledTime.Second, 0); } [Test] public void Should_Default_To_00_00_If_On_Is_Specified_And_At_Is_Not_Defined() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().On(DayOfWeek.Saturday); var input = new DateTime(2000, 1, 1, 1, 23, 25); var scheduledTime = schedule.CalculateNextRun(input); Assert.AreEqual(scheduledTime.Hour, 0); Assert.AreEqual(scheduledTime.Minute, 0); Assert.AreEqual(scheduledTime.Second, 0); } [Test] public void Should_Set_Specific_Hour_And_Minute_If_On_Is_Specified_And_At_Method_Is_Called() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().On(DayOfWeek.Saturday).At(3, 15); var input = new DateTime(2000, 1, 1); var scheduledTime = schedule.CalculateNextRun(input); Assert.AreEqual(scheduledTime.Date, input.Date.AddDays(14)); Assert.AreEqual(scheduledTime.Hour, 3); Assert.AreEqual(scheduledTime.Minute, 15); Assert.AreEqual(scheduledTime.Second, 0); } [Test] public void Should_Override_Existing_Minutes_And_Seconds_If_On_Is_Specified_And_At_Method_Is_Called() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().On(DayOfWeek.Saturday).At(3, 15); var input = new DateTime(2000, 1, 1, 1, 23, 25); var scheduledTime = schedule.CalculateNextRun(input); Assert.AreEqual(scheduledTime.Date, input.Date.AddDays(14)); Assert.AreEqual(scheduledTime.Hour, 3); Assert.AreEqual(scheduledTime.Minute, 15); Assert.AreEqual(scheduledTime.Second, 0); } [Test] public void Should_Select_The_Date_If_The_Next_Runtime_Falls_On_The_Specified_Day() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().On(DayOfWeek.Saturday); var input = new DateTime(2000, 1, 1); // Saturday var scheduledTime = schedule.CalculateNextRun(input); var expectedTime = new DateTime(2000, 1, 15); Assert.AreEqual(scheduledTime, expectedTime); } [Test] public void Should_Pick_The_Day_Of_Week_Specified() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().On(DayOfWeek.Sunday); var input = new DateTime(2000, 1, 1); var scheduledTime = schedule.CalculateNextRun(input); var expectedTime = new DateTime(2000, 1, 16); Assert.AreEqual(scheduledTime, expectedTime); } [Test] public void Should_Pick_The_Next_Week_If_The_Day_Of_Week_Has_Passed() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().On(DayOfWeek.Monday); var input = new DateTime(2000, 1, 5); // Wednesday var scheduledTime = schedule.CalculateNextRun(input); var expectedTime = new DateTime(2000, 1, 24); Assert.AreEqual(scheduledTime, expectedTime); } [Test] public void Should_Pick_The_Next_Week_If_The_Day_Of_Week_Has_Passed_For_New_Weeks() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().On(DayOfWeek.Saturday); var input = new DateTime(2000, 1, 2); // Sunday var scheduledTime = schedule.CalculateNextRun(input); var expectedTime = new DateTime(2000, 1, 22); Assert.AreEqual(scheduledTime, expectedTime); } [Test] public void Should_Pick_The_Next_Week_If_The_Day_Of_Week_Has_Passed_For_End_Of_Week() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().On(DayOfWeek.Sunday); var input = new DateTime(2000, 1, 1); // Saturday var scheduledTime = schedule.CalculateNextRun(input); var expectedTime = new DateTime(2000, 1, 16); Assert.AreEqual(scheduledTime, expectedTime); } [Test] public void Should_Pick_The_Next_Day_Of_Week_If_0_Weeks_Specified() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(0).Weeks().On(DayOfWeek.Wednesday); var input = new DateTime(2000, 1, 4); // Tuesday var scheduledTime = schedule.CalculateNextRun(input); var expectedTime = new DateTime(2000, 1, 5); Assert.AreEqual(scheduledTime, expectedTime); } [Test] public void Should_Pick_The_Next_Week_On_The_Specified_Day_Of_Week_If_0_Weeks_Specified() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(0).Weeks().On(DayOfWeek.Tuesday); var input = new DateTime(2000, 1, 4, 1, 23, 25); // Tuesday var scheduledTime = schedule.CalculateNextRun(input); var expectedTime = new DateTime(2000, 1, 11); Assert.AreEqual(scheduledTime, expectedTime); } [Test] public void Should_Pick_The_Same_Day_Of_Week_If_0_Weeks_Specified_And_Before_Specified_Run_Time() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(0).Weeks().On(DayOfWeek.Tuesday).At(4, 20); var input = new DateTime(2000, 1, 4, 3, 15, 0); // Tuesday var scheduledTime = schedule.CalculateNextRun(input); var expectedTime = new DateTime(2000, 1, 4, 4, 20, 0); Assert.AreEqual(scheduledTime, expectedTime); } [Test] public void Should_Schedule_Today_If_Input_Time_Is_Before_Run_Time() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().At(3, 15); var input = new DateTime(2000, 1, 1); var scheduledTime = schedule.CalculateNextRun(input); Assert.AreEqual(scheduledTime.Date, input.Date); Assert.AreEqual(scheduledTime.Hour, 3); Assert.AreEqual(scheduledTime.Minute, 15); Assert.AreEqual(scheduledTime.Second, 0); } [Test] public void Should_Not_Schedule_Today_If_Input_Time_Is_After_Run_Time() { var task = new Mock<ITask>(); var schedule = new Schedule(task.Object); schedule.ToRunEvery(2).Weeks().At(3, 15); var input = new DateTime(2000, 1, 1, 5, 23, 25); var scheduledTime = schedule.CalculateNextRun(input); Assert.AreEqual(scheduledTime.Date, input.Date.AddDays(14)); Assert.AreEqual(scheduledTime.Hour, 3); Assert.AreEqual(scheduledTime.Minute, 15); Assert.AreEqual(scheduledTime.Second, 0); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Python.Runtime { /// <summary> /// A MethodBinder encapsulates information about a (possibly overloaded) /// managed method, and is responsible for selecting the right method given /// a set of Python arguments. This is also used as a base class for the /// ConstructorBinder, a minor variation used to invoke constructors. /// </summary> [Serializable] internal class MethodBinder { private List<MethodInformation> list; private static Dictionary<string, MethodInfo> _resolvedGenericsCache = new(); public const bool DefaultAllowThreads = true; public bool allow_threads = DefaultAllowThreads; public bool init = false; internal MethodBinder() { list = new List<MethodInformation>(); } internal MethodBinder(MethodInfo mi) { list = new List<MethodInformation> { new MethodInformation(mi, mi.GetParameters()) }; } public int Count { get { return list.Count; } } internal void AddMethod(MethodBase m) { // we added a new method so we have to re sort the method list init = false; list.Add(new MethodInformation(m, m.GetParameters())); } /// <summary> /// Given a sequence of MethodInfo and a sequence of types, return the /// MethodInfo that matches the signature represented by those types. /// </summary> internal static MethodInfo MatchSignature(MethodInfo[] mi, Type[] tp) { if (tp == null) { return null; } int count = tp.Length; for (var i = 0; i < mi.Length; i++) { var t = mi[i]; ParameterInfo[] pi = t.GetParameters(); if (pi.Length != count) { continue; } for (var n = 0; n < pi.Length; n++) { if (tp[n] != pi[n].ParameterType) { break; } if (n == pi.Length - 1) { return t; } } } return null; } /// <summary> /// Given a sequence of MethodInfo and a sequence of type parameters, /// return the MethodInfo that represents the matching closed generic. /// </summary> internal static MethodInfo MatchParameters(MethodInfo[] mi, Type[] tp) { if (tp == null) { return null; } int count = tp.Length; for (var i = 0; i < mi.Length; i++) { var t = mi[i]; if (!t.IsGenericMethodDefinition) { continue; } Type[] args = t.GetGenericArguments(); if (args.Length != count) { continue; } try { // MakeGenericMethod can throw ArgumentException if the type parameters do not obey the constraints. MethodInfo method = t.MakeGenericMethod(tp); Exceptions.Clear(); return method; } catch (ArgumentException e) { Exceptions.SetError(e); // The error will remain set until cleared by a successful match. } } return null; } // Given a generic method and the argsTypes previously matched with it, // generate the matching method internal static MethodInfo ResolveGenericMethod(MethodInfo method, Object[] args) { // No need to resolve a method where generics are already assigned if(!method.ContainsGenericParameters){ return method; } bool shouldCache = method.DeclaringType != null; string key = null; // Check our resolved generics cache first if (shouldCache) { key = method.DeclaringType.AssemblyQualifiedName + method.ToString() + string.Join(",", args.Select(x => x?.GetType())); if (_resolvedGenericsCache.TryGetValue(key, out var cachedMethod)) { return cachedMethod; } } // Get our matching generic types to create our method var methodGenerics = method.GetGenericArguments().Where(x => x.IsGenericParameter).ToArray(); var resolvedGenericsTypes = new Type[methodGenerics.Length]; int resolvedGenerics = 0; var parameters = method.GetParameters(); // Iterate to length of ArgTypes since default args are plausible for (int k = 0; k < args.Length; k++) { if(args[k] == null){ continue; } var argType = args[k].GetType(); var parameterType = parameters[k].ParameterType; // Ignore those without generic params if (!parameterType.ContainsGenericParameters) { continue; } // The parameters generic definition var paramGenericDefinition = parameterType.GetGenericTypeDefinition(); // For the arg that matches this param index, determine the matching type for the generic var currentType = argType; while (currentType != null) { // Check the current type for generic type definition var genericType = currentType.IsGenericType ? currentType.GetGenericTypeDefinition() : null; // If the generic type matches our params generic definition, this is our match // go ahead and match these types to this arg if (paramGenericDefinition == genericType) { // The matching generic for this method parameter var paramGenerics = parameterType.GenericTypeArguments; var argGenericsResolved = currentType.GenericTypeArguments; for (int j = 0; j < paramGenerics.Length; j++) { // Get the final matching index for our resolved types array for this params generic var index = Array.IndexOf(methodGenerics, paramGenerics[j]); if (resolvedGenericsTypes[index] == null) { // Add it, and increment our count resolvedGenericsTypes[index] = argGenericsResolved[j]; resolvedGenerics++; } else if (resolvedGenericsTypes[index] != argGenericsResolved[j]) { // If we have two resolved types for the same generic we have a problem throw new ArgumentException("ResolveGenericMethod(): Generic method mismatch on argument types"); } } break; } // Step up the inheritance tree currentType = currentType.BaseType; } } try { if (resolvedGenerics != methodGenerics.Length) { throw new Exception($"ResolveGenericMethod(): Count of resolved generics {resolvedGenerics} does not match method generic count {methodGenerics.Length}."); } method = method.MakeGenericMethod(resolvedGenericsTypes); if (shouldCache) { // Add to cache _resolvedGenericsCache.Add(key, method); } } catch (ArgumentException e) { // Will throw argument exception if improperly matched Exceptions.SetError(e); } return method; } /// <summary> /// Given a sequence of MethodInfo and two sequences of type parameters, /// return the MethodInfo that matches the signature and the closed generic. /// </summary> internal static MethodInfo MatchSignatureAndParameters(MethodInfo[] mi, Type[] genericTp, Type[] sigTp) { if (genericTp == null || sigTp == null) { return null; } int genericCount = genericTp.Length; int signatureCount = sigTp.Length; for (var i = 0; i < mi.Length; i++) { var t = mi[i]; if (!t.IsGenericMethodDefinition) { continue; } Type[] genericArgs = t.GetGenericArguments(); if (genericArgs.Length != genericCount) { continue; } ParameterInfo[] pi = t.GetParameters(); if (pi.Length != signatureCount) { continue; } for (var n = 0; n < pi.Length; n++) { if (sigTp[n] != pi[n].ParameterType) { break; } if (n == pi.Length - 1) { MethodInfo match = t; if (match.IsGenericMethodDefinition) { // FIXME: typeArgs not used Type[] typeArgs = match.GetGenericArguments(); return match.MakeGenericMethod(genericTp); } return match; } } } return null; } /// <summary> /// Return the array of MethodInfo for this method. The result array /// is arranged in order of precedence (done lazily to avoid doing it /// at all for methods that are never called). /// </summary> internal List<MethodInformation> GetMethods() { if (!init) { // I'm sure this could be made more efficient. list.Sort(new MethodSorter()); init = true; } return list; } /// <summary> /// Precedence algorithm largely lifted from Jython - the concerns are /// generally the same so we'll start with this and tweak as necessary. /// </summary> /// <remarks> /// Based from Jython `org.python.core.ReflectedArgs.precedence` /// See: https://github.com/jythontools/jython/blob/master/src/org/python/core/ReflectedArgs.java#L192 /// </remarks> private static int GetPrecedence(MethodInformation methodInformation) { ParameterInfo[] pi = methodInformation.ParameterInfo; var mi = methodInformation.MethodBase; int val = mi.IsStatic ? 3000 : 0; int num = pi.Length; val += mi.IsGenericMethod ? 1 : 0; for (var i = 0; i < num; i++) { val += ArgPrecedence(pi[i].ParameterType, methodInformation); } var info = mi as MethodInfo; if (info != null) { val += ArgPrecedence(info.ReturnType, methodInformation); val += mi.DeclaringType == mi.ReflectedType ? 0 : 3000; } return val; } /// <summary> /// Return a precedence value for a particular Type object. /// </summary> internal static int ArgPrecedence(Type t, MethodInformation mi) { Type objectType = typeof(object); if (t == objectType) { return 3000; } if (t.IsAssignableFrom(typeof(PyObject)) && !OperatorMethod.IsOperatorMethod(mi.MethodBase)) { return -1; } TypeCode tc = Type.GetTypeCode(t); // TODO: Clean up switch (tc) { case TypeCode.Object: return 1; // we place higher precision methods at the top case TypeCode.Decimal: return 2; case TypeCode.Double: return 3; case TypeCode.Single: return 4; case TypeCode.Int64: return 21; case TypeCode.Int32: return 22; case TypeCode.Int16: return 23; case TypeCode.UInt64: return 24; case TypeCode.UInt32: return 25; case TypeCode.UInt16: return 26; case TypeCode.Char: return 27; case TypeCode.Byte: return 28; case TypeCode.SByte: return 29; case TypeCode.String: return 30; case TypeCode.Boolean: return 40; } if (t.IsArray) { Type e = t.GetElementType(); if (e == objectType) { return 2500; } return 100 + ArgPrecedence(e, mi); } return 2000; } /// <summary> /// Bind the given Python instance and arguments to a particular method /// overload and return a structure that contains the converted Python /// instance, converted arguments and the correct method to call. /// </summary> internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw) { return Bind(inst, args, kw, null, null); } internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) { return Bind(inst, args, kw, info, null); } internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo) { // Relevant function variables used post conversion Binding bindingUsingImplicitConversion = null; Binding genericBinding = null; // If we have KWArgs create dictionary and collect them Dictionary<string, IntPtr> kwArgDict = null; if (kw != IntPtr.Zero) { var pyKwArgsCount = (int)Runtime.PyDict_Size(kw); kwArgDict = new Dictionary<string, IntPtr>(pyKwArgsCount); IntPtr keylist = Runtime.PyDict_Keys(kw); IntPtr valueList = Runtime.PyDict_Values(kw); for (int i = 0; i < pyKwArgsCount; ++i) { var keyStr = Runtime.GetManagedString(Runtime.PyList_GetItem(new BorrowedReference(keylist), i)); kwArgDict[keyStr] = Runtime.PyList_GetItem(new BorrowedReference(valueList), i).DangerousGetAddress(); } Runtime.XDecref(keylist); Runtime.XDecref(valueList); } // Fetch our methods we are going to attempt to match and bind too. var methods = info == null ? GetMethods() : new List<MethodInformation>(1) { new MethodInformation(info, info.GetParameters()) }; for (var i = 0; i < methods.Count; i++) { var methodInformation = methods[i]; // Relevant method variables var mi = methodInformation.MethodBase; var pi = methodInformation.ParameterInfo; int pyArgCount = (int)Runtime.PyTuple_Size(args); // Special case for operators bool isOperator = OperatorMethod.IsOperatorMethod(mi); // Binary operator methods will have 2 CLR args but only one Python arg // (unary operators will have 1 less each), since Python operator methods are bound. isOperator = isOperator && pyArgCount == pi.Length - 1; bool isReverse = isOperator && OperatorMethod.IsReverse((MethodInfo)mi); // Only cast if isOperator. if (isReverse && OperatorMethod.IsComparisonOp((MethodInfo)mi)) continue; // Comparison operators in Python have no reverse mode. // Preprocessing pi to remove either the first or second argument. if (isOperator && !isReverse) { // The first Python arg is the right operand, while the bound instance is the left. // We need to skip the first (left operand) CLR argument. pi = pi.Skip(1).ToArray(); } else if (isOperator && isReverse) { // The first Python arg is the left operand. // We need to take the first CLR argument. pi = pi.Take(1).ToArray(); } // Must be done after IsOperator section int clrArgCount = pi.Length; if (CheckMethodArgumentsMatch(clrArgCount, pyArgCount, kwArgDict, pi, out bool paramsArray, out ArrayList defaultArgList)) { var outs = 0; var margs = new object[clrArgCount]; int paramsArrayIndex = paramsArray ? pi.Length - 1 : -1; // -1 indicates no paramsArray var usedImplicitConversion = false; // Conversion loop for each parameter for (int paramIndex = 0; paramIndex < clrArgCount; paramIndex++) { IntPtr op = IntPtr.Zero; // Python object to be converted; not yet set var parameter = pi[paramIndex]; // Clr parameter we are targeting object arg; // Python -> Clr argument // Check our KWargs for this parameter bool hasNamedParam = kwArgDict == null ? false : kwArgDict.TryGetValue(parameter.Name, out op); bool isNewReference = false; // Check if we are going to use default if (paramIndex >= pyArgCount && !(hasNamedParam || (paramsArray && paramIndex == paramsArrayIndex))) { if (defaultArgList != null) { margs[paramIndex] = defaultArgList[paramIndex - pyArgCount]; } continue; } // At this point, if op is IntPtr.Zero we don't have a KWArg and are not using default if (op == IntPtr.Zero) { // If we have reached the paramIndex if (paramsArrayIndex == paramIndex) { op = HandleParamsArray(args, paramsArrayIndex, pyArgCount, out isNewReference); } else { op = Runtime.PyTuple_GetItem(args, paramIndex); } } // this logic below handles cases when multiple overloading methods // are ambiguous, hence comparison between Python and CLR types // is necessary Type clrtype = null; IntPtr pyoptype; if (methods.Count > 1) { pyoptype = IntPtr.Zero; pyoptype = Runtime.PyObject_Type(op); Exceptions.Clear(); if (pyoptype != IntPtr.Zero) { clrtype = Converter.GetTypeByAlias(pyoptype); } Runtime.XDecref(pyoptype); } if (clrtype != null) { var typematch = false; if ((parameter.ParameterType != typeof(object)) && (parameter.ParameterType != clrtype)) { IntPtr pytype = Converter.GetPythonTypeByAlias(parameter.ParameterType); pyoptype = Runtime.PyObject_Type(op); Exceptions.Clear(); if (pyoptype != IntPtr.Zero) { if (pytype != pyoptype) { typematch = false; } else { typematch = true; clrtype = parameter.ParameterType; } } if (!typematch) { // this takes care of nullables var underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType); if (underlyingType == null) { underlyingType = parameter.ParameterType; } // this takes care of enum values TypeCode argtypecode = Type.GetTypeCode(underlyingType); TypeCode paramtypecode = Type.GetTypeCode(clrtype); if (argtypecode == paramtypecode) { typematch = true; clrtype = parameter.ParameterType; } // lets just keep the first binding using implicit conversion // this is to respect method order/precedence else if (bindingUsingImplicitConversion == null) { // accepts non-decimal numbers in decimal parameters if (underlyingType == typeof(decimal)) { clrtype = parameter.ParameterType; usedImplicitConversion |= typematch = Converter.ToManaged(op, clrtype, out arg, false); } if (!typematch) { // this takes care of implicit conversions var opImplicit = parameter.ParameterType.GetMethod("op_Implicit", new[] { clrtype }); if (opImplicit != null) { usedImplicitConversion |= typematch = opImplicit.ReturnType == parameter.ParameterType; clrtype = parameter.ParameterType; } } } } Runtime.XDecref(pyoptype); if (!typematch) { margs = null; break; } } else { clrtype = parameter.ParameterType; } } else { clrtype = parameter.ParameterType; } if (parameter.IsOut || clrtype.IsByRef) { outs++; } if (!Converter.ToManaged(op, clrtype, out arg, false)) { margs = null; break; } if (isNewReference) { // TODO: is this a bug? Should this happen even if the conversion fails? // GetSlice() creates a new reference but GetItem() // returns only a borrow reference. Runtime.XDecref(op); } margs[paramIndex] = arg; } if (margs == null) { continue; } if (isOperator) { if (inst != IntPtr.Zero) { if (ManagedType.GetManagedObject(inst) is CLRObject co) { bool isUnary = pyArgCount == 0; // Postprocessing to extend margs. var margsTemp = isUnary ? new object[1] : new object[2]; // If reverse, the bound instance is the right operand. int boundOperandIndex = isReverse ? 1 : 0; // If reverse, the passed instance is the left operand. int passedOperandIndex = isReverse ? 0 : 1; margsTemp[boundOperandIndex] = co.inst; if (!isUnary) { margsTemp[passedOperandIndex] = margs[0]; } margs = margsTemp; } else continue; } } object target = null; if (!mi.IsStatic && inst != IntPtr.Zero) { //CLRObject co = (CLRObject)ManagedType.GetManagedObject(inst); // InvalidCastException: Unable to cast object of type // 'Python.Runtime.ClassObject' to type 'Python.Runtime.CLRObject' var co = ManagedType.GetManagedObject(inst) as CLRObject; // Sanity check: this ensures a graceful exit if someone does // something intentionally wrong like call a non-static method // on the class rather than on an instance of the class. // XXX maybe better to do this before all the other rigmarole. if (co == null) { return null; } target = co.inst; } // If this match is generic we need to resolve it with our types. // Store this generic match to be used if no others match if (mi.IsGenericMethod) { mi = ResolveGenericMethod((MethodInfo)mi, margs); genericBinding = new Binding(mi, target, margs, outs); continue; } var binding = new Binding(mi, target, margs, outs); if (usedImplicitConversion) { // in this case we will not return the binding yet in case there is a match // which does not use implicit conversions, which will return directly bindingUsingImplicitConversion = binding; } else { return binding; } } } // if we generated a binding using implicit conversion return it if (bindingUsingImplicitConversion != null) { return bindingUsingImplicitConversion; } // if we generated a generic binding, return it if (genericBinding != null) { return genericBinding; } return null; } static IntPtr HandleParamsArray(IntPtr args, int arrayStart, int pyArgCount, out bool isNewReference) { isNewReference = false; IntPtr op; // for a params method, we may have a sequence or single/multiple items // here we look to see if the item at the paramIndex is there or not // and then if it is a sequence itself. if ((pyArgCount - arrayStart) == 1) { // Ee only have one argument left, so we need to check to see if it is a sequence or a single item // We also need to check if this object is possibly a wrapped C# Enumerable Object IntPtr item = Runtime.PyTuple_GetItem(args, arrayStart); if (!Runtime.PyString_Check(item) && (Runtime.PySequence_Check(item) || (ManagedType.GetManagedObject(item) as CLRObject)?.inst is IEnumerable)) { // it's a sequence (and not a string), so we use it as the op op = item; } else { // Its a single value that needs to be converted into the params array isNewReference = true; op = Runtime.PyTuple_GetSlice(args, arrayStart, pyArgCount); } } else { // Its a set of individual values, so we grab them as a tuple to be converted into the params array isNewReference = true; op = Runtime.PyTuple_GetSlice(args, arrayStart, pyArgCount); } return op; } /// <summary> /// This helper method will perform an initial check to determine if we found a matching /// method based on its parameters count and type <see cref="Bind(IntPtr,IntPtr,IntPtr,MethodBase,MethodInfo[])"/> /// </summary> private bool CheckMethodArgumentsMatch(int clrArgCount, int pyArgCount, Dictionary<string, IntPtr> kwargDict, ParameterInfo[] parameterInfo, out bool paramsArray, out ArrayList defaultArgList) { var match = false; // Prepare our outputs defaultArgList = null; paramsArray = false; if (parameterInfo.Length > 0) { var lastParameterInfo = parameterInfo[parameterInfo.Length - 1]; if (lastParameterInfo.ParameterType.IsArray) { paramsArray = Attribute.IsDefined(lastParameterInfo, typeof(ParamArrayAttribute)); } } // First if we have anys kwargs, look at the function for matching args if (kwargDict != null && kwargDict.Count > 0) { // If the method doesn't have all of these kw args, it is not a match // Otherwise just continue on to see if it is a match if (!kwargDict.All(x => parameterInfo.Any(pi => x.Key == pi.Name))) { return false; } } // If they have the exact same amount of args they do match // Must check kwargs because it contains additional args if (pyArgCount == clrArgCount && (kwargDict == null || kwargDict.Count == 0)) { match = true; } else if (pyArgCount < clrArgCount) { // every parameter past 'pyArgCount' must have either // a corresponding keyword argument or a default parameter match = true; defaultArgList = new ArrayList(); for (var v = pyArgCount; v < clrArgCount && match; v++) { if (kwargDict != null && kwargDict.ContainsKey(parameterInfo[v].Name)) { // we have a keyword argument for this parameter, // no need to check for a default parameter, but put a null // placeholder in defaultArgList defaultArgList.Add(null); } else if (parameterInfo[v].IsOptional) { // IsOptional will be true if the parameter has a default value, // or if the parameter has the [Optional] attribute specified. if (parameterInfo[v].HasDefaultValue) { defaultArgList.Add(parameterInfo[v].DefaultValue); } else { // [OptionalAttribute] was specified for the parameter. // See https://stackoverflow.com/questions/3416216/optionalattribute-parameters-default-value // for rules on determining the value to pass to the parameter var type = parameterInfo[v].ParameterType; if (type == typeof(object)) defaultArgList.Add(Type.Missing); else if (type.IsValueType) defaultArgList.Add(Activator.CreateInstance(type)); else defaultArgList.Add(null); } } else if (!paramsArray) { // If there is no KWArg or Default value, then this isn't a match match = false; } } } else if (pyArgCount > clrArgCount && clrArgCount > 0 && paramsArray) { // This is a `foo(params object[] bar)` style method // We will handle the params later match = true; } return match; } internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw) { return Invoke(inst, args, kw, null, null); } internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) { return Invoke(inst, args, kw, info, null); } internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo) { Binding binding = Bind(inst, args, kw, info, methodinfo); object result; IntPtr ts = IntPtr.Zero; if (binding == null) { // If we already have an exception pending, don't create a new one if(!Exceptions.ErrorOccurred()){ var value = new StringBuilder("No method matches given arguments"); if (methodinfo != null && methodinfo.Length > 0) { value.Append($" for {methodinfo[0].Name}"); } else if (list.Count > 0) { value.Append($" for {list[0].MethodBase.Name}"); } value.Append(": "); AppendArgumentTypes(to: value, args); Exceptions.RaiseTypeError(value.ToString()); } return IntPtr.Zero; } if (allow_threads) { ts = PythonEngine.BeginAllowThreads(); } try { result = binding.info.Invoke(binding.inst, BindingFlags.Default, null, binding.args, null); } catch (Exception e) { if (e.InnerException != null) { e = e.InnerException; } if (allow_threads) { PythonEngine.EndAllowThreads(ts); } Exceptions.SetError(e); return IntPtr.Zero; } if (allow_threads) { PythonEngine.EndAllowThreads(ts); } // If there are out parameters, we return a tuple containing // the result followed by the out parameters. If there is only // one out parameter and the return type of the method is void, // we return the out parameter as the result to Python (for // code compatibility with ironpython). var mi = (MethodInfo)binding.info; if (binding.outs > 0) { ParameterInfo[] pi = mi.GetParameters(); int c = pi.Length; var n = 0; IntPtr t = Runtime.PyTuple_New(binding.outs + 1); IntPtr v = Converter.ToPython(result, mi.ReturnType); Runtime.PyTuple_SetItem(t, n, v); n++; for (var i = 0; i < c; i++) { Type pt = pi[i].ParameterType; if (pi[i].IsOut || pt.IsByRef) { v = Converter.ToPython(binding.args[i], pt); Runtime.PyTuple_SetItem(t, n, v); n++; } } if (binding.outs == 1 && mi.ReturnType == typeof(void)) { v = Runtime.PyTuple_GetItem(t, 1); Runtime.XIncref(v); Runtime.XDecref(t); return v; } return t; } return Converter.ToPython(result, mi.ReturnType); } /// <summary> /// Utility class to store the information about a <see cref="MethodBase"/> /// </summary> [Serializable] internal class MethodInformation { public MethodBase MethodBase { get; } public ParameterInfo[] ParameterInfo { get; } public MethodInformation(MethodBase methodBase, ParameterInfo[] parameterInfo) { MethodBase = methodBase; ParameterInfo = parameterInfo; } public override string ToString() { return MethodBase.ToString(); } } /// <summary> /// Utility class to sort method info by parameter type precedence. /// </summary> private class MethodSorter : IComparer<MethodInformation> { public int Compare(MethodInformation x, MethodInformation y) { int p1 = GetPrecedence(x); int p2 = GetPrecedence(y); if (p1 < p2) { return -1; } if (p1 > p2) { return 1; } return 0; } } protected static void AppendArgumentTypes(StringBuilder to, IntPtr args) { long argCount = Runtime.PyTuple_Size(args); to.Append("("); for (long argIndex = 0; argIndex < argCount; argIndex++) { var arg = Runtime.PyTuple_GetItem(args, argIndex); if (arg != IntPtr.Zero) { var type = Runtime.PyObject_Type(arg); if (type != IntPtr.Zero) { try { var description = Runtime.PyObject_Unicode(type); if (description != IntPtr.Zero) { to.Append(Runtime.GetManagedSpan(description, out var newReference)); newReference.Dispose(); Runtime.XDecref(description); } } finally { Runtime.XDecref(type); } } } if (argIndex + 1 < argCount) to.Append(", "); } to.Append(')'); } } /// <summary> /// A Binding is a utility instance that bundles together a MethodInfo /// representing a method to call, a (possibly null) target instance for /// the call, and the arguments for the call (all as managed values). /// </summary> internal class Binding { public MethodBase info; public object[] args; public object inst; public int outs; internal Binding(MethodBase info, object inst, object[] args, int outs) { this.info = info; this.inst = inst; this.args = args; this.outs = outs; } } }
/// 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: <quad name=NAME size=25 width=1 /> [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; public override void SetVerticesDirty() { base.SetVerticesDirty(); UpdateQuadImage(); } #if UNITY_EDITOR protected override void OnValidate() { base.OnValidate(); UpdateQuadImage(); } #endif /// <summary> /// After parsing the final text /// </summary> private string m_OutputText; [System.Serializable] public struct IconName { public string name; public Sprite sprite; } public IconName[] inspectorIconList; private Dictionary<string, Sprite> iconList = new Dictionary<string, Sprite>(); 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; //Commented out as private and not used.. Yet? //private bool selected = false; private List<Vector2> positions = new List<Vector2>(); /** * Little heck to support multiple hrefs with same name */ private string previousText = ""; public bool isCreating_m_HrefInfos = true; /** * Unity Inspector cant display Dictionary vars, * so we use this little hack to setup the iconList */ new void Start() { button = GetComponent<Button>(); if (inspectorIconList != null && inspectorIconList.Length > 0) { foreach (IconName icon in inspectorIconList) { // Debug.Log(icon.sprite.name); iconList.Add(icon.name, icon.sprite); } } Reset_m_HrefInfos (); } protected void UpdateQuadImage() { #if UNITY_EDITOR if (UnityEditor.PrefabUtility.GetPrefabType(this) == UnityEditor.PrefabType.Prefab) { return; } #endif m_OutputText = GetOutputText(); m_ImagesVertexIndex.Clear(); foreach (Match match in s_Regex.Matches(m_OutputText)) { var picIndex = match.Index; var endIndex = picIndex * 4 + 3; m_ImagesVertexIndex.Add(endIndex); m_ImagesPool.RemoveAll(image => image == null); if (m_ImagesPool.Count == 0) { GetComponentsInChildren<Image>(m_ImagesPool); } if (m_ImagesVertexIndex.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.localPosition = Vector3.zero; rt.localRotation = Quaternion.identity; rt.localScale = Vector3.one; } m_ImagesPool.Add(go.GetComponent<Image>()); } var spriteName = match.Groups[1].Value; //var size = float.Parse(match.Groups[2].Value); var img = m_ImagesPool[m_ImagesVertexIndex.Count - 1]; if (img.sprite == null || img.sprite.name != spriteName) { // img.sprite = Resources.Load<Sprite>(spriteName); if (inspectorIconList != null && inspectorIconList.Length > 0) { foreach (IconName icon in inspectorIconList) { if (icon.name == spriteName) { img.sprite = icon.sprite; break; } } } } img.rectTransform.sizeDelta = new Vector2(fontSize * ImageScalingFactor, fontSize * ImageScalingFactor); img.enabled = true; if (positions.Count == m_ImagesPool.Count) { img.rectTransform.anchoredPosition = positions[m_ImagesVertexIndex.Count - 1]; } } for (var i = m_ImagesVertexIndex.Count; i < m_ImagesPool.Count; i++) { if (m_ImagesPool[i]) { /* TEMPORARY FIX REMOVE IMAGES FROM POOL DELETE LATER SINCE CANNOT DESTROY */ // m_ImagesPool[i].enabled = false; m_ImagesPool[i].gameObject.SetActive(false); m_ImagesPool[i].gameObject.hideFlags = HideFlags.HideAndDontSave; culled_ImagesPool.Add(m_ImagesPool[i].gameObject); m_ImagesPool.Remove(m_ImagesPool[i]); } } if (culled_ImagesPool.Count > 1) { 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]; var rt = m_ImagesPool[i].rectTransform; var size = rt.sizeDelta; if (endIndex < toFill.currentVertCount) { toFill.PopulateUIVertex(ref vert, endIndex); positions.Add(new Vector2((vert.position.x + size.x / 2), (vert.position.y + size.y / 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); } } } if (m_ImagesVertexIndex.Count != 0) { m_ImagesVertexIndex.Clear(); } // 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; if (pos.x < bounds.min.x) // Wrap re-add surround frame { 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)); } UpdateQuadImage(); } /// <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 (icon.name != null && 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)); return s_TextBuilder.ToString(); } /// <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) { //do your stuff when highlighted //selected = true; 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) { //do your stuff when highlighted //selected = false; 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) { //do your stuff when selected //selected = true; if (m_ImagesPool.Count >= 1) { foreach (Image img in m_ImagesPool) { if (button != null && button.isActiveAndEnabled) { img.color = button.colors.highlightedColor; } } } } /// <summary> /// Hyperlinks Info /// </summary> private class HrefInfo { public int startIndex; public int endIndex; public string name; public readonly List<Rect> boxes = new List<Rect>(); } /* TEMPORARY FIX REMOVE IMAGES FROM POOL DELETE LATER SINCE CANNOT DESTROY */ void Update() { lock (thisLock) { if (clearImages) { for (int i = 0; i < culled_ImagesPool.Count; i++){ DestroyImmediate(culled_ImagesPool[i]); } culled_ImagesPool.Clear(); clearImages = false; } } if( previousText != text) Reset_m_HrefInfos (); } // Reseting m_HrefInfos array if there is any change in text void Reset_m_HrefInfos () { previousText = text; m_HrefInfos.Clear(); isCreating_m_HrefInfos = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans; namespace Tester.AzureUtils.Utilities { /// <summary> /// A helper utility class that allows to control the rate of generation of asynchronous activities. /// Maintains a pipeline of asynchronous operations up to a given maximal capacity and blocks the calling thread if the pipeline /// gets too deep before enqueued operations are not finished. /// Effectively adds a back-pressure to the caller. /// This is mainly useful for stress-testing grains under controlled load and should never be used from within a grain code! /// </summary> public class AsyncPipeline { /// <summary> /// The Default Capacity of this AsyncPipeline. Equals to 10. /// </summary> public const int DEFAULT_CAPACITY = 10; private readonly HashSet<Task> running; private readonly int capacity; private readonly LinkedList<Tuple<Task,TaskCompletionSource<bool>>> waiting; private readonly object lockable; /// <summary> /// The maximal number of async in-flight operations that can be enqueued into this async pipeline. /// </summary> public int Capacity { get { return capacity; } } /// <summary> /// The number of items currently enqueued into this async pipeline. /// </summary> public int Count { get { return running.Count; } } /// <summary> /// Constructs an empty AsyncPipeline with capacity equal to the DefaultCapacity. /// </summary> public AsyncPipeline() : this(DEFAULT_CAPACITY) {} /// <summary> /// Constructs an empty AsyncPipeline with a given capacity. /// </summary> /// <param name="capacity">The maximal capacity of this AsyncPipeline.</param> public AsyncPipeline(int capacity) { if (capacity < 1) throw new ArgumentOutOfRangeException("capacity", "The pipeline size must be larger than 0."); running = new HashSet<Task>(); waiting = new LinkedList<Tuple<Task, TaskCompletionSource<bool>>>(); this.capacity = capacity; lockable = new object(); } /// <summary> /// Adds a new task to this AsyncPipeline. /// </summary> /// <param name="task">A task to add to this AsyncPipeline.</param> public void Add(Task task) { Add(task, whiteBox: null); } /// <summary> /// Adds a collection of tasks to this AsyncPipeline. /// </summary> /// <param name="tasks">A collection of tasks to add to this AsyncPipeline.</param> public void AddRange(IEnumerable<Task> tasks) { foreach (var i in tasks) Add(i); } /// <summary> /// Adds a collection of tasks to this AsyncPipeline. /// </summary> /// <param name="tasks">A collection of tasks to add to this AsyncPipeline.</param> public void AddRange<T>(IEnumerable<Task<T>> tasks) { foreach (var i in tasks) Add(i); } /// <summary> /// Waits until all currently queued asynchronous operations are done. /// Blocks the calling thread. /// </summary> public void Wait() { Wait(null); } internal void Wait(WhiteBox whiteBox) { var tasks = new List<Task>(); lock (lockable) { tasks.AddRange(running); foreach (var i in waiting) tasks.Add(i.Item2.Task); } Task.WhenAll(tasks).Wait(); if (null != whiteBox) { whiteBox.Reset(); whiteBox.PipelineSize = 0; } } private bool IsFull { get { return Count >= capacity; } } internal void Add(Task task, WhiteBox whiteBox) { if (null == task) throw new ArgumentNullException("task"); // whitebox testing results-- we initialize pipeSz with an inconsistent copy of Count because it's better than nothing and will reflect that the pipeline size was in a valid state during some portion of this method, even if it isn't at a properly synchronized moment. int pipeSz = Count; var full = false; // we should be using a try...finally to execute the whitebox testing logic here but it apparently adds too much latency to be palatable for AsyncPipelineSimpleTest(), which is sensitive to latency. try { TaskCompletionSource<bool> tcs; lock (lockable) { if (!IsFull && waiting.Count == 0) { task.ContinueWith(OnTaskCompletion).Ignore(); running.Add(task); pipeSz = Count; return; } full = true; tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); waiting.AddLast(Tuple.Create(task, tcs)); } tcs.Task.Wait(); // the following quantity is an inconsistent value but i don't have a means to geuuuut one in this part of the // code because adding the actual add has already been performed from within a continuation. pipeSz = Count; } finally { if (whiteBox != null) { whiteBox.Reset(); whiteBox.PipelineSize = pipeSz; whiteBox.PipelineFull = full; } } } private void OnTaskCompletion(Task task) { lock (lockable) { running.Remove(task); UnblockWaiting(); } } private void UnblockWaiting() { while (!IsFull && waiting.Count > 0) { Tuple<Task,TaskCompletionSource<bool>> next = waiting.First(); waiting.RemoveFirst(); Task task = next.Item1; if(!task.IsCompleted) { task.ContinueWith(OnTaskCompletion).Ignore(); running.Add(task); } next.Item2.SetResult(true); } } internal class WhiteBox { public bool PipelineFull { get; internal set; } public int PipelineSize { get; internal set; } public bool FastPathed { get; internal set; } public WhiteBox() { Reset(); } public void Reset() { PipelineFull = false; PipelineSize = 0; } } } }
using JetBrains.Annotations; namespace Synergy.Contracts { static partial class Fail { #region variable.FailIfNull(nameof(variable)) /// <summary> /// Throws exception when provided value is <see langword="null"/>. /// </summary> /// <typeparam name="T">Type of the value to check against nullability.</typeparam> /// <param name="value">Value to check against nullability.</param> /// <param name="name">Name of the checked argument / parameter.</param> [NotNull] [return: System.Diagnostics.CodeAnalysis.NotNull] [AssertionMethod] [ContractAnnotation("value: null => halt; value: notnull => notnull")] public static T FailIfNull<T>( [CanBeNull] [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] this T value, [NotNull] [System.Diagnostics.CodeAnalysis.NotNull] string name) { Fail.RequiresArgumentName(name); return value.FailIfNull(Violation.WhenVariableIsNull(name)); } /// <summary> /// Throws exception when provided value is <see langword="null"/>. /// </summary> /// <typeparam name="T">Type of the value to check against nullability.</typeparam> /// <param name="value">Value to check against nullability.</param> /// <param name="message">Message that will be passed to <see cref="DesignByContractViolationException"/> when the check fails.</param> [NotNull] [return: System.Diagnostics.CodeAnalysis.NotNull] [AssertionMethod] [ContractAnnotation("value: null => halt; value: notnull => notnull")] public static T FailIfNull<T>( [CanBeNull] [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] this T value, Violation message) { if (value == null) throw Fail.Because(message); return value; } #endregion /// <summary> /// Throws exception when provided value is <see langword="null"/>. /// </summary> /// <typeparam name="T">Type of the value to check against nullability.</typeparam> /// <param name="value">Value to check against nullability.</param> /// <param name="name">Name of the checked argument / parameter.</param> /// <returns>Exactly the same value as provided to this method.</returns> [NotNull] [return: System.Diagnostics.CodeAnalysis.NotNull] [AssertionMethod] [ContractAnnotation("value: null => halt; value: notnull => notnull")] public static T OrFail<T>( [CanBeNull] [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] this T value, [NotNull] [System.Diagnostics.CodeAnalysis.NotNull] string name) { Fail.RequiresArgumentName(name); if (value == null) throw Fail.Because(Violation.WhenVariableIsNull(name)); return value; } /// <summary> /// /// Throws exception when provided value is <see langword="null"/>. /// </summary> /// <param name="value">Value to check against nullability.</param> /// <param name="name">Name of the checked argument / parameter.</param> /// <typeparam name="T">Type of the value to check against nullability.</typeparam> /// <returns>Value (not null) of the passed argument / parameter</returns> /// <exception cref="DesignByContractViolationException"></exception> [ContractAnnotation("value: null => halt")] public static T OrFail<T>(this T? value, [NotNull] [System.Diagnostics.CodeAnalysis.NotNull] string name) where T : struct { Fail.RequiresArgumentName(name); if (value == null) throw Fail.Because(Violation.WhenVariableIsNull(name)); return value.Value; } /// <summary> /// Throws exception when provided value is <see langword="null"/>. /// </summary> /// <typeparam name="T">Type of the value to check against nullability.</typeparam> /// <param name="value">Value to check against nullability.</param> /// <param name="name">Name of the checked argument / parameter.</param> /// <returns>Exactly the same value as provided to this method.</returns> [NotNull] [return: System.Diagnostics.CodeAnalysis.NotNull] [AssertionMethod] [ContractAnnotation("value: null => halt; value: notnull => notnull")] public static T NotNull<T>( [CanBeNull] [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] this T value, [NotNull] [System.Diagnostics.CodeAnalysis.NotNull] string name ) { return value.OrFail(name); } #region variable.CanBeNull() /// <summary> /// Returns EXACTLY the same object as method argument. /// It is useful when you have [NotNull] variable that you want to check against nullability as this method is marked with [CanBeNull]. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="value">Value to change its contract from [NotNull] to [CanBeNull].</param> /// <returns>Exactly the same value as provided to this method.</returns> [CanBeNull] [AssertionMethod] [ContractAnnotation("value: null => null; value: notnull => notnull")] public static T CanBeNull<T>([CanBeNull] [NoEnumeration] this T value) { return value; } #endregion #region Fail.IfArgumentNull /// <summary> /// Throws exception when specified argument value is <see langword="null" />. /// </summary> /// <param name="argumentValue">Value of the argument to check against being <see langword="null" />.</param> /// <param name="argumentName">Name of the argument passed to your method.</param> [AssertionMethod] [ContractAnnotation("argumentValue: null => halt")] //[Obsolete("Use " + nameof(Fail) + "." + nameof(IfNull) + " instead.")] public static void IfArgumentNull<T>( [CanBeNull] [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] T argumentValue, [NotNull] [System.Diagnostics.CodeAnalysis.NotNull] string argumentName) { Fail.RequiresArgumentName(argumentName); if (argumentValue == null) throw Fail.Because(Violation.WhenArgumentIsNull(argumentName)); } #endregion #region Fail.IfNull /// <summary> /// Throws exception when specified value is <see langword="null" />. /// </summary> /// <param name="value">Value to check against being <see langword="null" />.</param> /// <param name="name">Name of the checked argument / parameter.</param> [AssertionMethod] [ContractAnnotation("value: null => halt")] public static void IfNull<T>( [CanBeNull] [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] T value, [NotNull] [System.Diagnostics.CodeAnalysis.NotNull] string name) { Fail.RequiresArgumentName(name); Fail.IfNull(value, Violation.WhenVariableIsNull(name)); } /// <summary> /// Throws exception when specified value is <see langword="null" />. /// </summary> /// <param name="value">Value to check against being <see langword="null" />.</param> /// <param name="message">Message that will be passed to <see cref="DesignByContractViolationException"/> when the check fails.</param> [AssertionMethod] [ContractAnnotation("value: null => halt")] public static void IfNull<T>( [CanBeNull] [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] T value, Violation message) { if (value == null) throw Fail.Because(message); } #endregion #region Fail.IfNotNull /// <summary> /// Throws exception when specified value is NOT <see langword="null" />. /// </summary> /// <param name="value">Value to check against being NOT <see langword="null" />.</param> /// <param name="name">Name of the checked argument / parameter.</param> [AssertionMethod] [ContractAnnotation("value: notnull => halt")] public static void IfNotNull<T>([CanBeNull] [NoEnumeration] T value, [NotNull] [System.Diagnostics.CodeAnalysis.NotNull] string name) { Fail.RequiresArgumentName(name); Fail.IfNotNull(value, Violation.WhenVariableIsNotNull(name)); } /// <summary> /// Throws exception when specified value is NOT <see langword="null" />. /// </summary> /// <param name="value">Value to check against being NOT <see langword="null" />.</param> /// <param name="message">Message that will be passed to <see cref="DesignByContractViolationException"/> when the check fails.</param> [AssertionMethod] [ContractAnnotation("value: notnull => halt")] public static void IfNotNull<T>([CanBeNull] [NoEnumeration] T value, Violation message) { if (value != null) throw Fail.Because(message); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.CompilerServices; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; public sealed class DataContractSerializer : XmlObjectSerializer { private Type _rootType; private DataContract _rootContract; // post-surrogate private bool _needsContractNsAtRoot; private XmlDictionaryString _rootName; private XmlDictionaryString _rootNamespace; private int _maxItemsInObjectGraph; private bool _ignoreExtensionDataObject; private bool _preserveObjectReferences; private ReadOnlyCollection<Type> _knownTypeCollection; internal IList<Type> knownTypeList; internal DataContractDictionary knownDataContracts; private DataContractResolver _dataContractResolver; private ISerializationSurrogateProvider _serializationSurrogateProvider; private bool _serializeReadOnlyTypes; private static SerializationOption _option = IsReflectionBackupAllowed() ? SerializationOption.ReflectionAsBackup : SerializationOption.CodeGenOnly; private static bool _optionAlreadySet; internal static SerializationOption Option { get { return _option; } set { if (_optionAlreadySet) { throw new InvalidOperationException("Can only set once"); } _optionAlreadySet = true; _option = value; } } #if uapaot [RemovableFeature(ReflectionBasedSerializationFeature.Name, UseNopBody = true)] #endif private static bool IsReflectionBackupAllowed() { // The RemovableFeature annotation above is going to replace this with // "return false" if reflection based serialization feature was removed // at publishing time. return true; } public DataContractSerializer(Type type) : this(type, (IEnumerable<Type>)null) { } public DataContractSerializer(Type type, IEnumerable<Type> knownTypes) { Initialize(type, knownTypes, int.MaxValue, false, false, null, false); } public DataContractSerializer(Type type, string rootName, string rootNamespace) : this(type, rootName, rootNamespace, null) { } public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable<Type> knownTypes) { XmlDictionary dictionary = new XmlDictionary(2); Initialize(type, dictionary.Add(rootName), dictionary.Add(DataContract.GetNamespace(rootNamespace)), knownTypes, int.MaxValue, false, false, null, false); } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace) : this(type, rootName, rootNamespace, null) { } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes) { Initialize(type, rootName, rootNamespace, knownTypes, int.MaxValue, false, false, null, false); } #if uapaot public DataContractSerializer(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences) #else internal DataContractSerializer(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences) #endif { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, null, false); } public DataContractSerializer(Type type, DataContractSerializerSettings settings) { if (settings == null) { settings = new DataContractSerializerSettings(); } Initialize(type, settings.RootName, settings.RootNamespace, settings.KnownTypes, settings.MaxItemsInObjectGraph, false, settings.PreserveObjectReferences, settings.DataContractResolver, settings.SerializeReadOnlyTypes); } private void Initialize(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, DataContractResolver dataContractResolver, bool serializeReadOnlyTypes) { CheckNull(type, nameof(type)); _rootType = type; if (knownTypes != null) { this.knownTypeList = new List<Type>(); foreach (Type knownType in knownTypes) { this.knownTypeList.Add(knownType); } } if (maxItemsInObjectGraph < 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(maxItemsInObjectGraph), SR.Format(SR.ValueMustBeNonNegative))); _maxItemsInObjectGraph = maxItemsInObjectGraph; _ignoreExtensionDataObject = ignoreExtensionDataObject; _preserveObjectReferences = preserveObjectReferences; _dataContractResolver = dataContractResolver; _serializeReadOnlyTypes = serializeReadOnlyTypes; } private void Initialize(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, DataContractResolver dataContractResolver, bool serializeReadOnlyTypes) { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractResolver, serializeReadOnlyTypes); // validate root name and namespace are both non-null _rootName = rootName; _rootNamespace = rootNamespace; } public ReadOnlyCollection<Type> KnownTypes { get { if (_knownTypeCollection == null) { if (knownTypeList != null) { _knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList); } else { _knownTypeCollection = new ReadOnlyCollection<Type>(Array.Empty<Type>()); } } return _knownTypeCollection; } } internal override DataContractDictionary KnownDataContracts { get { if (this.knownDataContracts == null && this.knownTypeList != null) { // This assignment may be performed concurrently and thus is a race condition. // It's safe, however, because at worse a new (and identical) dictionary of // data contracts will be created and re-assigned to this field. Introduction // of a lock here could lead to deadlocks. this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList); } return this.knownDataContracts; } } public int MaxItemsInObjectGraph { get { return _maxItemsInObjectGraph; } } internal ISerializationSurrogateProvider SerializationSurrogateProvider { get { return _serializationSurrogateProvider; } set { _serializationSurrogateProvider = value; } } public bool PreserveObjectReferences { get { return _preserveObjectReferences; } } public bool IgnoreExtensionDataObject { get { return _ignoreExtensionDataObject; } } public DataContractResolver DataContractResolver { get { return _dataContractResolver; } } public bool SerializeReadOnlyTypes { get { return _serializeReadOnlyTypes; } } private DataContract RootContract { get { if (_rootContract == null) { _rootContract = DataContract.GetDataContract((_serializationSurrogateProvider == null) ? _rootType : GetSurrogatedType(_serializationSurrogateProvider, _rootType)); _needsContractNsAtRoot = CheckIfNeedsContractNsAtRoot(_rootName, _rootNamespace, _rootContract); } return _rootContract; } } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph) { InternalWriteObject(writer, graph, null); } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { InternalWriteStartObject(writer, graph); InternalWriteObjectContent(writer, graph, dataContractResolver); InternalWriteEndObject(writer); } public override void WriteObject(XmlWriter writer, object graph) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteStartObject(XmlWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteObjectContent(XmlWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteEndObject(XmlWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteEndObject(XmlDictionaryWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } public void WriteObject(XmlDictionaryWriter writer, object graph, DataContractResolver dataContractResolver) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph, dataContractResolver); } public override object ReadObject(XmlReader reader) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/); } public override object ReadObject(XmlReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlDictionaryReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } public object ReadObject(XmlDictionaryReader reader, bool verifyObjectName, DataContractResolver dataContractResolver) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName, dataContractResolver); } internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph) { WriteRootElement(writer, RootContract, _rootName, _rootNamespace, _needsContractNsAtRoot); } internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) { InternalWriteObjectContent(writer, graph, null); } internal void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); DataContract contract = RootContract; Type declaredType = contract.UnderlyingType; Type graphType = (graph == null) ? declaredType : graph.GetType(); if (_serializationSurrogateProvider != null) { graph = SurrogateToDataContractType(_serializationSurrogateProvider, graph, declaredType, ref graphType); } if (dataContractResolver == null) dataContractResolver = this.DataContractResolver; if (graph == null) { if (IsRootXmlAny(_rootName, contract)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeNull, declaredType))); WriteNull(writer); } else { if (declaredType == graphType) { if (contract.CanContainReferences) { XmlObjectSerializerWriteContext context = XmlObjectSerializerWriteContext.CreateContext(this, contract , dataContractResolver ); context.HandleGraphAtTopLevel(writer, graph, contract); context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle); } else { contract.WriteXmlValue(writer, graph, null); } } else { XmlObjectSerializerWriteContext context = null; if (IsRootXmlAny(_rootName, contract)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeSerializedAsDerivedType, graphType, contract.UnderlyingType))); contract = GetDataContract(contract, declaredType, graphType); context = XmlObjectSerializerWriteContext.CreateContext(this, RootContract , dataContractResolver ); if (contract.CanContainReferences) { context.HandleGraphAtTopLevel(writer, graph, contract); } context.OnHandleIsReference(writer, contract, graph); context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType); } } } internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType) { if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { return declaredTypeContract; } else if (declaredType.IsArray)//Array covariance is not supported in XSD { return declaredTypeContract; } else { return DataContract.GetDataContract(objectType.TypeHandle, objectType, SerializationMode.SharedContract); } } internal override void InternalWriteEndObject(XmlWriterDelegator writer) { if (!IsRootXmlAny(_rootName, RootContract)) { writer.WriteEndElement(); } } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) { return InternalReadObject(xmlReader, verifyObjectName, null); } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName, DataContractResolver dataContractResolver) { if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); if (dataContractResolver == null) dataContractResolver = this.DataContractResolver; #if uapaot // Give the root contract a chance to initialize or pre-verify the read RootContract.PrepareToRead(xmlReader); #endif if (verifyObjectName) { if (!InternalIsStartObject(xmlReader)) { XmlDictionaryString expectedName; XmlDictionaryString expectedNs; if (_rootName == null) { expectedName = RootContract.TopLevelElementName; expectedNs = RootContract.TopLevelElementNamespace; } else { expectedName = _rootName; expectedNs = _rootNamespace; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElement, expectedNs, expectedName), xmlReader)); } } else if (!IsStartElement(xmlReader)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElementAtDeserialize, XmlNodeType.Element), xmlReader)); } DataContract contract = RootContract; if (contract.IsPrimitive && object.ReferenceEquals(contract.UnderlyingType, _rootType) /*handle Nullable<T> differently*/) { return contract.ReadXmlValue(xmlReader, null); } if (IsRootXmlAny(_rootName, contract)) { return XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, contract as XmlDataContract, false /*isMemberType*/); } XmlObjectSerializerReadContext context = XmlObjectSerializerReadContext.CreateContext(this, contract, dataContractResolver); return context.InternalDeserialize(xmlReader, _rootType, contract, null, null); } internal override bool InternalIsStartObject(XmlReaderDelegator reader) { return IsRootElement(reader, RootContract, _rootName, _rootNamespace); } internal override Type GetSerializeType(object graph) { return (graph == null) ? _rootType : graph.GetType(); } internal override Type GetDeserializeType() { return _rootType; } internal static object SurrogateToDataContractType(ISerializationSurrogateProvider serializationSurrogateProvider, object oldObj, Type surrogatedDeclaredType, ref Type objType) { object obj = DataContractSurrogateCaller.GetObjectToSerialize(serializationSurrogateProvider, oldObj, objType, surrogatedDeclaredType); if (obj != oldObj) { objType = obj != null ? obj.GetType() : Globals.TypeOfObject; } return obj; } internal static Type GetSurrogatedType(ISerializationSurrogateProvider serializationSurrogateProvider, Type type) { return DataContractSurrogateCaller.GetDataContractType(serializationSurrogateProvider, DataContract.UnwrapNullableType(type)); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.SqlDataSource.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { public partial class SqlDataSource : System.Web.UI.DataSourceControl { #region Methods and constructors protected virtual new SqlDataSourceView CreateDataSourceView(string viewName) { return default(SqlDataSourceView); } public int Delete() { return default(int); } protected virtual new System.Data.Common.DbProviderFactory GetDbProviderFactory() { return default(System.Data.Common.DbProviderFactory); } protected override System.Web.UI.DataSourceView GetView(string viewName) { return default(System.Web.UI.DataSourceView); } protected override System.Collections.ICollection GetViewNames() { return default(System.Collections.ICollection); } public int Insert() { return default(int); } protected override void LoadViewState(Object savedState) { } protected internal override void OnInit(EventArgs e) { } protected override Object SaveViewState() { return default(Object); } public System.Collections.IEnumerable Select(System.Web.UI.DataSourceSelectArguments arguments) { return default(System.Collections.IEnumerable); } public SqlDataSource(string connectionString, string selectCommand) { } public SqlDataSource(string providerName, string connectionString, string selectCommand) { } public SqlDataSource() { } protected override void TrackViewState() { } public int Update() { return default(int); } #endregion #region Properties and indexers public virtual new int CacheDuration { get { return default(int); } set { } } public virtual new System.Web.UI.DataSourceCacheExpiry CacheExpirationPolicy { get { return default(System.Web.UI.DataSourceCacheExpiry); } set { } } public virtual new string CacheKeyDependency { get { return default(string); } set { } } public virtual new bool CancelSelectOnNullParameter { get { return default(bool); } set { } } public System.Web.UI.ConflictOptions ConflictDetection { get { return default(System.Web.UI.ConflictOptions); } set { } } public virtual new string ConnectionString { get { return default(string); } set { } } public SqlDataSourceMode DataSourceMode { get { return default(SqlDataSourceMode); } set { } } public string DeleteCommand { get { return default(string); } set { } } public SqlDataSourceCommandType DeleteCommandType { get { return default(SqlDataSourceCommandType); } set { } } public ParameterCollection DeleteParameters { get { return default(ParameterCollection); } } public virtual new bool EnableCaching { get { return default(bool); } set { } } public string FilterExpression { get { return default(string); } set { } } public ParameterCollection FilterParameters { get { return default(ParameterCollection); } } public string InsertCommand { get { return default(string); } set { } } public SqlDataSourceCommandType InsertCommandType { get { return default(SqlDataSourceCommandType); } set { } } public ParameterCollection InsertParameters { get { return default(ParameterCollection); } } public string OldValuesParameterFormatString { get { return default(string); } set { } } public virtual new string ProviderName { get { return default(string); } set { } } public string SelectCommand { get { return default(string); } set { } } public SqlDataSourceCommandType SelectCommandType { get { return default(SqlDataSourceCommandType); } set { } } public ParameterCollection SelectParameters { get { return default(ParameterCollection); } } public string SortParameterName { get { return default(string); } set { } } public virtual new string SqlCacheDependency { get { return default(string); } set { } } public string UpdateCommand { get { return default(string); } set { } } public SqlDataSourceCommandType UpdateCommandType { get { return default(SqlDataSourceCommandType); } set { } } public ParameterCollection UpdateParameters { get { return default(ParameterCollection); } } #endregion #region Events public event SqlDataSourceStatusEventHandler Deleted { add { } remove { } } public event SqlDataSourceCommandEventHandler Deleting { add { } remove { } } public event SqlDataSourceFilteringEventHandler Filtering { add { } remove { } } public event SqlDataSourceStatusEventHandler Inserted { add { } remove { } } public event SqlDataSourceCommandEventHandler Inserting { add { } remove { } } public event SqlDataSourceStatusEventHandler Selected { add { } remove { } } public event SqlDataSourceSelectingEventHandler Selecting { add { } remove { } } public event SqlDataSourceStatusEventHandler Updated { add { } remove { } } public event SqlDataSourceCommandEventHandler Updating { add { } remove { } } #endregion } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace SPO_MasterPages { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H05_CountryColl (editable child list).<br/> /// This is a generated base class of <see cref="H05_CountryColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="H04_SubContinent"/> editable child object.<br/> /// The items of the collection are <see cref="H06_Country"/> objects. /// </remarks> [Serializable] public partial class H05_CountryColl : BusinessListBase<H05_CountryColl, H06_Country> { #region Collection Business Methods /// <summary> /// Removes a <see cref="H06_Country"/> item from the collection. /// </summary> /// <param name="country_ID">The Country_ID of the item to be removed.</param> public void Remove(int country_ID) { foreach (var h06_Country in this) { if (h06_Country.Country_ID == country_ID) { Remove(h06_Country); break; } } } /// <summary> /// Determines whether a <see cref="H06_Country"/> item is in the collection. /// </summary> /// <param name="country_ID">The Country_ID of the item to search for.</param> /// <returns><c>true</c> if the H06_Country is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int country_ID) { foreach (var h06_Country in this) { if (h06_Country.Country_ID == country_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="H06_Country"/> item is in the collection's DeletedList. /// </summary> /// <param name="country_ID">The Country_ID of the item to search for.</param> /// <returns><c>true</c> if the H06_Country is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int country_ID) { foreach (var h06_Country in DeletedList) { if (h06_Country.Country_ID == country_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="H06_Country"/> item of the <see cref="H05_CountryColl"/> collection, based on a given Country_ID. /// </summary> /// <param name="country_ID">The Country_ID.</param> /// <returns>A <see cref="H06_Country"/> object.</returns> public H06_Country FindH06_CountryByCountry_ID(int country_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].Country_ID.Equals(country_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="H05_CountryColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="H05_CountryColl"/> collection.</returns> internal static H05_CountryColl NewH05_CountryColl() { return DataPortal.CreateChild<H05_CountryColl>(); } /// <summary> /// Factory method. Loads a <see cref="H05_CountryColl"/> collection, based on given parameters. /// </summary> /// <param name="parent_SubContinent_ID">The Parent_SubContinent_ID parameter of the H05_CountryColl to fetch.</param> /// <returns>A reference to the fetched <see cref="H05_CountryColl"/> collection.</returns> internal static H05_CountryColl GetH05_CountryColl(int parent_SubContinent_ID) { return DataPortal.FetchChild<H05_CountryColl>(parent_SubContinent_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H05_CountryColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public H05_CountryColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="H05_CountryColl"/> collection from the database, based on given criteria. /// </summary> /// <param name="parent_SubContinent_ID">The Parent Sub Continent ID.</param> protected void Child_Fetch(int parent_SubContinent_ID) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetH05_CountryColl", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", parent_SubContinent_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, parent_SubContinent_ID); OnFetchPre(args); LoadCollection(cmd); OnFetchPost(args); } } foreach (var item in this) { item.FetchChildren(); } } private void LoadCollection(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { Fetch(dr); } } /// <summary> /// Loads all <see cref="H05_CountryColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(H06_Country.GetH06_Country(dr)); } RaiseListChangedEvents = rlce; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; namespace System { public partial class String { public bool Contains(string value) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); return SpanHelpers.IndexOf( ref _firstChar, Length, ref value._firstChar, value.Length) >= 0; } public bool Contains(string value, StringComparison comparisonType) { return IndexOf(value, comparisonType) >= 0; } public bool Contains(char value) => SpanHelpers.Contains(ref _firstChar, value, Length); public bool Contains(char value, StringComparison comparisonType) { return IndexOf(value, comparisonType) != -1; } // Returns the index of the first occurrence of a specified character in the current instance. // The search starts at startIndex and runs thorough the next count characters. // public int IndexOf(char value) => SpanHelpers.IndexOf(ref _firstChar, value, Length); public int IndexOf(char value, int startIndex) { return IndexOf(value, startIndex, this.Length - startIndex); } public int IndexOf(char value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IndexOf(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return IndexOf(value); case StringComparison.OrdinalIgnoreCase: return CompareInfo.Invariant.IndexOf(this, value, CompareOptions.OrdinalIgnoreCase); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } public unsafe int IndexOf(char value, int startIndex, int count) { if ((uint)startIndex > (uint)Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if ((uint)count > (uint)(Length - startIndex)) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); int result = SpanHelpers.IndexOf(ref Unsafe.Add(ref _firstChar, startIndex), value, count); return result == -1 ? result : result + startIndex; } // Returns the index of the first occurrence of any specified character in the current instance. // The search starts at startIndex and runs to startIndex + count - 1. // public int IndexOfAny(char[] anyOf) { return IndexOfAny(anyOf, 0, this.Length); } public int IndexOfAny(char[] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, this.Length - startIndex); } public int IndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException(nameof(anyOf)); if ((uint)startIndex > (uint)Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if ((uint)count > (uint)(Length - startIndex)) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (anyOf.Length > 0 && anyOf.Length <= 5) { // The ReadOnlySpan.IndexOfAny extension is vectorized for values of 1 - 5 in length int result = new ReadOnlySpan<char>(ref Unsafe.Add(ref _firstChar, startIndex), count).IndexOfAny(anyOf); return result == -1 ? result : result + startIndex; } else if (anyOf.Length > 5) { // Use Probabilistic Map return IndexOfCharArray(anyOf, startIndex, count); } else // anyOf.Length == 0 { return -1; } } private unsafe int IndexOfCharArray(char[] anyOf, int startIndex, int count) { // use probabilistic map, see InitializeProbabilisticMap ProbabilisticMap map = default; uint* charMap = (uint*)&map; InitializeProbabilisticMap(charMap, anyOf); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count > 0) { int thisChar = *pCh; if (IsCharBitSet(charMap, (byte)thisChar) && IsCharBitSet(charMap, (byte)(thisChar >> 8)) && ArrayContains((char)thisChar, anyOf)) { return (int)(pCh - pChars); } count--; pCh++; } return -1; } } private const int PROBABILISTICMAP_BLOCK_INDEX_MASK = 0x7; private const int PROBABILISTICMAP_BLOCK_INDEX_SHIFT = 0x3; private const int PROBABILISTICMAP_SIZE = 0x8; // A probabilistic map is an optimization that is used in IndexOfAny/ // LastIndexOfAny methods. The idea is to create a bit map of the characters we // are searching for and use this map as a "cheap" check to decide if the // current character in the string exists in the array of input characters. // There are 256 bits in the map, with each character mapped to 2 bits. Every // character is divided into 2 bytes, and then every byte is mapped to 1 bit. // The character map is an array of 8 integers acting as map blocks. The 3 lsb // in each byte in the character is used to index into this map to get the // right block, the value of the remaining 5 msb are used as the bit position // inside this block. private static unsafe void InitializeProbabilisticMap(uint* charMap, ReadOnlySpan<char> anyOf) { bool hasAscii = false; uint* charMapLocal = charMap; // https://github.com/dotnet/coreclr/issues/14264 for (int i = 0; i < anyOf.Length; ++i) { int c = anyOf[i]; // Map low bit SetCharBit(charMapLocal, (byte)c); // Map high bit c >>= 8; if (c == 0) { hasAscii = true; } else { SetCharBit(charMapLocal, (byte)c); } } if (hasAscii) { // Common to search for ASCII symbols. Just set the high value once. charMapLocal[0] |= 1u; } } private static bool ArrayContains(char searchChar, char[] anyOf) { for (int i = 0; i < anyOf.Length; i++) { if (anyOf[i] == searchChar) return true; } return false; } private static unsafe bool IsCharBitSet(uint* charMap, byte value) { return (charMap[value & PROBABILISTICMAP_BLOCK_INDEX_MASK] & (1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT))) != 0; } private static unsafe void SetCharBit(uint* charMap, byte value) { charMap[value & PROBABILISTICMAP_BLOCK_INDEX_MASK] |= 1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT); } public int IndexOf(string value) { return IndexOf(value, StringComparison.CurrentCulture); } public int IndexOf(string value, int startIndex) { return IndexOf(value, startIndex, StringComparison.CurrentCulture); } public int IndexOf(string value, int startIndex, int count) { if (startIndex < 0 || startIndex > this.Length) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } if (count < 0 || count > this.Length - startIndex) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } return IndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int IndexOf(string value, StringComparison comparisonType) { return IndexOf(value, 0, this.Length, comparisonType); } public int IndexOf(string value, int startIndex, StringComparison comparisonType) { return IndexOf(value, startIndex, this.Length - startIndex, comparisonType); } public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType) { // Validate inputs if (value == null) throw new ArgumentNullException(nameof(value)); if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || startIndex > this.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (comparisonType == StringComparison.Ordinal) { int result = SpanHelpers.IndexOf( ref Unsafe.Add(ref this._firstChar, startIndex), count, ref value._firstChar, value.Length); return (result >= 0 ? startIndex : 0) + result; } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.OrdinalIgnoreCase: return CompareInfo.IndexOfOrdinal(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } // Returns the index of the last occurrence of a specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOf(char value) => SpanHelpers.LastIndexOf(ref _firstChar, value, Length); public int LastIndexOf(char value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public unsafe int LastIndexOf(char value, int startIndex, int count) { if (Length == 0) return -1; if ((uint)startIndex >= (uint)Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if ((uint)count > (uint)startIndex + 1) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); int startSearchAt = startIndex + 1 - count; int result = SpanHelpers.LastIndexOf(ref Unsafe.Add(ref _firstChar, startSearchAt), value, count); return result == -1 ? result : result + startSearchAt; } // Returns the index of the last occurrence of any specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOfAny(char[] anyOf) { return LastIndexOfAny(anyOf, this.Length - 1, this.Length); } public int LastIndexOfAny(char[] anyOf, int startIndex) { return LastIndexOfAny(anyOf, startIndex, startIndex + 1); } public unsafe int LastIndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException(nameof(anyOf)); if (Length == 0) return -1; if ((uint)startIndex >= (uint)Length) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } if ((count < 0) || ((count - 1) > startIndex)) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } if (anyOf.Length > 1) { return LastIndexOfCharArray(anyOf, startIndex, count); } else if (anyOf.Length == 1) { return LastIndexOf(anyOf[0], startIndex, count); } else // anyOf.Length == 0 { return -1; } } private unsafe int LastIndexOfCharArray(char[] anyOf, int startIndex, int count) { // use probabilistic map, see InitializeProbabilisticMap ProbabilisticMap map = default; uint* charMap = (uint*)&map; InitializeProbabilisticMap(charMap, anyOf); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count > 0) { int thisChar = *pCh; if (IsCharBitSet(charMap, (byte)thisChar) && IsCharBitSet(charMap, (byte)(thisChar >> 8)) && ArrayContains((char)thisChar, anyOf)) { return (int)(pCh - pChars); } count--; pCh--; } return -1; } } // Returns the index of the last occurrence of any character in value in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOf(string value) { return LastIndexOf(value, this.Length - 1, this.Length, StringComparison.CurrentCulture); } public int LastIndexOf(string value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture); } public int LastIndexOf(string value, int startIndex, int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } return LastIndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int LastIndexOf(string value, StringComparison comparisonType) { return LastIndexOf(value, this.Length - 1, this.Length, comparisonType); } public int LastIndexOf(string value, int startIndex, StringComparison comparisonType) { return LastIndexOf(value, startIndex, startIndex + 1, comparisonType); } public int LastIndexOf(string value, int startIndex, int count, StringComparison comparisonType) { if (value == null) throw new ArgumentNullException(nameof(value)); // Special case for 0 length input strings if (this.Length == 0 && (startIndex == -1 || startIndex == 0)) return (value.Length == 0) ? 0 : -1; // Now after handling empty strings, make sure we're not out of range if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == this.Length if (startIndex == this.Length) { startIndex--; if (count > 0) count--; } // 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); // If we are looking for nothing, just return startIndex if (value.Length == 0) return startIndex; switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.LastIndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: case StringComparison.OrdinalIgnoreCase: return CompareInfo.LastIndexOfOrdinal(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } [StructLayout(LayoutKind.Explicit, Size = PROBABILISTICMAP_SIZE * sizeof(uint))] private struct ProbabilisticMap { } } }
// // System.Web.Caching // // Author: // Patrik Torstensson // Daniel Cazzulino ([email protected]) // // // 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.Threading; namespace System.Web.Caching { internal class CacheEntry { enum Flags { Removed = 1, Public = 2 } internal static readonly byte NoBucketHash = byte.MaxValue; internal static readonly int NoIndexInBucket = int.MaxValue; CacheItemPriority _enumPriority; long _longHits; byte _byteExpiresBucket; int _intExpiresIndex; long _ticksExpires; long _ticksSlidingExpiration; string _strKey; object _objItem; long _longMinHits; Flags _enumFlags; CacheDependency _objDependency; Cache _objCache; ReaderWriterLock _lock = new ReaderWriterLock(); internal event CacheItemRemovedCallback _onRemoved; internal CacheEntry (Cache objManager, string strKey, object objItem,CacheDependency objDependency, CacheItemRemovedCallback eventRemove, DateTime dtExpires, TimeSpan tsSpan, long longMinHits, bool boolPublic, CacheItemPriority enumPriority ) { if (boolPublic) _enumFlags |= Flags.Public; _strKey = strKey; _objItem = objItem; _objCache = objManager; _onRemoved += eventRemove; _enumPriority = enumPriority; _ticksExpires = dtExpires.ToUniversalTime ().Ticks; _ticksSlidingExpiration = tsSpan.Ticks; // If we have a sliding expiration it overrides the absolute expiration (MS behavior) // This is because sliding expiration causes the absolute expiration to be // moved after each period, and the absolute expiration is the value used // for all expiration calculations. if (tsSpan.Ticks != Cache.NoSlidingExpiration.Ticks) _ticksExpires = DateTime.UtcNow.AddTicks (_ticksSlidingExpiration).Ticks; _objDependency = objDependency; if (_objDependency != null) // Add the entry to the cache dependency handler (we support multiple entries per handler) _objDependency.Changed += new CacheDependencyChangedHandler (OnChanged); _longMinHits = longMinHits; } internal void OnChanged (object sender, CacheDependencyChangedArgs objDependency) { _objCache.Remove (_strKey, CacheItemRemovedReason.DependencyChanged); } internal void Close (CacheItemRemovedReason enumReason) { Delegate [] removedEvents = null; _lock.AcquireWriterLock(-1); try { // Check if the item already is removed if ((_enumFlags & Flags.Removed) != 0) return; _enumFlags |= Flags.Removed; if (_onRemoved != null) removedEvents = _onRemoved.GetInvocationList (); } finally { _lock.ReleaseWriterLock(); } if (removedEvents != null) { // Call the delegate to tell that we are now removing the entry foreach (Delegate del in removedEvents) { CacheItemRemovedCallback removed = (CacheItemRemovedCallback) del; try { removed (_strKey, _objItem, enumReason); } catch (Exception obj) { if (IsPublic) HttpApplicationFactory.SignalError (obj); } } } _lock.AcquireWriterLock(-1); try { // If we have a dependency, remove the entry if (_objDependency != null) _objDependency.Changed -= new CacheDependencyChangedHandler (OnChanged); } finally { _lock.ReleaseWriterLock(); } } internal bool HasUsage { get { if (_longMinHits == System.Int64.MaxValue) return false; return true; } } internal bool HasAbsoluteExpiration { get { if (_ticksExpires == Cache.NoAbsoluteExpiration.Ticks) return false; return true; } } internal bool HasSlidingExpiration { get { if (_ticksSlidingExpiration == Cache.NoSlidingExpiration.Ticks) return false; return true; } } internal byte ExpiresBucket { get { return _byteExpiresBucket; } set { _byteExpiresBucket = value; } } internal int ExpiresIndex { get { return _intExpiresIndex; } set { _intExpiresIndex = value; } } internal long Expires { get { return _ticksExpires; } set { _ticksExpires = value; } } internal long SlidingExpiration { get { return _ticksSlidingExpiration; } } internal object Item { get { return _objItem; } } internal string Key { get { return _strKey; } } internal long Hits { get { return _longHits; } } internal long MinimumHits { get { return _longMinHits; } } internal CacheItemPriority Priority { get { return _enumPriority; } } internal bool IsPublic { get { return (_enumFlags & Flags.Public) != 0; } } internal void Hit () { Interlocked.Increment (ref _longHits); } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// Provider of professional services. /// </summary> public class ProfessionalService_Core : TypeCore, ILocalBusiness { public ProfessionalService_Core() { this._TypeId = 216; this._Id = "ProfessionalService"; this._Schema_Org_Url = "http://schema.org/ProfessionalService"; string label = ""; GetLabel(out label, "ProfessionalService", typeof(ProfessionalService_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155}; this._SubTypes = new int[]{9,21,84,89,112,133,156,186,209,231}; this._SuperTypes = new int[]{155}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using Stream = System.IO.Stream; using TextReader = System.IO.TextReader; using StringBuilder = System.Text.StringBuilder; using Hashtable = System.Collections.Hashtable; using Assembly = System.Reflection.Assembly; using EventHandlerList = System.ComponentModel.EventHandlerList; using BitSet = antlr.collections.impl.BitSet; using antlr.debug; namespace antlr { /*ANTLR Translator Generator * Project led by Terence Parr at http://www.jGuru.com * Software rights: http://www.antlr.org/license.html * * $Id:$ */ // // ANTLR C# Code Generator by Micheal Jordan // Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com // Anthony Oguntimehin // // With many thanks to Eric V. Smith from the ANTLR list. // public abstract class CharScanner : TokenStream, ICharScannerDebugSubject { internal const char NO_CHAR = (char) (0); public static readonly char EOF_CHAR = Char.MaxValue; // Used to store event delegates private EventHandlerList events_ = new EventHandlerList(); protected internal EventHandlerList Events { get { return events_; } } // The unique keys for each event that CharScanner [objects] can generate internal static readonly object EnterRuleEventKey = new object(); internal static readonly object ExitRuleEventKey = new object(); internal static readonly object DoneEventKey = new object(); internal static readonly object ReportErrorEventKey = new object(); internal static readonly object ReportWarningEventKey = new object(); internal static readonly object NewLineEventKey = new object(); internal static readonly object MatchEventKey = new object(); internal static readonly object MatchNotEventKey = new object(); internal static readonly object MisMatchEventKey = new object(); internal static readonly object MisMatchNotEventKey = new object(); internal static readonly object ConsumeEventKey = new object(); internal static readonly object LAEventKey = new object(); internal static readonly object SemPredEvaluatedEventKey = new object(); internal static readonly object SynPredStartedEventKey = new object(); internal static readonly object SynPredFailedEventKey = new object(); internal static readonly object SynPredSucceededEventKey = new object(); protected internal StringBuilder text; // text of current token protected bool saveConsumedInput = true; // does consume() save characters? /// <summary>Used for creating Token instances.</summary> protected TokenCreator tokenCreator; /// <summary>Used for caching lookahead characters.</summary> protected char cached_LA1; protected char cached_LA2; protected bool caseSensitive = true; protected bool caseSensitiveLiterals = true; protected Hashtable literals; // set by subclass /*Tab chars are handled by tab() according to this value; override * method to do anything weird with tabs. */ protected internal int tabsize = 8; protected internal IToken returnToken_ = null; // used to return tokens w/o using return val. protected internal LexerSharedInputState inputState; /*Used during filter mode to indicate that path is desired. * A subsequent scan error will report an error as usual if * acceptPath=true; */ protected internal bool commitToPath = false; /*Used to keep track of indentdepth for traceIn/Out */ protected internal int traceDepth = 0; public CharScanner() { text = new StringBuilder(); setTokenCreator(new CommonToken.CommonTokenCreator()); } public CharScanner(InputBuffer cb) : this() { inputState = new LexerSharedInputState(cb); cached_LA2 = inputState.input.LA(2); cached_LA1 = inputState.input.LA(1); } public CharScanner(LexerSharedInputState sharedState) : this() { inputState = sharedState; if (inputState != null) { cached_LA2 = inputState.input.LA(2); cached_LA1 = inputState.input.LA(1); } } public event TraceEventHandler EnterRule { add { Events.AddHandler(EnterRuleEventKey, value); } remove { Events.RemoveHandler(EnterRuleEventKey, value); } } public event TraceEventHandler ExitRule { add { Events.AddHandler(ExitRuleEventKey, value); } remove { Events.RemoveHandler(ExitRuleEventKey, value); } } public event TraceEventHandler Done { add { Events.AddHandler(DoneEventKey, value); } remove { Events.RemoveHandler(DoneEventKey, value); } } public event MessageEventHandler ErrorReported { add { Events.AddHandler(ReportErrorEventKey, value); } remove { Events.RemoveHandler(ReportErrorEventKey, value); } } public event MessageEventHandler WarningReported { add { Events.AddHandler(ReportWarningEventKey, value); } remove { Events.RemoveHandler(ReportWarningEventKey, value); } } public event NewLineEventHandler HitNewLine { add { Events.AddHandler(NewLineEventKey, value); } remove { Events.RemoveHandler(NewLineEventKey, value); } } public event MatchEventHandler MatchedChar { add { Events.AddHandler(MatchEventKey, value); } remove { Events.RemoveHandler(MatchEventKey, value); } } public event MatchEventHandler MatchedNotChar { add { Events.AddHandler(MatchNotEventKey, value); } remove { Events.RemoveHandler(MatchNotEventKey, value); } } public event MatchEventHandler MisMatchedChar { add { Events.AddHandler(MisMatchEventKey, value); } remove { Events.RemoveHandler(MisMatchEventKey, value); } } public event MatchEventHandler MisMatchedNotChar { add { Events.AddHandler(MisMatchNotEventKey, value); } remove { Events.RemoveHandler(MisMatchNotEventKey, value); } } public event TokenEventHandler ConsumedChar { add { Events.AddHandler(ConsumeEventKey, value); } remove { Events.RemoveHandler(ConsumeEventKey, value); } } public event TokenEventHandler CharLA { add { Events.AddHandler(LAEventKey, value); } remove { Events.RemoveHandler(LAEventKey, value); } } public event SemanticPredicateEventHandler SemPredEvaluated { add { Events.AddHandler(SemPredEvaluatedEventKey, value); } remove { Events.RemoveHandler(SemPredEvaluatedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredStarted { add { Events.AddHandler(SynPredStartedEventKey, value); } remove { Events.RemoveHandler(SynPredStartedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredFailed { add { Events.AddHandler(SynPredFailedEventKey, value); } remove { Events.RemoveHandler(SynPredFailedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredSucceeded { add { Events.AddHandler(SynPredSucceededEventKey, value); } remove { Events.RemoveHandler(SynPredSucceededEventKey, value); } } // From interface TokenStream public virtual IToken nextToken() { return null; } public virtual void append(char c) { if (saveConsumedInput) { text.Append(c); } } public virtual void append(string s) { if (saveConsumedInput) { text.Append(s); } } public virtual void commit() { inputState.input.commit(); } public virtual void consume() { if (inputState.guessing == 0) { if (caseSensitive) { append(cached_LA1); } else { // use input.LA(), not LA(), to get original case // CharScanner.LA() would toLower it. append(inputState.input.LA(1)); } if (cached_LA1 == '\t') { tab(); } else { inputState.column++; } } if (caseSensitive) { cached_LA1 = inputState.input.consume(); cached_LA2 = inputState.input.LA(2); } else { cached_LA1 = toLower(inputState.input.consume()); cached_LA2 = toLower(inputState.input.LA(2)); } } /*Consume chars until one matches the given char */ public virtual void consumeUntil(int c) { while ((EOF_CHAR != cached_LA1) && (c != cached_LA1)) { consume(); } } /*Consume chars until one matches the given set */ public virtual void consumeUntil(BitSet bset) { while (cached_LA1 != EOF_CHAR && !bset.member(cached_LA1)) { consume(); } } public virtual bool getCaseSensitive() { return caseSensitive; } public bool getCaseSensitiveLiterals() { return caseSensitiveLiterals; } public virtual int getColumn() { return inputState.column; } public virtual void setColumn(int c) { inputState.column = c; } public virtual bool getCommitToPath() { return commitToPath; } public virtual string getFilename() { return inputState.filename; } public virtual InputBuffer getInputBuffer() { return inputState.input; } public virtual LexerSharedInputState getInputState() { return inputState; } public virtual void setInputState(LexerSharedInputState state) { inputState = state; } public virtual int getLine() { return inputState.line; } /*return a copy of the current text buffer */ public virtual string getText() { return text.ToString(); } public virtual IToken getTokenObject() { return returnToken_; } public virtual char LA(int i) { if (i == 1) { return cached_LA1; } if (i == 2) { return cached_LA2; } if (caseSensitive) { return inputState.input.LA(i); } else { return toLower(inputState.input.LA(i)); } } protected internal virtual IToken makeToken(int t) { IToken newToken = null; bool typeCreated; try { newToken = tokenCreator.Create(); if (newToken != null) { newToken.Type = t; newToken.setColumn(inputState.tokenStartColumn); newToken.setLine(inputState.tokenStartLine); // tracking real start line now: newToken.setLine(inputState.line); newToken.setFilename(inputState.filename); } typeCreated = true; } catch { typeCreated = false; } if (!typeCreated) { panic("Can't create Token object '" + tokenCreator.TokenTypeName + "'"); newToken = Token.badToken; } return newToken; } public virtual int mark() { return inputState.input.mark(); } public virtual void match(char c) { match((int) c); } public virtual void match(int c) { if (cached_LA1 != c) { throw new MismatchedCharException(cached_LA1, Convert.ToChar(c), false, this); } consume(); } public virtual void match(BitSet b) { if (!b.member(cached_LA1)) { throw new MismatchedCharException(cached_LA1, b, false, this); } consume(); } public virtual void match(string s) { int len = s.Length; for (int i = 0; i < len; i++) { if (cached_LA1 != s[i]) { throw new MismatchedCharException(cached_LA1, s[i], false, this); } consume(); } } public virtual void matchNot(char c) { matchNot((int) c); } public virtual void matchNot(int c) { if (cached_LA1 == c) { throw new MismatchedCharException(cached_LA1, Convert.ToChar(c), true, this); } consume(); } public virtual void matchRange(int c1, int c2) { if (cached_LA1 < c1 || cached_LA1 > c2) { throw new MismatchedCharException(cached_LA1, Convert.ToChar(c1), Convert.ToChar(c2), false, this); } consume(); } public virtual void matchRange(char c1, char c2) { matchRange((int) c1, (int) c2); } public virtual void newline() { inputState.line++; inputState.column = 1; } /*advance the current column number by an appropriate amount * according to tab size. This method is called from consume(). */ public virtual void tab() { int c = getColumn(); int nc = (((c - 1) / tabsize) + 1) * tabsize + 1; // calculate tab stop setColumn(nc); } public virtual void setTabSize(int size) { tabsize = size; } public virtual int getTabSize() { return tabsize; } public virtual void panic() { //Console.Error.WriteLine("CharScanner: panic"); //Environment.Exit(1); panic(""); } /// <summary> /// This method is executed by ANTLR internally when it detected an illegal /// state that cannot be recovered from. /// The previous implementation of this method called <see cref="Environment.Exit"/> /// and writes directly to <see cref="Console.Error"/>, which is usually not /// appropriate when a translator is embedded into a larger application. /// </summary> /// <param name="s">Error message.</param> public virtual void panic(string s) { //Console.Error.WriteLine("CharScanner; panic: " + s); //Environment.Exit(1); throw new ANTLRPanicException("CharScanner::panic: " + s); } /*Parser error-reporting function can be overridden in subclass */ public virtual void reportError(RecognitionException ex) { Console.Error.WriteLine(ex); } /*Parser error-reporting function can be overridden in subclass */ public virtual void reportError(string s) { if (getFilename() == null) { Console.Error.WriteLine("error: " + s); } else { Console.Error.WriteLine(getFilename() + ": error: " + s); } } /*Parser warning-reporting function can be overridden in subclass */ public virtual void reportWarning(string s) { if (getFilename() == null) { Console.Error.WriteLine("warning: " + s); } else { Console.Error.WriteLine(getFilename() + ": warning: " + s); } } public virtual void refresh() { if (caseSensitive) { cached_LA2 = inputState.input.LA(2); cached_LA1 = inputState.input.LA(1); } else { cached_LA2 = toLower(inputState.input.LA(2)); cached_LA1 = toLower(inputState.input.LA(1)); } } public virtual void resetState(InputBuffer ib) { text.Length = 0; traceDepth = 0; inputState.resetInput(ib); refresh(); } public void resetState(Stream s) { resetState(new ByteBuffer(s)); } public void resetState(TextReader tr) { resetState(new CharBuffer(tr)); } public virtual void resetText() { text.Length = 0; inputState.tokenStartColumn = inputState.column; inputState.tokenStartLine = inputState.line; } public virtual void rewind(int pos) { inputState.input.rewind(pos); //setColumn(inputState.tokenStartColumn); cached_LA2 = inputState.input.LA(2); cached_LA1 = inputState.input.LA(1); } public virtual void setCaseSensitive(bool t) { caseSensitive = t; if (caseSensitive) { cached_LA2 = inputState.input.LA(2); cached_LA1 = inputState.input.LA(1); } else { cached_LA2 = toLower(inputState.input.LA(2)); cached_LA1 = toLower(inputState.input.LA(1)); } } public virtual void setCommitToPath(bool commit) { commitToPath = commit; } public virtual void setFilename(string f) { inputState.filename = f; } public virtual void setLine(int line) { inputState.line = line; } public virtual void setText(string s) { resetText(); text.Append(s); } public virtual void setTokenCreator(TokenCreator tokenCreator) { this.tokenCreator = tokenCreator; } // Test the token text against the literals table // Override this method to perform a different literals test public virtual int testLiteralsTable(int ttype) { string tokenText = text.ToString(); if ( (tokenText == null) || (tokenText == string.Empty) ) return ttype; else { object typeAsObject = literals[tokenText]; return (typeAsObject == null) ? ttype : ((int) typeAsObject); } } /*Test the text passed in against the literals table * Override this method to perform a different literals test * This is used primarily when you want to test a portion of * a token. */ public virtual int testLiteralsTable(string someText, int ttype) { if ( (someText == null) || (someText == string.Empty) ) return ttype; else { object typeAsObject = literals[someText]; return (typeAsObject == null) ? ttype : ((int) typeAsObject); } } // Override this method to get more specific case handling public virtual char toLower(int c) { return Char.ToLower(Convert.ToChar(c), System.Globalization.CultureInfo.InvariantCulture); } public virtual void traceIndent() { for (int i = 0; i < traceDepth; i++) Console.Out.Write(" "); } public virtual void traceIn(string rname) { traceDepth += 1; traceIndent(); Console.Out.WriteLine("> lexer " + rname + "; c==" + LA(1)); } public virtual void traceOut(string rname) { traceIndent(); Console.Out.WriteLine("< lexer " + rname + "; c==" + LA(1)); traceDepth -= 1; } /*This method is called by YourLexer.nextToken() when the lexer has * hit EOF condition. EOF is NOT a character. * This method is not called if EOF is reached during * syntactic predicate evaluation or during evaluation * of normal lexical rules, which presumably would be * an IOException. This traps the "normal" EOF condition. * * uponEOF() is called after the complete evaluation of * the previous token and only if your parser asks * for another token beyond that last non-EOF token. * * You might want to throw token or char stream exceptions * like: "Heh, premature eof" or a retry stream exception * ("I found the end of this file, go back to referencing file"). */ public virtual void uponEOF() { } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK; using OpenTK.Graphics; using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Drawables; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Online.Multiplayer; using osu.Game.Users; namespace osu.Game.Screens.Multiplayer { public class DrawableRoom : OsuClickableContainer { private const float transition_duration = 100; private const float content_padding = 10; private const float height = 100; private const float side_strip_width = 5; private const float cover_width = 145; private readonly Box sideStrip; private readonly Container coverContainer; private readonly OsuSpriteText name, status, beatmapTitle, beatmapDash, beatmapArtist; private readonly FillFlowContainer<OsuSpriteText> beatmapInfoFlow; private readonly ParticipantInfo participantInfo; private readonly ModeTypeInfo modeTypeInfo; private readonly Bindable<string> nameBind = new Bindable<string>(); private readonly Bindable<User> hostBind = new Bindable<User>(); private readonly Bindable<RoomStatus> statusBind = new Bindable<RoomStatus>(); private readonly Bindable<GameType> typeBind = new Bindable<GameType>(); private readonly Bindable<BeatmapInfo> beatmapBind = new Bindable<BeatmapInfo>(); private readonly Bindable<User[]> participantsBind = new Bindable<User[]>(); private OsuColour colours; private LocalisationEngine localisation; public readonly Room Room; public DrawableRoom(Room room) { Room = room; RelativeSizeAxes = Axes.X; Height = height; CornerRadius = 5; Masking = true; EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(40), Radius = 5, }; Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = OsuColour.FromHex(@"212121"), }, sideStrip = new Box { RelativeSizeAxes = Axes.Y, Width = side_strip_width, }, new Container { Width = cover_width, RelativeSizeAxes = Axes.Y, Masking = true, Margin = new MarginPadding { Left = side_strip_width }, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, coverContainer = new Container { RelativeSizeAxes = Axes.Both, }, }, }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Vertical = content_padding, Left = side_strip_width + cover_width + content_padding, Right = content_padding, }, Children = new Drawable[] { new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(5f), Children = new Drawable[] { name = new OsuSpriteText { TextSize = 18, }, participantInfo = new ParticipantInfo(), }, }, new FillFlowContainer { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Children = new Drawable[] { status = new OsuSpriteText { TextSize = 14, Font = @"Exo2.0-Bold", }, beatmapInfoFlow = new FillFlowContainer<OsuSpriteText> { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Horizontal, Children = new[] { beatmapTitle = new OsuSpriteText { TextSize = 14, Font = @"Exo2.0-BoldItalic", }, beatmapDash = new OsuSpriteText { TextSize = 14, Font = @"Exo2.0-BoldItalic", }, beatmapArtist = new OsuSpriteText { TextSize = 14, Font = @"Exo2.0-RegularItalic", }, }, }, }, }, modeTypeInfo = new ModeTypeInfo { Anchor = Anchor.BottomRight, Origin = Anchor.BottomRight, }, }, }, }; nameBind.ValueChanged += displayName; hostBind.ValueChanged += displayUser; typeBind.ValueChanged += displayGameType; participantsBind.ValueChanged += displayParticipants; nameBind.BindTo(Room.Name); hostBind.BindTo(Room.Host); statusBind.BindTo(Room.Status); typeBind.BindTo(Room.Type); beatmapBind.BindTo(Room.Beatmap); participantsBind.BindTo(Room.Participants); } [BackgroundDependencyLoader] private void load(OsuColour colours, LocalisationEngine localisation) { this.localisation = localisation; this.colours = colours; beatmapInfoFlow.Colour = colours.Gray9; //binded here instead of ctor because dependencies are needed statusBind.ValueChanged += displayStatus; beatmapBind.ValueChanged += displayBeatmap; statusBind.TriggerChange(); beatmapBind.TriggerChange(); } private void displayName(string value) { name.Text = value; } private void displayUser(User value) { participantInfo.Host = value; } private void displayStatus(RoomStatus value) { if (value == null) return; status.Text = value.Message; foreach (Drawable d in new Drawable[] { sideStrip, status }) d.FadeColour(value.GetAppropriateColour(colours), 100); } private void displayGameType(GameType value) { modeTypeInfo.Type = value; } private void displayBeatmap(BeatmapInfo value) { modeTypeInfo.Beatmap = value; if (value != null) { coverContainer.FadeIn(transition_duration); coverContainer.Children = new[] { new AsyncLoadWrapper(new BeatmapSetCover(value.BeatmapSet) { Anchor = Anchor.Centre, Origin = Anchor.Centre, FillMode = FillMode.Fill, OnLoadComplete = d => d.FadeInFromZero(400, Easing.Out), }) { RelativeSizeAxes = Axes.Both }, }; beatmapTitle.Current = localisation.GetUnicodePreference(value.Metadata.TitleUnicode, value.Metadata.Title); beatmapDash.Text = @" - "; beatmapArtist.Current = localisation.GetUnicodePreference(value.Metadata.ArtistUnicode, value.Metadata.Artist); } else { coverContainer.FadeOut(transition_duration); beatmapTitle.Current = null; beatmapArtist.Current = null; beatmapTitle.Text = "Changing map"; beatmapDash.Text = beatmapArtist.Text = string.Empty; } } private void displayParticipants(User[] value) { participantInfo.Participants = value; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Xml.Linq; using CsQuery; using FormFactory; using FormFactory.Attributes; using FormFactory.RazorEngine; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OneOf; using RazorEngine.Text; using SirenDotNet; using Action = SirenDotNet.Action; using Exception = System.Exception; namespace SirenToHtmlClientProxy { public class ForwardProxyMessageHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var userIp = HttpContext.Current.Request.UserHostAddress; request.Headers.Add("X-Forwarded-For", userIp); IEnumerable<string> destinations; if (!request.Headers.TryGetValues("X-Destination", out destinations)) { return request.CreateErrorResponse(HttpStatusCode.BadRequest, "Please add an X-Destination header e.g. http://firstproxy, http://secondproxy http://endwarehost"); } if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Trace) request.Content = null; var first = new Uri(destinations.First()); Func<string, string> sanitiseUrls = s => s.Replace(first.ToString(), "/"); var uri = new UriBuilder(first.ToString().TrimEnd('/') + '/' + request.RequestUri.PathAndQuery.TrimStart('/')); uri.Host = first.Host; uri.Port = first.Port; request.Headers.Clear(); request.Headers.Remove("X-Destination"); if (destinations.Skip(1).Any()) request.Headers.Add("X-Destination", destinations.Skip(1)); request.Headers.Accept.Clear(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.siren+json")); request.Headers.Host = uri.Host; request.Headers.AcceptEncoding.Clear(); var qs = request.RequestUri.ParseQueryString(); var methodOverride = qs["_method"]; if (methodOverride != null) { request.Method = new HttpMethod(methodOverride); qs.Remove("_method"); } uri.Query = qs.ToString(); request.RequestUri = new Uri(uri.ToString()); if (request.Content != null) await request.Content.LoadIntoBufferAsync(); List<string> httpLog = new List<string>(); using (var httpClient = new HttpClient()) { var requestInitialContent = request.Content; if (requestInitialContent != null) { await requestInitialContent.LoadIntoBufferAsync(); var requestContentStream = await requestInitialContent.ReadAsStreamAsync(); request.Content = new StreamContent(requestContentStream); requestInitialContent.Headers.ToList() .ForEach(kvp => request.Content.Headers.TryAddWithoutValidation(kvp.Key, kvp.Value)); } var responseMessage = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken); request.Content = requestInitialContent; httpLog.Add(ToString(request)); httpLog.Add(ToString(responseMessage)); responseMessage.Headers.TransferEncodingChunked = null; //throws an error on calls to WebApi results if (responseMessage.StatusCode == HttpStatusCode.NotModified) return responseMessage; if (request.Method == HttpMethod.Head) responseMessage.Content = null; if (responseMessage.Content != null) { try { if (request.Method == HttpMethod.Post) { if (responseMessage.StatusCode == HttpStatusCode.Created || responseMessage.StatusCode == HttpStatusCode.Accepted) { if (responseMessage.Headers.Location != null) { var redirectMessage = request.CreateResponse(HttpStatusCode.Moved); redirectMessage.Headers.Location = new Uri(sanitiseUrls(responseMessage.Headers.Location.ToString()), UriKind.Relative); return redirectMessage; } } if (responseMessage.StatusCode == HttpStatusCode.OK) { //fall through to get handler } else { throw new NotImplementedException(); } } if (responseMessage.Content?.Headers?.ContentType?.MediaType == "application/vnd.siren+json") { var content = await responseMessage.Content.ReadAsStringAsync(); var html = ReadSirenAndConvertToForm(sanitiseUrls(content)); html = SplitContainer(html, string.Join(Environment.NewLine,httpLog)); var stringContent = new StringContent(html, Encoding.Default, "text/html"); responseMessage.Content = stringContent; } } catch (Exception ex) { responseMessage.Content = new StringContent(request.RequestUri.ToString() + request.Headers.ToString() + ex.ToString()); } } return responseMessage; } } private static string ReadSirenAndConvertToForm(string content) { var jo = JObject.Parse(content); var entity = jo.ToObject<SirenDotNet.Entity>(); return BuildComponentsForEntity(entity, 1); } private static string BuildComponentsForEntity(Entity entity, int depth) { var list = new List<string>(); if (entity.Title != null) { list.Add($"<h{depth}>{entity.Title}</h{depth}>"); } list.AddRange(entity.Links?.Select(x => BuildPropertyVmFromLink(x).Render(new RazorTemplateHtmlHelper()).ToString()) ?? new List<string>()); depth++; list.AddRange(entity.Entities?.Select(e => BuildPropertyVmFromSubEntity(e, depth)) .Select(entityPropertiesHtml => string.Join(Environment.NewLine, entityPropertiesHtml)) .Select(entityHtml => CsQuery.CQ.Create("<div>").Html(entityHtml).AddClass("subentity").AddClass("depth" + depth).Render()) .ToList() ?? new List<string>()); depth--; ; entity.Properties?.Properties().Select(PropertyVmFromJToken).ToList().ForEach(p => list.Add(p.Render(new RazorTemplateHtmlHelper()).ToString())); entity.Actions?.Select(BuildFormVmFromAction).ToList().ForEach(x => list.Add(x.Render(new RazorTemplateHtmlHelper()).ToString())); return CQ.Create("<div>").Html(string.Join(Environment.NewLine, list)).AddClass("entity").AddClass("depth" + depth).Render(); } private static IEnumerable<string> BuildPropertyVmFromSubEntity(SubEntity e, int depth) { var list = new List<string>(); var embedded = e as SubEntity.Embedded; if (embedded != null) { if (embedded.Title != null) { list.Add($"<h{depth}>{embedded.Title}</h{depth}>"); } embedded.Links?.Select(BuildPropertyVmFromLink).ToList().ForEach(x => list.Add(x.Render(new RazorTemplateHtmlHelper()).ToString())); embedded.Properties?.Properties() .Select(PropertyVmFromJToken) .ToList() .ForEach(x => list.Add(x.Render(new RazorTemplateHtmlHelper()).ToString())); embedded.Actions?.Select(BuildFormVmFromAction).ToList().ForEach(x => list.Add(x.Render(new RazorTemplateHtmlHelper()).ToString())); depth++; list.AddRange(embedded.Entities?.Select(e1 => BuildPropertyVmFromSubEntity(e1, depth)) .Select(entityPropertiesHtml => string.Join(Environment.NewLine, entityPropertiesHtml)) .Select( entityHtml => CsQuery.CQ.Create("<div>") .Html(entityHtml) .AddClass("entity") .AddClass("depth" + depth) .Render()) .ToList() ?? new List<string>()); depth--; return list.AsEnumerable(); } var linked = (SubEntity.Linked) e; if (linked != null) { return new[] { $"<a href='{linked.Href}'>{linked.Title ?? linked.Href.ToString()}</a>" }; } //not implemented return list; } private static PropertyVm PropertyVmFromJToken(JProperty property) { var propertyVm = new PropertyVm(typeof(string), property.Name) { Value = property.Value.ToString(), Readonly = true, DisplayName = property.Name, }; //propertyVm.GetCustomAttributes = () => new object[] {new DataTypeAttribute(DataType.MultilineText)}; return propertyVm; } private static PropertyVm BuildPropertyVmFromLink(Link link) { var element = new XElement("a", new XAttribute("href", link.Href)); var rels = string.Join(", ", link.Rel); element.SetAttributeValue("title", rels); element.Value = link.Title ?? rels; var propertyVm = new PropertyVm(typeof(XElement), rels) { Value = element, Readonly = true, DisplayName = rels, Name = rels, GetCustomAttributes = () => new object[] {new NoLabelAttribute()} }; return propertyVm; } private static string ToString(HttpRequestMessage req) { return CsQuery.CQ.Create("<pre>").Text($"{req.Method} {req.RequestUri}\r\n" + req.Headers.ToString() + req.Content?.Headers.ToString() + FormatIfJson(req.Content)).AddClass("request").Render(); } private string ToString(HttpResponseMessage resp) { return CsQuery.CQ.Create("<pre>").Text($"{(int)resp.StatusCode} {resp.StatusCode}\r\n" + resp.Headers.ToString() + resp.Content?.Headers.ToString() + FormatIfJson(resp.Content)).AddClass("response").AddClass("status" + (int)resp.StatusCode).Render(); } private static string FormatIfJson(HttpContent content) { var mediaType = content?.Headers?.ContentType?.MediaType; if (mediaType == "application/json" || mediaType == "application/vnd.siren+json") { return JToken.Parse(content.ReadAsStringAsync().Result).ToString(Formatting.Indented); } return content?.ReadAsStringAsync().Result; } private static FormVm BuildFormVmFromAction(Action action) { var form = new FormVm { ActionUrl = action.Href.ToString(), DisplayName = action.Title ?? action.Name ?? "link", Method = action?.Method.ToString().ToLower(), Inputs = action.Fields?.Select(field => new PropertyVm(typeof(string), field.Name) {DisplayName = field.Name}) ?.ToArray() ?? Enumerable.Empty<PropertyVm>(), }; if (form.Method != "get" && form.Method != "post") { form.ActionUrl += form.ActionUrl.Contains("?") ? "&" : "?"; form.ActionUrl += "_method=" + form.Method.ToString().ToUpper(); form.Method = "post"; } return form; } string SplitContainer(string left, string right) { return $@" <div class=""split-container""> <div class=""split-item split-left""> {left} </div> <div class=""split-item split-right""> {right} </div> </div> <style> .split-container {{ -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; }} .split-item {{ display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; width: 50%; padding: 3em 5em 6em 5em; }} .request{{ background-color: aliceblue; }} .response{{ background-color: lightgrey; }} .response.status200{{ background-color: f5fff0 }} .entity, .subentity {{ background-color: rgba(220, 220, 220, 0.1); border: solid 1px rgba(220, 220, 220, 0.2); padding: 10px 10px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; }} </style> "; } } }
// // - StreamContext.cs - // // Copyright 2005, 2006, 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Text; namespace Carbonfrost.Commons.Shared.Runtime { [TypeConverter(typeof(StreamContextConverter))] public abstract class StreamContext : IUriContext { public static readonly StreamContext Null = new NullStreamContext(); public static readonly StreamContext Invalid = new InvalidStreamContext(); [SelfDescribingPriority(PriorityLevel.Medium)] public abstract CultureInfo Culture { get; } [SelfDescribingPriority(PriorityLevel.Low)] public virtual ContentType ContentType { get { return ContentType.Parse(ContentTypes.Binary); } } protected Uri BaseUri { get; set; } [SelfDescribingPriority(PriorityLevel.Medium)] public virtual string DisplayName { get { return Uri.PathAndQuery; } } [SelfDescribingPriority(PriorityLevel.Low)] public virtual Encoding Encoding { get { return Utility.GetEncodingFromContentType(this.ContentType.Parameters.GetValueOrDefault("charset")); } } [SelfDescribingPriority(PriorityLevel.Low)] public virtual bool IsAnonymous { get { return false; } } [SelfDescribingPriority(PriorityLevel.Low)] public virtual bool IsLocal { get { return true; } } [SelfDescribingPriority(PriorityLevel.Low)] public virtual bool IsMultipart { get { return false; } } [SelfDescribingPriority(PriorityLevel.High)] public abstract Uri Uri { get; } protected StreamContext() {} public StreamWriter AppendText() { return AppendText(null); } public StreamWriter AppendText(Encoding encoding) { return new StreamWriter( GetStream(FileAccess.Write, FallbackBehavior.ThrowException), encoding ?? this.Encoding); } public abstract StreamContext ChangeCulture(CultureInfo resourceCulture); public abstract StreamContext ChangePath(string relativePath); public virtual StreamContext ChangeContentType(ContentType contentType) { throw new NotSupportedException(); } public virtual StreamContext ChangeEncoding(Encoding encoding) { throw new NotSupportedException(); } public StreamContext ChangeExtension(string extension) { string localName = Path.GetFileName(Uri.LocalPath); int index = localName.LastIndexOf('.'); // $NON-NLS-1 // Replace the local name with the extension index = (index < 0) ? localName.Length - 1 : index; string targetFile = localName.Substring(0, index) + extension; // $NON-NLS-1 return ChangePath("./" + targetFile); // $NON-NLS-1 } public Stream GetStream(FileAccess fileAccess, FallbackBehavior fallbackOn) { Stream result = GetStreamCore(fileAccess); if (result == null) { switch (fallbackOn) { case FallbackBehavior.CreateDefault: return Stream.Null; case FallbackBehavior.None: return null; case FallbackBehavior.ThrowException: default: throw RuntimeFailure.StreamContextDoesNotExist(); } } else { return result; } } public Stream GetStream(FallbackBehavior fallbackOn) { return GetStream(FileAccess.ReadWrite, fallbackOn); } public Stream GetStream() { return GetStream(FallbackBehavior.CreateDefault); } protected abstract Stream GetStreamCore(FileAccess access); public StreamReader OpenText() { return OpenText(null); } public StreamReader OpenText(Encoding encoding) { encoding = encoding ?? this.Encoding; if (encoding == null) return new StreamReader( GetStream(FileAccess.Read, FallbackBehavior.ThrowException)); else return new StreamReader( GetStream(FileAccess.Read, FallbackBehavior.ThrowException), encoding); } public Stream OpenRead() { return GetStream(FileAccess.Read, FallbackBehavior.ThrowException); } public Stream OpenWrite() { return GetStream(FileAccess.Write, FallbackBehavior.ThrowException); } public object ReadValue(Type componentType) { return Activation.FromStreamContext(componentType, this); } public T ReadValue<T>() { return (T) ReadValue(typeof(T)); } public byte[] ReadAllBytes() { using (Stream s = GetStream(FileAccess.Read, FallbackBehavior.ThrowException)) return s.BufferedCopyToBytes(); } public string[] ReadAllLines() { return ReadAllLines(null); } public IEnumerable<string> ReadLines() { return ReadLines(null); } public IEnumerable<string> ReadLines(Encoding encoding) { using (StreamReader reader = OpenText(encoding)) { string s; while ((s = reader.ReadLine()) != null) { yield return s; } } } public string[] ReadAllLines(Encoding encoding) { List<string> result = new List<string>(); result.AddRange(ReadLines(encoding)); return result.ToArray(); } public string ReadAllText(Encoding encoding) { using (StreamReader sr = OpenText(encoding)) { return sr.ReadToEnd(); } } public string ReadAllText() { return ReadAllText(null); } public void WriteValue(Type componentType, object value) { if (componentType == null) throw new ArgumentNullException("componentType"); if (value == null) throw new ArgumentNullException("value"); StreamingSource ss = StreamingSource.Create( componentType, this.ContentType, null, ServiceProvider.Null); ss.Save(this, value); } public void WriteValue<T>(T value) { WriteValue(typeof(T), value); } public void WriteAllBytes(byte[] value) { if (value == null) throw new ArgumentNullException("value"); using (Stream s = GetStream(FileAccess.Write, FallbackBehavior.ThrowException)) new MemoryStream(value).CopyTo(s); } public void WriteAllLines(string[] lines) { if (lines == null) throw new ArgumentNullException("lines"); WriteAllLines(lines, null); } public void WriteAllLines(string[] lines, Encoding encoding) { if (lines == null) throw new ArgumentNullException("lines"); using (TextWriter w = AppendText(encoding)) { foreach (string line in lines) w.WriteLine(line); } } public void WriteAllText(string text, Encoding encoding) { using (StreamWriter sr = AppendText(encoding)) { sr.Write(text); } } public void WriteAllText(string text) { WriteAllText(text, null); } // 'Object' overrides. public override string ToString() { return this.Uri.ToString(); } // Static construction methods. public static StreamContext FromAssemblyManifestResource(Assembly assembly, string resourceName) { if (assembly == null) { throw new ArgumentNullException("assembly"); } // $NON-NLS-1 Require.NotNullOrEmptyString("resourceName", resourceName); // $NON-NLS-1 return new AssemblyManifestResourceStreamContext(assembly, resourceName); } public static StreamContext FromByteArray(byte[] data) { if (data == null) throw new ArgumentNullException("data"); var ms = new MemoryStream(data, false); return new DataStreamContext(ms, ContentType.Parse(ContentTypes.Binary)); } public static StreamContext FromText(string text, Encoding encoding) { if (string.IsNullOrEmpty(text)) return StreamContext.Null; encoding = (encoding ?? Encoding.UTF8); MemoryStream ms = new MemoryStream(encoding.GetBytes(text)); var param = new Dictionary<string, string> { { "charset", encoding.WebName } }; return new DataStreamContext(ms, new ContentType("text", "plain", param)); } public static StreamContext FromText(string text) { return FromText(text, Encoding.UTF8); } public static StreamContext FromFile(string fileName) { return new FileSystemStreamContext(fileName); } public static StreamContext FromFile(string fileName, CultureInfo resourceCulture) { Require.NotNullOrEmptyString("fileName", fileName); // $NON-NLS-1 if (resourceCulture == null) { throw new ArgumentNullException("resourceCulture"); } // $NON-NLS-1 return new FileSystemStreamContext(fileName, resourceCulture, null); } public static StreamContext FromStream(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } // $NON-NLS-1 return new StreamStreamContext(stream, null); } public static StreamContext FromStream(Stream stream, Encoding encoding) { if (stream == null) throw new ArgumentNullException("stream"); // $NON-NLS-1 return new StreamStreamContext(stream, encoding); } public static StreamContext FromSource(Uri source) { if (source == null) throw new ArgumentNullException("source"); // Look for native providers (file, res, iso, mem, stream) if (source.IsAbsoluteUri) { switch (source.Scheme) { case "file": // $NON-NLS-1 return FromFile(source.LocalPath); case "res": // $NON-NLS-1 return AssemblyManifestResourceStreamContext.CreateResFromUri(source); case "data": // $NON-NLS-1 return new DataStreamContext(source); case "invalid": // $NON-NLS-1 return StreamContext.Invalid; case "null": // $NON-NLS-1 return StreamContext.Null; case "stdout": // $NON-NLS-1 return new StreamStreamContext(new Uri("stdout://"), Console.OpenStandardOutput(), Console.OutputEncoding); case "stderr": // $NON-NLS-1 return new StreamStreamContext(new Uri("stderr://"), Console.OpenStandardError(), Console.OutputEncoding); case "stdin": // $NON-NLS-1 return new StreamStreamContext(new Uri("stdin://"), Console.OpenStandardInput(), Console.InputEncoding); case "stream": // $NON-NLS-1 throw RuntimeFailure.ForbiddenStreamStreamContext(); default: // Fall back to the URI return new UriStreamContext(source, null); } } else { // Relative URIs must be handled in this way return FromFile(source.ToString()); } } // IUriContext Uri IUriContext.BaseUri { get { return BaseUri; } set { BaseUri = value; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Discord; namespace gamebot { class gamebot { static void Main(string[] args) => new gamebot().Start(); private static DiscordClient _client = new DiscordClient(); public static string prefix = "g!"; // Sets custom bot prefix List<TicTacToe> TTTGames = new List<TicTacToe>(); public void Start() { _client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}"); _client.MessageReceived += async (s, e) => { try { if (!e.User.IsBot) { string msg = e.Message.RawText; string rawcmd = "no-cmd"; // Filler command if (msg.StartsWith(prefix)) // Check if message starts with prefix rawcmd = msg.Replace(prefix, ""); // Set rawcmd to full command (cmd + arguments) string cmd = rawcmd.Split(' ')[0]; // Grab just the command string[] par = msg.Split(' ').Skip(1).ToArray(); // Grabs the arguments used in the command // string parContents = null; // foreach (string arg in par) // parContents += arg + " "; // Console.WriteLine(parContents); if (cmd == "help") // help command code { string greet = "Heya! I'm gamebot, a bot for automating various games. Here's a list of games/commands you can use:"; string help = "`g!help` - displays info about the bot & bot commands"; string info = "`g!info` - displays extra info about the bot"; string ttt = "`g!ttt` - displays help about tic-tac-toe"; await e.Channel.SendMessage($"{greet}\n\n{help}\n{info}\n{ttt}"); } else if (cmd == "info") // info command { string contributors = "`Noahkiq` and `Technochips`"; string message = $"Heya! I'm gamebot, a bot for automating various games. I've been created by {contributors}. You can report issues, make suggestions, or examine my source code at <https://github.com/Noahkiq/gamebot/>."; await e.Channel.SendMessage(message); } else if (cmd == "ttt") // tictactoe command code { string helpNew = $"Type `{prefix}{cmd} new <mention>` to invite someone to play Tic Tac Toe."; string helpPlay = $"Type `{prefix}{cmd} play <X> <Y>` to place a cross or a circle in a game."; string helpCancel = $"Type `{prefix}{cmd} cancel` to cancel your current game in this channel."; if (par.Length == 1) // checks if only one command argument was supplied { if (par[0] == "new") await e.Channel.SendMessage(helpNew); // outputs the 'helpNew' string if the argument was 'new' else if (par[0] == "play") await e.Channel.SendMessage(helpPlay); // same as above comment, but with 'helpPlay' string and 'play' arg else if (par[0] == "cancel") { int i = TicTacToe.SearchPlayer(TTTGames.ToArray(), e.User, e.Channel); // searches for a game with command runner and channel if (i != -1) //checks if it actually finds a player { TTTGames.RemoveAt(i); // deletes game at 'i', which will be the current game if found await e.Channel.SendMessage($"The game has successfully been cancelled."); } else await e.Channel.SendMessage($"You are currently not in a game in this channel."); } else if (par[0] == "save") { List<JSON.TicTacToe> ttts = new List<JSON.TicTacToe>(); foreach (TicTacToe t in TTTGames) { ttts.Add(t.ToStruct()); } Save.Saves(ttts.ToArray(), "ttt.json"); } else await e.Channel.SendMessage($"{helpNew}\n{helpPlay}\n{helpCancel}"); } else if (par.Length == 2 || par.Length == 4) // checks if two or four arguments were supplied { if (par[0] == "play") await e.Channel.SendMessage(helpPlay); // too few requirements were supplied so help is shown else if (par[0] == "cancel") await e.Channel.SendMessage(helpCancel); else if (par[0] == "new") { User[] mentioned = e.Message.MentionedUsers.ToArray(); if (mentioned.Length != 1 || mentioned[0] == null) await e.Channel.SendMessage(helpNew); // too few (or many) users were mentioned, help is show else { var i = TicTacToe.SearchPlayer(TTTGames.ToArray(), e.User, e.Channel); //search the user var j = TicTacToe.SearchPlayer(TTTGames.ToArray(), mentioned[0], e.Channel); //search the mentioned user if (i == -1 && j == -1) //if it doesn't find anything { if (mentioned[0].IsBot) await e.Channel.SendMessage($"You cannot play against another bot!"); // else if (mentioned[0].Status.Value == UserStatus.Offline) // await e.Channel.SendMessage($"You cannot play against an offline/invisible user!"); else if (mentioned[0] == e.User) await e.Channel.SendMessage($"You cannot play a game with yourself!"); else { if (par.Length == 2) { TTTGames.Add(new TicTacToe(e.User, mentioned[0], e.Channel)); // a new TTT game is added to 'TTTGames' with the command runner, opponent, and channel await e.Channel.SendMessage("A new game has started!"); } else if (par.Length == 4) { bool validInts = true; try { int.Parse(par[2]); int.Parse(par[3]); } catch { validInts = false; } if (validInts) { if (int.Parse(par[2]) < 3 || int.Parse(par[3]) < 3) { await e.Channel.SendMessage("Board must be atleast 3x3."); } else if (int.Parse(par[2]) > 9 || int.Parse(par[3]) > 9) { await e.Channel.SendMessage("Board must be atmost 9x9."); } else { TTTGames.Add(new TicTacToe(e.User, mentioned[0], e.Channel, int.Parse(par[2]), int.Parse(par[3]))); // a new TTT game is added to 'TTTGames' with the command runner, opponent, channel, and board size await e.Channel.SendMessage($"A new game has started with a board size of {int.Parse(par[2])} x {int.Parse(par[3])}!"); } } else await e.Channel.SendMessage($"**Error:** Invalid integers were supplied for the board size."); } } } else if (i != -1) //if it has found the user await e.Channel.SendMessage("You are already in a game in this channel."); //the user cannot play two game in a channel else if (j != -1) //if it has found the mentioned user await e.Channel.SendMessage("They are already in a game in this channel."); //the user cannot play with another user playing another game } } else await e.Channel.SendMessage($"{helpNew}\n{helpPlay}\n{helpCancel}"); // send default help message if no valid commands were detected } else if (par.Length == 3) { if (par[0] == "new") await e.Channel.SendMessage(helpNew); // too many requirements were supplied so help is shown else if (par[0] == "cancel") await e.Channel.SendMessage(helpCancel); else if (par[0] == "play") { int i = TicTacToe.SearchPlayer(TTTGames.ToArray(), e.User, e.Channel); if (i != -1) //checks if it actually finds a player { bool? isc = TTTGames[i].TakeTurn(e.User, int.Parse(par[1]), int.Parse(par[2])); //check the turn if (isc == true) //if the turn was successful { await e.Channel.SendMessage(TTTGames[i].DrawGame()); //write down the game var c = TTTGames[i].CheckGame(); //check if someone wins if (c == TicTacToe.GameStat.CircleWin || c == TicTacToe.GameStat.CrossWin) //if someone wins { await e.Channel.SendMessage($"Congratulation, <@{e.User.Id}>, you won!"); TTTGames.RemoveAt(i); //delete the game } else if (c == TicTacToe.GameStat.Tie) //if there is a tie { await e.Channel.SendMessage("You are both stuck, there is a tie. The game has ended."); TTTGames.RemoveAt(i); //delete the game } //otherwise well the game continues } else if (isc == false) await e.Channel.SendMessage("It's not your turn."); //the user cannot play if it's not his turn else await e.Channel.SendMessage("You can't place a shape onto another shape."); //the user cannot cheat by replacing a shape } else await e.Channel.SendMessage("You are currently not in a game in this channel."); //the user cannot play if he's not playing } else await e.Channel.SendMessage($"{helpNew}\n{helpPlay}\n{helpCancel}"); // invalid arguments given, help displayed } else await e.Channel.SendMessage($"{helpNew}\n{helpPlay}\n{helpCancel}"); } // else if (cmd == "hangman") // hangman command code // { // if (par.Length == 1) // checks if only one command argument was supplied // { // if (par[0] == "new") { // await e.Channel.SendMessage("Setting up game..."); // outputs string // } // } // } else if (cmd == "crash") { throw new Exception("Manual crash tester."); } } } catch (Exception ex) { await e.Channel.SendMessage("**Error:** A unexcepted error happened.\nIf you think this bug should be fixed, go here: <https://github.com/Noahkiq/gamebot/issues>"); if (ex.ToString().Length < 2000) await e.Channel.SendMessage($"```\n{ex}```"); Console.WriteLine(ex); } }; string token = File.ReadAllText("bot-token.txt"); _client.ExecuteAndWait(async () => { await _client.Connect(token, TokenType.Bot); }); _client.Ready += (s, e) => { //Console.WriteLine("a"); if (File.Exists(Save.path + "ttt.json")) { //Console.WriteLine("a"); JSON.TicTacToe[] gamej = Save.Load<JSON.TicTacToe[]>("ttt.json"); //Console.WriteLine(gamej.Length); foreach (JSON.TicTacToe j in gamej) { //Console.WriteLine("b"); TTTGames.Add(TicTacToe.ToClass(j, _client)); } //Console.WriteLine("c"); } }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization { // This abstract class represents a calendar. A calendar reckons time in // divisions such as weeks, months and years. The number, length and start of // the divisions vary in each calendar. // // Any instant in time can be represented as an n-tuple of numeric values using // a particular calendar. For example, the next vernal equinox occurs at (0.0, 0 // , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of // Calendar can map any DateTime value to such an n-tuple and vice versa. The // DateTimeFormat class can map between such n-tuples and a textual // representation such as "8:46 AM March 20th 1999 AD". // // Most calendars identify a year which begins the current era. There may be any // number of previous eras. The Calendar class identifies the eras as enumerated // integers where the current era (CurrentEra) has the value zero. // // For consistency, the first unit in each interval, e.g. the first month, is // assigned the value one. // The calculation of hour/minute/second is moved to Calendar from GregorianCalendar, // since most of the calendars (or all?) have the same way of calcuating hour/minute/second. public abstract partial class Calendar : ICloneable { // Number of 100ns (10E-7 second) ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; private int _currentEraValue = -1; [OptionalField(VersionAdded = 2)] private bool _isReadOnly = false; #if CORECLR internal const CalendarId CAL_HEBREW = CalendarId.HEBREW; internal const CalendarId CAL_HIJRI = CalendarId.HIJRI; internal const CalendarId CAL_JAPAN = CalendarId.JAPAN; internal const CalendarId CAL_JULIAN = CalendarId.JULIAN; internal const CalendarId CAL_TAIWAN = CalendarId.TAIWAN; internal const CalendarId CAL_UMALQURA = CalendarId.UMALQURA; internal const CalendarId CAL_PERSIAN = CalendarId.PERSIAN; #endif // The minimum supported DateTime range for the calendar. public virtual DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } // The maximum supported DateTime range for the calendar. public virtual DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public virtual CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.Unknown; } } protected Calendar() { //Do-nothing constructor. } /// // This can not be abstract, otherwise no one can create a subclass of Calendar. // internal virtual CalendarId ID { get { return CalendarId.UNINITIALIZED_VALUE; } } /// // Return the Base calendar ID for calendars that didn't have defined data in calendarData // internal virtual CalendarId BaseCalendarID { get { return ID; } } //////////////////////////////////////////////////////////////////////// // // IsReadOnly // // Detect if the object is readonly. // //////////////////////////////////////////////////////////////////////// public bool IsReadOnly { get { return (_isReadOnly); } } //////////////////////////////////////////////////////////////////////// // // Clone // // Is the implementation of ICloneable. // //////////////////////////////////////////////////////////////////////// public virtual object Clone() { object o = MemberwiseClone(); ((Calendar)o).SetReadOnlyState(false); return (o); } //////////////////////////////////////////////////////////////////////// // // ReadOnly // // Create a cloned readonly instance or return the input one if it is // readonly. // //////////////////////////////////////////////////////////////////////// public static Calendar ReadOnly(Calendar calendar) { if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); } Contract.EndContractBlock(); if (calendar.IsReadOnly) { return (calendar); } Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone()); clonedCalendar.SetReadOnlyState(true); return (clonedCalendar); } internal void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } internal void SetReadOnlyState(bool readOnly) { _isReadOnly = readOnly; } /*=================================CurrentEraValue========================== **Action: This is used to convert CurretEra(0) to an appropriate era value. **Returns: **Arguments: **Exceptions: **Notes: ** The value is from calendar.nlp. ============================================================================*/ internal virtual int CurrentEraValue { get { // The following code assumes that the current era value can not be -1. if (_currentEraValue == -1) { Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID"); _currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra; } return (_currentEraValue); } } // The current era for a calendar. public const int CurrentEra = 0; internal int twoDigitYearMax = -1; internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue) { if (ticks < minValue.Ticks || ticks > maxValue.Ticks) { throw new ArgumentException( String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange, minValue, maxValue))); } Contract.EndContractBlock(); } internal DateTime Add(DateTime time, double value, int scale) { // From ECMA CLI spec, Partition III, section 3.27: // // If overflow occurs converting a floating-point type to an integer, or if the floating-point value // being converted to an integer is a NaN, the value returned is unspecified. // // Based upon this, this method should be performing the comparison against the double // before attempting a cast. Otherwise, the result is undefined. double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5)); if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis))) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue); } long millis = (long)tempMillis; long ticks = time.Ticks + millis * TicksPerMillisecond; CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // milliseconds to the specified DateTime. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to the specified DateTime. The value // argument is permitted to be negative. // public virtual DateTime AddMilliseconds(DateTime time, double milliseconds) { return (Add(time, milliseconds, 1)); } // Returns the DateTime resulting from adding a fractional number of // days to the specified DateTime. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddDays(DateTime time, int days) { return (Add(time, days, MillisPerDay)); } // Returns the DateTime resulting from adding a fractional number of // hours to the specified DateTime. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddHours(DateTime time, int hours) { return (Add(time, hours, MillisPerHour)); } // Returns the DateTime resulting from adding a fractional number of // minutes to the specified DateTime. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddMinutes(DateTime time, int minutes) { return (Add(time, minutes, MillisPerMinute)); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public abstract DateTime AddMonths(DateTime time, int months); // Returns the DateTime resulting from adding a number of // seconds to the specified DateTime. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddSeconds(DateTime time, int seconds) { return Add(time, seconds, MillisPerSecond); } // Returns the DateTime resulting from adding a number of // weeks to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddWeeks(DateTime time, int weeks) { return (AddDays(time, weeks * 7)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public abstract DateTime AddYears(DateTime time, int years); // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public abstract int GetDayOfMonth(DateTime time); // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public abstract DayOfWeek GetDayOfWeek(DateTime time); // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public abstract int GetDayOfYear(DateTime time); // Returns the number of days in the month given by the year and // month arguments. // public virtual int GetDaysInMonth(int year, int month) { return (GetDaysInMonth(year, month, CurrentEra)); } // Returns the number of days in the month given by the year and // month arguments for the specified era. // public abstract int GetDaysInMonth(int year, int month, int era); // Returns the number of days in the year given by the year argument for the current era. // public virtual int GetDaysInYear(int year) { return (GetDaysInYear(year, CurrentEra)); } // Returns the number of days in the year given by the year argument for the current era. // public abstract int GetDaysInYear(int year, int era); // Returns the era for the specified DateTime value. public abstract int GetEra(DateTime time); /*=================================Eras========================== **Action: Get the list of era values. **Returns: The int array of the era names supported in this calendar. ** null if era is not used. **Arguments: None. **Exceptions: None. ============================================================================*/ public abstract int[] Eras { get; } // Returns the hour part of the specified DateTime. The returned value is an // integer between 0 and 23. // public virtual int GetHour(DateTime time) { return ((int)((time.Ticks / TicksPerHour) % 24)); } // Returns the millisecond part of the specified DateTime. The returned value // is an integer between 0 and 999. // public virtual double GetMilliseconds(DateTime time) { return (double)((time.Ticks / TicksPerMillisecond) % 1000); } // Returns the minute part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetMinute(DateTime time) { return ((int)((time.Ticks / TicksPerMinute) % 60)); } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public abstract int GetMonth(DateTime time); // Returns the number of months in the specified year in the current era. public virtual int GetMonthsInYear(int year) { return (GetMonthsInYear(year, CurrentEra)); } // Returns the number of months in the specified year and era. public abstract int GetMonthsInYear(int year, int era); // Returns the second part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetSecond(DateTime time) { return ((int)((time.Ticks / TicksPerSecond) % 60)); } /*=================================GetFirstDayWeekOfYear========================== **Action: Get the week of year using the FirstDay rule. **Returns: the week of year. **Arguments: ** time ** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday) **Notes: ** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year. ** Assume f is the specifed firstDayOfWeek, ** and n is the day of week for January 1 of the specified year. ** Assign offset = n - f; ** Case 1: offset = 0 ** E.g. ** f=1 ** weekday 0 1 2 3 4 5 6 0 1 ** date 1/1 ** week# 1 2 ** then week of year = (GetDayOfYear(time) - 1) / 7 + 1 ** ** Case 2: offset < 0 ** e.g. ** n=1 f=3 ** weekday 0 1 2 3 4 5 6 0 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 5 days before 1/1. ** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1 ** Case 3: offset > 0 ** e.g. ** f=0 n=2 ** weekday 0 1 2 3 4 5 6 0 1 2 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 2 days before 1/1. ** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1 ============================================================================*/ internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) { int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // Calculate the day of week for the first day of the year. // dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); return ((dayOfYear + offset) / 7 + 1); } private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) { int dayForJan1; int offset; int day; int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); // Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if (offset != 0 && offset >= fullDays) { // // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. // offset -= 7; } // // Calculate the day of year for specified time by taking offset into account. // day = dayOfYear - offset; if (day >= 0) { // // If the day of year value is greater than zero, get the week of year. // return (day / 7 + 1); } // // Otherwise, the specified time falls on the week of previous year. // Call this method again by passing the last day of previous year. // // the last day of the previous year may "underflow" to no longer be a valid date time for // this calendar if we just subtract so we need the subclass to provide us with // that information if (time <= MinSupportedDateTime.AddDays(dayOfYear)) { return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays); } return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays)); } private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek) { int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7; // Calculate the offset (how many days from the start of the year to the start of the week) int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7; if (offset == 0 || offset >= minimumDaysInFirstWeek) { // First of year falls in the first week of the year return 1; } int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7); // starting from first day of the year, how many days do you have to go forward // before getting to the first day of the week? int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7; int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek; if (daysInInitialPartialWeek >= minimumDaysInFirstWeek) { // If the offset is greater than the minimum Days in the first week, it means that // First of year is part of the first week of the year even though it is only a partial week // add another week day += 7; } return (day / 7 + 1); } // it would be nice to make this abstract but we can't since that would break previous implementations protected virtual int DaysInYearBeforeMinSupportedYear { get { return 365; } } // Returns the week of year for the specified DateTime. The returned value is an // integer between 1 and 53. // public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) { throw new ArgumentOutOfRangeException( nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } Contract.EndContractBlock(); switch (rule) { case CalendarWeekRule.FirstDay: return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek)); case CalendarWeekRule.FirstFullWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7)); case CalendarWeekRule.FirstFourDayWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4)); } throw new ArgumentOutOfRangeException( nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range, CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public abstract int GetYear(DateTime time); // Checks whether a given day in the current era is a leap day. This method returns true if // the date is a leap day, or false if not. // public virtual bool IsLeapDay(int year, int month, int day) { return (IsLeapDay(year, month, day, CurrentEra)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public abstract bool IsLeapDay(int year, int month, int day, int era); // Checks whether a given month in the current era is a leap month. This method returns true if // month is a leap month, or false if not. // public virtual bool IsLeapMonth(int year, int month) { return (IsLeapMonth(year, month, CurrentEra)); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public abstract bool IsLeapMonth(int year, int month, int era); // Returns the leap month in a calendar year of the current era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public virtual int GetLeapMonth(int year) { return (GetLeapMonth(year, CurrentEra)); } // 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. // public virtual int GetLeapMonth(int year, int era) { if (!IsLeapYear(year, era)) return 0; int monthsCount = GetMonthsInYear(year, era); for (int month = 1; month <= monthsCount; month++) { if (IsLeapMonth(year, month, era)) return month; } return 0; } // Checks whether a given year in the current era is a leap year. This method returns true if // year is a leap year, or false if not. // public virtual bool IsLeapYear(int year) { return (IsLeapYear(year, CurrentEra)); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public abstract bool IsLeapYear(int year, int era); // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era); internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { result = DateTime.MinValue; try { result = ToDateTime(year, month, day, hour, minute, second, millisecond, era); return true; } catch (ArgumentException) { return false; } } internal virtual bool IsValidYear(int year, int era) { return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime)); } internal virtual bool IsValidMonth(int year, int month, int era) { return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era)); } internal virtual bool IsValidDay(int year, int month, int day, int era) { return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era)); } // Returns and assigns the maximum value to represent a two digit year. This // value is the upper boundary of a 100 year range that allows a two digit year // to be properly translated to a four digit year. For example, if 2029 is the // upper boundary, then a two digit value of 30 should be interpreted as 1930 // while a two digit value of 29 should be interpreted as 2029. In this example // , the 100 year range would be from 1930-2029. See ToFourDigitYear(). public virtual int TwoDigitYearMax { get { return (twoDigitYearMax); } set { VerifyWritable(); twoDigitYearMax = value; } } // Converts the year value to the appropriate century by using the // TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029, // then a two digit value of 30 will get converted to 1930 while a two digit // value of 29 will get converted to 2029. public virtual int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (year < 100) { return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( nameof(millisecond), String.Format( CultureInfo.InvariantCulture, SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1))); } return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond; } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue) { int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID); if (twoDigitYearMax < 0) { twoDigitYearMax = defaultYearValue; } return (twoDigitYearMax); } } }
// Copyright 2009 Auxilium B.V. - http://www.auxilium.nl/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace JelloScrum.Web.Helpers { using System; using System.Collections; using System.Collections.Generic; using System.Text; using Castle.ActiveRecord; using JelloScrum.Model.Entities; using Model; using Model.Enumerations; using NHibernate; using NHibernate.Criterion; using QueryObjects; /// <summary> /// BurnDown functionalteiten /// </summary> public class BurnDown2Helper { /// <summary> /// Berekent de totaal geschatten tijd /// </summary> /// <returns></returns> public TimeSpan TotaalGeschatteTijd(Sprint sprint) { TimeSpan totaal = new TimeSpan(); foreach (SprintStory sprintStory in sprint.SprintStories) { totaal += sprintStory.Estimation; } return totaal; } /// <summary> /// voorheen AantaldagenTotNu /// </summary> /// <param name="sprint"></param> /// <returns></returns> public int AantalWerkdagenTotNu(Sprint sprint) { return CalculateWerkdagen(sprint, DateTime.Today); } /// <summary> /// Voorheen TotaalSprintTijd /// </summary> /// <param name="sprint"></param> /// <returns></returns> public int AantalWerkdagenSprint(Sprint sprint) { return CalculateWerkdagen(sprint, null); } /// <summary> /// // zondag willen we zaterdag van maken /// // checken of deze bestaat, anders steeds 1 dag eraf /// // anders return value /// </summary> /// <param name="date"></param> /// <param name="toeter"></param> /// <returns></returns> public double laatsteWaarde(DateTime date, IDictionary<DateTime, double> toeter) { DateTime gisteren = date.AddDays(-1); while (!toeter.ContainsKey(gisteren.Date)) { gisteren = gisteren.AddDays(-1); } return toeter[gisteren.Date]; } /// <summary> /// Hier worde de datapoint voor de burndown berekent /// </summary> /// <param name="sprint"></param> /// <returns></returns> public IDictionary<DateTime, double> Werk(Sprint sprint) { TotalTimeSpentOnClosedTasksInSprintQuery query = new TotalTimeSpentOnClosedTasksInSprintQuery(); query.Sprint = sprint; ICriteria crit = query.GetQuery(ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(typeof(ModelBase))); crit.AddOrder(Order.Asc("Date")); IList result = crit.List(); IDictionary<DateTime, double> dataPoints = new SortedDictionary<DateTime, double>(); double totaal = TotaalGeschatteTijd(sprint).TotalHours; foreach (TimeRegistration registratie in result) { if (!dataPoints.ContainsKey(registratie.Date.Date)) { dataPoints.Add(registratie.Date.Date, totaal); } totaal -= registratie.Time.TotalHours; dataPoints[registratie.Date.Date] = totaal; } DateTime temp = sprint.StartDate; while (temp <= sprint.EndDate) { if (temp.Date <= DateTime.Today) { if (temp <= sprint.StartDate && !dataPoints.ContainsKey(temp.Date)) { //Als er de eerste dag niet gewerkt is en hij probeer de dag er voor te pakken heb je een infinte loop.. dataPoints.Add(temp.Date, TotaalGeschatteTijd(sprint).TotalHours); } if (temp.DayOfWeek != DayOfWeek.Saturday && temp.DayOfWeek != DayOfWeek.Sunday) { if (!dataPoints.ContainsKey(temp.Date)) { dataPoints.Add(temp.Date, laatsteWaarde(temp, dataPoints)); } } } temp = temp.AddDays(1); } return dataPoints; } private int CalculateWerkdagen(Sprint sprint, DateTime? date) { if (date == null) { date = sprint.EndDate.Date; } int dayCount = 0; DateTime temp = sprint.StartDate; while (temp <= date) { if (temp.DayOfWeek != DayOfWeek.Saturday && temp.DayOfWeek != DayOfWeek.Sunday) { dayCount += 1; } temp = temp.AddDays(1); } return dayCount; } /// private string GenereerJavascript(Sprint sprint) { DateTime startdatum = sprint.StartDate; DateTime einddatum = sprint.EndDate; DateTime temp = startdatum; IList<DateTime> werkdagen = new List<DateTime>(); while (temp <= einddatum) { if (temp.DayOfWeek != DayOfWeek.Saturday && temp.DayOfWeek != DayOfWeek.Sunday) { werkdagen.Add(temp); } temp = temp.AddDays(1); } //Zaken voor de balkjes AllTimeRegistrationsBetweenDatesForSprint alleTijdregistratiesTussenDatumsPerSprint = new AllTimeRegistrationsBetweenDatesForSprint(); alleTijdregistratiesTussenDatumsPerSprint.StartDate = startdatum; alleTijdregistratiesTussenDatumsPerSprint.EndDate = einddatum; alleTijdregistratiesTussenDatumsPerSprint.Sprint = sprint; ICriteria crit = alleTijdregistratiesTussenDatumsPerSprint.GetQuery(ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(typeof(ModelBase))); IList<TimeRegistration> tijdregistraties = crit.List<TimeRegistration>(); IDictionary<DateTime, TimeSpan> totaleTijdPerDag = new Dictionary<DateTime, TimeSpan>(); foreach (TimeRegistration registratie in tijdregistraties) { if (!totaleTijdPerDag.ContainsKey(registratie.Date.Date)) { totaleTijdPerDag.Add(registratie.Date.Date, TimeSpan.Zero); } totaleTijdPerDag[registratie.Date.Date] += registratie.Time; } TimeSpan totaalbestedeTijd = new TimeSpan(); //Zaken voor de ideale lijn double totaalTijd = sprint.GetTotalTimeEstimatedForAllStories().TotalHours; double urenPerDag = totaalTijd / (werkdagen.Count - 1); double aantalNogTeBestedenUren = totaalTijd; StringBuilder stringbuilder = new StringBuilder(); StringBuilder arrayString = new StringBuilder(); StringBuilder arrayTicks = new StringBuilder(); StringBuilder arrayDone = new StringBuilder(); StringBuilder tabelMetGegevens = new StringBuilder(); int i = 0; if (totaalTijd > 0) { int chartWidth = ((werkdagen.Count - 1)*40); double chartHeight = Math.Round((totaalTijd*2) + 150, 0); if (chartWidth < 500) chartWidth = 500; if (chartHeight < 300) chartHeight = 300; stringbuilder.AppendLine("swfobject.embedSWF('/Content/open-flash-chart.swf', 'burndown_chart', '" + chartWidth + "', '" + (chartHeight) + "', '9.0.0');"); stringbuilder.AppendLine("function open_flash_chart_data()"); stringbuilder.AppendLine("{"); stringbuilder.AppendLine("return JSON.stringify(data_1);"); stringbuilder.AppendLine("}"); stringbuilder.Append("var data_1 = {'tooltip': { 'mouse': 2}, 'elements': [{'type': 'line','values':"); arrayString.Append("["); double vandaagBestedeUren = 0; double teveelBestedeUrenVandaag = 0; double afhalenVanNietAfgeslotenUren = 0; double gewonnenTijd = 0; double resterendeUren = 0; double reductieTijdTeVeel = 0; tabelMetGegevens.Append("<table class=\"tablesorter\">"); tabelMetGegevens.Append("<thead>"); tabelMetGegevens.Append("<tr><th>Datum</th><th>Resterende uren</th><th>nietAfgerond</th><th>Afhalen</th><th>Teveel</th><th>gewonnen</th><th>gewerkte uren</th></tr>"); tabelMetGegevens.Append("</thead>"); tabelMetGegevens.Append("<tbody>"); foreach (DateTime werkdag in werkdagen) { //IDEALE LIJN arrayTicks.Append("'" + werkdag.DayOfWeek + " " + werkdag.ToShortDateString() + "'"); arrayString.Append("" + Math.Round(totaalTijd, 0) + ""); totaalTijd = totaalTijd - urenPerDag; //Hier gaan we de bars opbouwen. vandaagBestedeUren = TotaalGewerkteUrenVanNietAfgerondeStoriesVoorDatum(werkdag.Date, sprint);//Groen //Rodebalk gewonnenTijd = GewonnenUrenAanStoriesVoorDatum(werkdag.Date, sprint); teveelBestedeUrenVandaag = TeveelGewerkteUrenAanStoriesVoorDatum(werkdag.Date, sprint);//Rood if(gewonnenTijd > teveelBestedeUrenVandaag) { reductieTijdTeVeel = 0;//We zetten teveel besteed op 0 omdat er meer is gewonnen dan teveel is gewerkt. afhalenVanNietAfgeslotenUren = vandaagBestedeUren;// + reductieTijd; } else if(gewonnenTijd < teveelBestedeUrenVandaag) { reductieTijdTeVeel = teveelBestedeUrenVandaag - gewonnenTijd; afhalenVanNietAfgeslotenUren = vandaagBestedeUren + reductieTijdTeVeel; } else { afhalenVanNietAfgeslotenUren = vandaagBestedeUren ; } //Nu gaan we de blauwe balk opbouwen resterendeUren = Math.Round(sprint.GetTotalEstimatedTimeForNotClosedStoriesTil(werkdag).TotalHours - afhalenVanNietAfgeslotenUren); //Blauw tabelMetGegevens.Append("<tr><td>" + werkdag.DayOfWeek + " " + werkdag.ToShortDateString() + "</td><td>" + resterendeUren + "</td><td>" + sprint.GetTotalEstimatedTimeForNotClosedStoriesTil(werkdag).TotalHours + "</td><td>" + afhalenVanNietAfgeslotenUren + "</td><td>" + teveelBestedeUrenVandaag + "</td><td>" + gewonnenTijd + "</td><td>" + vandaagBestedeUren + "</td></tr>"); arrayDone.Append("[" + resterendeUren + "," + Math.Round(reductieTijdTeVeel) + "," + Math.Round(vandaagBestedeUren) + "]"); //Rest if (werkdag != werkdagen[werkdagen.Count - 1]) { arrayString.Append(","); arrayTicks.Append(","); arrayDone.Append(","); } } tabelMetGegevens.Append("</tbody>"); tabelMetGegevens.Append("</table>"); arrayString.Append("]}"); stringbuilder.Append(arrayString); stringbuilder.Append(",{'type': 'bar_stack', 'colours': [ '#6699ff', '#ff3333' , '#66cc33' ], 'values': [" + arrayDone + "]"); stringbuilder.Append(", 'keys': [ { 'colour': '#6699ff', 'text': 'Nog uit te voeren uren werk', 'font-size': 14 }, { 'colour': '#ff3333', 'text': 'Niet ingeschat werk (overshoot)', 'font-size': 14 }, { 'colour': '#66cc33', 'text': 'Gewerkte uren', 'font-size': 14 } ]"); stringbuilder.Append("}"); stringbuilder.Append("], 'x_axis': { 'labels': { 'rotate': 300, 'labels': [" + arrayTicks + "]} }, 'y_axis': {'min': 0,'max': " + Math.Round((sprint.GetTotalTimeEstimatedForAllStories().TotalHours), 0) + ", 'steps' : 10, 'offset': 300}, 'bg_colour': '#FFFFFF', 'title': { 'text': 'Burndown chart', 'style': 'font-size: 20px;' }"); stringbuilder.Append("};"); } else { stringbuilder.AppendLine("$('#burndown_chart').html('Er is geen schatting ingevuld bij de stories, er kan dus geen burndown gemaakt worden.');"); } //Deze kan je aanzetten om meer inzicht te krijgen in wat er in de burndown gebeurd //stringbuilder.AppendLine("$('#burndown_uitleg').html('" + tabelMetGegevens + "');"); return stringbuilder.ToString(); } /// <summary> /// /// </summary> /// <param name="dateTime"></param> /// <param name="sprint"></param> /// <returns></returns> private double BerekenReedsBestedeUren(DateTime dateTime, Sprint sprint) { double totaalUren = 0; foreach (SprintStory sprintStory in sprint.SprintStories) { } return totaalUren; } private double TotaalGewerkteUrenVanNietAfgerondeStoriesVoorDatum(DateTime dateTime, Sprint sprint) { //We gaan hier de gewerkte uren terug geven van de opgegeven datum //Dit doen we zolang de storie nog niet is afgesloten of tot aan de datum dat hij afgesloten is. //Zijn er meer uren gewerkt dan geschat dan geven we de schatting terug. Het teveel aan gewerkte uren wordt verwerkt in een andere functie. double totaalGewerkteTijd = 0; foreach (SprintStory sprintStory in sprint.SprintStories) { if (sprintStory.State == State.Closed && dateTime.Date < sprintStory.Story.ClosedDate.Value.Date) { //Als er meer werk is gedaan dan dat er is geschat, sturen we de schatting mee. het teveel aan uren zal in rood worden weergegeven. if (sprintStory.Story.TotalTimeSpent(sprint.StartDate, dateTime) < sprintStory.Estimation) { totaalGewerkteTijd += TimeSpanHelper.TimeSpanInMinuten(sprintStory.Story.TotalTimeSpent(sprint.StartDate, dateTime)); } else { //er is meer tijd gewerkt dan geschat dus we gaan de schatting terug geven. totaalGewerkteTijd += TimeSpanHelper.TimeSpanInMinuten(sprintStory.Estimation); } } else if (sprintStory.State != State.Closed) { //Hier gaan we als de story nog niet is afgesloten. if (sprintStory.Story.TotalTimeSpent(sprint.StartDate, dateTime) < sprintStory.Estimation) { totaalGewerkteTijd += TimeSpanHelper.TimeSpanInMinuten(sprintStory.Story.TotalTimeSpent(sprint.StartDate, dateTime)); } else { //er is meer tijd gewerkt dan geschat dus we gaan de schatting terug geven. totaalGewerkteTijd += TimeSpanHelper.TimeSpanInMinuten(sprintStory.Estimation); } } } return totaalGewerkteTijd; } private double TeveelGewerkteUrenAanStoriesVoorDatum(DateTime dateTime, Sprint sprint) { double totaalTeVeelGewerkteTijd = 0; foreach (SprintStory sprintStory in sprint.SprintStories) { /* if (sprintStory.Status == Status.Afgesloten && dateTime.Date < sprintStory.Story.DatumAfgesloten.Value.Date) { //Als er meer werk is gedaan dan dat er is geschat, sturen we de schatting mee. het teveel aan uren zal in rood worden weergegeven. if (sprintStory.Story.TotaalBestedeTijd(sprint.StartDatum, dateTime) > sprintStory.Schatting) { totaalTeVeelGewerkteTijd += TimeSpanHelper.TimeSpanInMinuten(sprintStory.Story.TotaalBestedeTijd(sprint.StartDatum, dateTime) - sprintStory.Schatting); } } else if (sprintStory.Status != Status.Afgesloten) {*/ //Hier gaan we als de story nog niet is afgesloten. if (sprintStory.Story.TotalTimeSpent(sprint.StartDate, dateTime) > sprintStory.Estimation) { totaalTeVeelGewerkteTijd += TimeSpanHelper.TimeSpanInMinuten(sprintStory.Story.TotalTimeSpent(sprint.StartDate, dateTime) - sprintStory.Estimation); } //} } return totaalTeVeelGewerkteTijd; } private double GewonnenUrenAanStoriesVoorDatum(DateTime dateTime, Sprint sprint) { double gewonnenUren = 0; foreach (SprintStory sprintStory in sprint.SprintStories) { if (sprintStory.State == State.Closed && dateTime.Date >= sprintStory.Story.ClosedDate.Value.Date && sprintStory.Story.TotalTimeSpent(sprint.StartDate, dateTime) < sprintStory.Estimation) { //Als het werk sneller is afgerond voor afgesloten stories betekend dit dat we extra ruimte hebben verkregen om te ontwikkellen. gewonnenUren += TimeSpanHelper.TimeSpanInMinuten(sprintStory.Estimation - sprintStory.Story.TotalTimeSpent(sprint.StartDate, dateTime)); } } return gewonnenUren; } } }
// Visual Studio Shared Project // 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, // MERCHANTABILITY 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.ComponentModel.Design; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudioTools.Project; namespace Microsoft.VisualStudioTools.Navigation { /// <summary> /// Inplementation of the service that builds the information to expose to the symbols /// navigation tools (class view or object browser) from the source files inside a /// hierarchy. /// </summary> internal abstract partial class LibraryManager : IDisposable, IVsRunningDocTableEvents { private readonly CommonPackage/*!*/ _package; private readonly Dictionary<uint, TextLineEventListener> _documents; private readonly Dictionary<IVsHierarchy, HierarchyInfo> _hierarchies = new Dictionary<IVsHierarchy, HierarchyInfo>(); private readonly Dictionary<ModuleId, LibraryNode> _files; private readonly Library _library; private readonly IVsEditorAdaptersFactoryService _adapterFactory; private uint _objectManagerCookie; private uint _runningDocTableCookie; public LibraryManager(CommonPackage/*!*/ package) { Contract.Assert(package != null); _package = package; _documents = new Dictionary<uint, TextLineEventListener>(); _library = new Library(new Guid(CommonConstants.LibraryGuid)); _library.LibraryCapabilities = (_LIB_FLAGS2)_LIB_FLAGS.LF_PROJECT; _files = new Dictionary<ModuleId, LibraryNode>(); var model = ((IServiceContainer)package).GetService(typeof(SComponentModel)) as IComponentModel; _adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>(); // Register our library now so it'll be available for find all references RegisterLibrary(); } public Library Library { get { return _library; } } public virtual LibraryNode CreateFileLibraryNode(LibraryNode parent, HierarchyNode hierarchy, string name, string filename) { return new LibraryNode(null, name, filename, LibraryNodeType.Namespaces); } private object GetPackageService(Type/*!*/ type) { return ((System.IServiceProvider)_package).GetService(type); } private void RegisterForRDTEvents() { if (0 != _runningDocTableCookie) { return; } IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (null != rdt) { // Do not throw here in case of error, simply skip the registration. rdt.AdviseRunningDocTableEvents(this, out _runningDocTableCookie); } } private void UnregisterRDTEvents() { if (0 == _runningDocTableCookie) { return; } IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (null != rdt) { // Do not throw in case of error. rdt.UnadviseRunningDocTableEvents(_runningDocTableCookie); } _runningDocTableCookie = 0; } #region ILibraryManager Members public virtual void RegisterHierarchy(IVsHierarchy hierarchy) { if ((null == hierarchy) || _hierarchies.ContainsKey(hierarchy)) { return; } var commonProject = hierarchy.GetProject()?.GetCommonProject(); if (commonProject == null) { return; } RegisterLibrary(); HierarchyListener listener = new HierarchyListener(hierarchy, this); var node = _hierarchies[hierarchy] = new HierarchyInfo( listener, new ProjectLibraryNode(commonProject) ); _library.AddNode(node.ProjectLibraryNode); listener.StartListening(false); RegisterForRDTEvents(); } private void RegisterLibrary() { if (0 == _objectManagerCookie) { IVsObjectManager2 objManager = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2; if (null == objManager) { return; } Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( objManager.RegisterSimpleLibrary(_library, out _objectManagerCookie)); } } public virtual void UnregisterHierarchy(IVsHierarchy hierarchy) { if ((null == hierarchy) || !_hierarchies.ContainsKey(hierarchy)) { return; } HierarchyInfo info = _hierarchies[hierarchy]; if (null != info) { info.Listener.Dispose(); } _hierarchies.Remove(hierarchy); _library.RemoveNode(info.ProjectLibraryNode); if (0 == _hierarchies.Count) { UnregisterRDTEvents(); } lock (_files) { ModuleId[] keys = new ModuleId[_files.Keys.Count]; _files.Keys.CopyTo(keys, 0); foreach (ModuleId id in keys) { if (hierarchy.Equals(id.Hierarchy)) { _library.RemoveNode(_files[id]); _files.Remove(id); } } } // Remove the document listeners. uint[] docKeys = new uint[_documents.Keys.Count]; _documents.Keys.CopyTo(docKeys, 0); foreach (uint id in docKeys) { TextLineEventListener docListener = _documents[id]; if (hierarchy.Equals(docListener.FileID.Hierarchy)) { _documents.Remove(id); docListener.Dispose(); } } } public void RegisterLineChangeHandler(uint document, TextLineChangeEvent lineChanged, Action<IVsTextLines> onIdle) { _documents[document].OnFileChangedImmediate += delegate (object sender, TextLineChange[] changes, int fLast) { lineChanged(sender, changes, fLast); }; _documents[document].OnFileChanged += (sender, args) => onIdle(args.TextBuffer); } #endregion #region Library Member Production /// <summary> /// Overridden in the base class to receive notifications of when a file should /// be analyzed for inclusion in the library. The derived class should queue /// the parsing of the file and when it's complete it should call FileParsed /// with the provided LibraryTask and an IScopeNode which provides information /// about the members of the file. /// </summary> protected virtual void OnNewFile(LibraryTask task) { } /// <summary> /// Called by derived class when a file has been parsed. The caller should /// provide the LibraryTask received from the OnNewFile call and an IScopeNode /// which represents the contents of the library. /// /// It is safe to call this method from any thread. /// </summary> protected void FileParsed(LibraryTask task) { try { var project = task.ModuleID.Hierarchy.GetProject()?.GetCommonProject(); if (project == null) { return; } HierarchyNode fileNode = fileNode = project.NodeFromItemId(task.ModuleID.ItemID); HierarchyInfo parent; if (fileNode == null || !_hierarchies.TryGetValue(task.ModuleID.Hierarchy, out parent)) { return; } LibraryNode module = CreateFileLibraryNode( parent.ProjectLibraryNode, fileNode, System.IO.Path.GetFileName(task.FileName), task.FileName ); // TODO: Creating the module tree should be done lazily as needed // Currently we replace the entire tree and rely upon the libraries // update count to invalidate the whole thing. We could do this // finer grained and only update the changed nodes. But then we // need to make sure we're not mutating lists which are handed out. if (null != task.ModuleID) { LibraryNode previousItem = null; lock (_files) { if (_files.TryGetValue(task.ModuleID, out previousItem)) { _files.Remove(task.ModuleID); parent.ProjectLibraryNode.RemoveNode(previousItem); } } } parent.ProjectLibraryNode.AddNode(module); _library.Update(); if (null != task.ModuleID) { lock (_files) { _files.Add(task.ModuleID, module); } } } catch (COMException) { // we're shutting down and can't get the project } } #endregion #region Hierarchy Events private void OnNewFile(object sender, HierarchyEventArgs args) { IVsHierarchy hierarchy = sender as IVsHierarchy; if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) { return; } ITextBuffer buffer = null; if (null != args.TextBuffer) { buffer = _adapterFactory.GetDocumentBuffer(args.TextBuffer); } var id = new ModuleId(hierarchy, args.ItemID); OnNewFile(new LibraryTask(args.CanonicalName, buffer, new ModuleId(hierarchy, args.ItemID))); } /// <summary> /// Handles the delete event, checking to see if this is a project item. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnDeleteFile(object sender, HierarchyEventArgs args) { IVsHierarchy hierarchy = sender as IVsHierarchy; if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) { return; } OnDeleteFile(hierarchy, args); } /// <summary> /// Does a delete w/o checking if it's a non-meber item, for handling the /// transition from member item to non-member item. /// </summary> private void OnDeleteFile(IVsHierarchy hierarchy, HierarchyEventArgs args) { ModuleId id = new ModuleId(hierarchy, args.ItemID); LibraryNode node = null; lock (_files) { if (_files.TryGetValue(id, out node)) { _files.Remove(id); HierarchyInfo parent; if (_hierarchies.TryGetValue(hierarchy, out parent)) { parent.ProjectLibraryNode.RemoveNode(node); } } } if (null != node) { _library.RemoveNode(node); } } private void IsNonMemberItemChanged(object sender, HierarchyEventArgs args) { IVsHierarchy hierarchy = sender as IVsHierarchy; if (null == hierarchy) { return; } if (!IsNonMemberItem(hierarchy, args.ItemID)) { OnNewFile(hierarchy, args); } else { OnDeleteFile(hierarchy, args); } } /// <summary> /// Checks whether this hierarchy item is a project member (on disk items from show all /// files aren't considered project members). /// </summary> protected bool IsNonMemberItem(IVsHierarchy hierarchy, uint itemId) { object val; int hr = hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_IsNonMemberItem, out val); return ErrorHandler.Succeeded(hr) && (bool)val; } #endregion #region IVsRunningDocTableEvents Members public int OnAfterAttributeChange(uint docCookie, uint grfAttribs) { if ((grfAttribs & (uint)(__VSRDTATTRIB.RDTA_MkDocument)) == (uint)__VSRDTATTRIB.RDTA_MkDocument) { IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt != null) { uint flags, readLocks, editLocks, itemid; IVsHierarchy hier; IntPtr docData = IntPtr.Zero; string moniker; int hr; try { hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out editLocks, out moniker, out hier, out itemid, out docData); TextLineEventListener listner; if (_documents.TryGetValue(docCookie, out listner)) { listner.FileName = moniker; } } finally { if (IntPtr.Zero != docData) { Marshal.Release(docData); } } } } return VSConstants.S_OK; } public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame) { return VSConstants.S_OK; } public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) { return VSConstants.S_OK; } public int OnAfterSave(uint docCookie) { return VSConstants.S_OK; } public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame) { // Check if this document is in the list of the documents. if (_documents.ContainsKey(docCookie)) { return VSConstants.S_OK; } // Get the information about this document from the RDT. IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (null != rdt) { // Note that here we don't want to throw in case of error. uint flags; uint readLocks; uint writeLoks; string documentMoniker; IVsHierarchy hierarchy; uint itemId; IntPtr unkDocData; int hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out writeLoks, out documentMoniker, out hierarchy, out itemId, out unkDocData); try { if (Microsoft.VisualStudio.ErrorHandler.Failed(hr) || (IntPtr.Zero == unkDocData)) { return VSConstants.S_OK; } // Check if the herarchy is one of the hierarchies this service is monitoring. if (!_hierarchies.ContainsKey(hierarchy)) { // This hierarchy is not monitored, we can exit now. return VSConstants.S_OK; } // Check the file to see if a listener is required. if (_package.IsRecognizedFile(documentMoniker)) { return VSConstants.S_OK; } // Create the module id for this document. ModuleId docId = new ModuleId(hierarchy, itemId); // Try to get the text buffer. IVsTextLines buffer = Marshal.GetObjectForIUnknown(unkDocData) as IVsTextLines; // Create the listener. TextLineEventListener listener = new TextLineEventListener(buffer, documentMoniker, docId); // Set the event handler for the change event. Note that there is no difference // between the AddFile and FileChanged operation, so we can use the same handler. listener.OnFileChanged += new EventHandler<HierarchyEventArgs>(OnNewFile); // Add the listener to the dictionary, so we will not create it anymore. _documents.Add(docCookie, listener); } finally { if (IntPtr.Zero != unkDocData) { Marshal.Release(unkDocData); } } } // Always return success. return VSConstants.S_OK; } public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) { if ((0 != dwEditLocksRemaining) || (0 != dwReadLocksRemaining)) { return VSConstants.S_OK; } TextLineEventListener listener; if (!_documents.TryGetValue(docCookie, out listener) || (null == listener)) { return VSConstants.S_OK; } using (listener) { _documents.Remove(docCookie); // Now make sure that the information about this file are up to date (e.g. it is // possible that Class View shows something strange if the file was closed without // saving the changes). HierarchyEventArgs args = new HierarchyEventArgs(listener.FileID.ItemID, listener.FileName); OnNewFile(listener.FileID.Hierarchy, args); } return VSConstants.S_OK; } #endregion public void OnIdle(IOleComponentManager compMgr) { foreach (TextLineEventListener listener in _documents.Values) { if (compMgr.FContinueIdle() == 0) { break; } listener.OnIdle(); } } #region IDisposable Members public void Dispose() { // Dispose all the listeners. foreach (var info in _hierarchies.Values) { info.Listener.Dispose(); } _hierarchies.Clear(); foreach (TextLineEventListener textListener in _documents.Values) { textListener.Dispose(); } _documents.Clear(); // Remove this library from the object manager. if (0 != _objectManagerCookie) { IVsObjectManager2 mgr = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2; if (null != mgr) { mgr.UnregisterLibrary(_objectManagerCookie); } _objectManagerCookie = 0; } // Unregister this object from the RDT events. UnregisterRDTEvents(); _library.Dispose(); } #endregion class HierarchyInfo { public readonly HierarchyListener Listener; public readonly ProjectLibraryNode ProjectLibraryNode; public HierarchyInfo(HierarchyListener listener, ProjectLibraryNode projectLibNode) { Listener = listener; ProjectLibraryNode = projectLibNode; } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Microsoft.Win32; using NLog; using NLog.Common; using NLog.Internal; using NLog.Config; using System.ComponentModel; using NLog.Layouts; /// <summary> /// A value from the Registry. /// </summary> [LayoutRenderer("registry")] public class RegistryLayoutRenderer : LayoutRenderer { /// <summary> /// Create new renderer /// </summary> public RegistryLayoutRenderer() { RequireEscapingSlashesInDefaultValue = true; } /// <summary> /// Gets or sets the registry value name. /// </summary> /// <docgen category='Registry Options' order='10' /> public Layout Value { get; set; } /// <summary> /// Gets or sets the value to be output when the specified registry key or value is not found. /// </summary> /// <docgen category='Registry Options' order='10' /> public Layout DefaultValue { get; set; } /// <summary> /// Require escaping backward slashes in <see cref="DefaultValue"/>. Need to be backwardscompatible. /// /// When true: /// /// `\` in value should be configured as `\\` /// `\\` in value should be configured as `\\\\`. /// </summary> /// <remarks>Default value wasn't a Layout before and needed an escape of the slash</remarks> [DefaultValue(true)] public bool RequireEscapingSlashesInDefaultValue { get; set; } #if !NET3_5 /// <summary> /// Gets or sets the registry view (see: https://msdn.microsoft.com/de-de/library/microsoft.win32.registryview.aspx). /// Allowed values: Registry32, Registry64, Default /// </summary> [DefaultValue("Default")] public RegistryView View { get; set; } #endif /// <summary> /// Gets or sets the registry key. /// </summary> /// <example> /// HKCU\Software\NLogTest /// </example> /// <remarks> /// Possible keys: /// <ul> ///<li>HKEY_LOCAL_MACHINE</li> ///<li>HKLM</li> ///<li>HKEY_CURRENT_USER</li> ///<li>HKCU</li> ///<li>HKEY_CLASSES_ROOT</li> ///<li>HKEY_USERS</li> ///<li>HKEY_CURRENT_CONFIG</li> ///<li>HKEY_DYN_DATA</li> ///<li>HKEY_PERFORMANCE_DATA</li> /// </ul> /// </remarks> /// <docgen category='Registry Options' order='10' /> [RequiredParameter] public Layout Key { get; set; } /// <summary> /// Reads the specified registry key and value and appends it to /// the passed <see cref="StringBuilder"/>. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event. Ignored.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { Object registryValue = null; // Value = null is necessary for querying "unnamed values" string renderedValue = this.Value != null ? this.Value.Render(logEvent) : null; var parseResult = ParseKey(this.Key.Render(logEvent)); try { #if !NET3_5 using (RegistryKey rootKey = RegistryKey.OpenBaseKey(parseResult.Hive, View)) #else var rootKey = MapHiveToKey(parseResult.Hive); #endif { if (parseResult.HasSubKey) { using (RegistryKey registryKey = rootKey.OpenSubKey(parseResult.SubKey)) { if (registryKey != null) registryValue = registryKey.GetValue(renderedValue); } } else { registryValue = rootKey.GetValue(renderedValue); } } } catch (Exception ex) { InternalLogger.Error("Error when writing to registry"); if (ex.MustBeRethrown()) { throw; } } string value = null; if (registryValue != null) // valid value returned from registry will never be null { value = Convert.ToString(registryValue, CultureInfo.InvariantCulture); } else if (this.DefaultValue != null) { value = this.DefaultValue.Render(logEvent); if (RequireEscapingSlashesInDefaultValue) { //remove escape slash value = value.Replace("\\\\", "\\"); } } builder.Append(value); } private class ParseResult { public string SubKey { get; set; } public RegistryHive Hive { get; set; } /// <summary> /// Has <see cref="SubKey"/>? /// </summary> public bool HasSubKey { get { return !string.IsNullOrEmpty(SubKey); } } } /// <summary> /// Parse key to <see cref="RegistryHive"/> and subkey. /// </summary> /// <param name="key">full registry key name</param> /// <returns>Result of parsing, never <c>null</c>.</returns> private static ParseResult ParseKey(string key) { string hiveName; int pos = key.IndexOfAny(new char[] { '\\', '/' }); string subkey = null; if (pos >= 0) { hiveName = key.Substring(0, pos); //normalize slashes subkey = key.Substring(pos + 1).Replace('/', '\\'); //remove starting slashes subkey = subkey.TrimStart('\\'); //replace double slashes from pre-layout times subkey = subkey.Replace("\\\\", "\\"); } else { hiveName = key; } var hive = ParseHiveName(hiveName); return new ParseResult { SubKey = subkey, Hive = hive, }; } /// <summary> /// Aliases for the hives. See https://msdn.microsoft.com/en-us/library/ctb3kd86(v=vs.110).aspx /// </summary> private static readonly Dictionary<string, RegistryHive> HiveAliases = new Dictionary<string, RegistryHive>(StringComparer.InvariantCultureIgnoreCase) { {"HKEY_LOCAL_MACHINE", RegistryHive.LocalMachine}, {"HKLM", RegistryHive.LocalMachine}, {"HKEY_CURRENT_USER", RegistryHive.CurrentUser}, {"HKCU", RegistryHive.CurrentUser}, {"HKEY_CLASSES_ROOT", RegistryHive.ClassesRoot}, {"HKEY_USERS", RegistryHive.Users}, {"HKEY_CURRENT_CONFIG", RegistryHive.CurrentConfig}, {"HKEY_DYN_DATA", RegistryHive.DynData}, {"HKEY_PERFORMANCE_DATA", RegistryHive.PerformanceData}, }; private static RegistryHive ParseHiveName(string hiveName) { RegistryHive hive; if (HiveAliases.TryGetValue(hiveName, out hive)) { return hive; } //ArgumentException is consistent throw new ArgumentException(string.Format("Key name is not supported. Root hive '{0}' not recognized.", hiveName)); } #if NET3_5 private static RegistryKey MapHiveToKey(RegistryHive hive) { switch (hive) { case RegistryHive.LocalMachine: return Registry.LocalMachine; case RegistryHive.CurrentUser: return Registry.CurrentUser; default: throw new ArgumentException("Only RegistryHive.LocalMachine and RegistryHive.CurrentUser are supported.", "hive"); } } #endif } } #endif
#pragma warning disable 162,108,618 using Casanova.Prelude; using System.Linq; using System; using System.Collections.Generic; using UnityEngine; namespace Game {public class World : MonoBehaviour{ public static int frame; void Update () { Update(Time.deltaTime, this); frame++; } public bool JustEntered = true; public void Start() { Cubes = ( Enumerable.Empty<Cube>()).ToList<Cube>(); } public List<Cube> __Cubes; public List<Cube> Cubes{ get { return __Cubes; } set{ __Cubes = value; foreach(var e in value){if(e.JustEntered){ e.JustEntered = false; } } } } System.DateTime init_time = System.DateTime.Now; public void Update(float dt, World world) { var t = System.DateTime.Now; this.Rule0(dt, world); for(int x0 = 0; x0 < Cubes.Count; x0++) { Cubes[x0].Update(dt, world); } this.Rule1(dt, world); } public void Rule0(float dt, World world) { Cubes = ( (Cubes).Select(__ContextSymbol1 => new { ___c00 = __ContextSymbol1 }) .Where(__ContextSymbol2 => ((__ContextSymbol2.___c00.UnityCube.Destroyed) == (false))) .Select(__ContextSymbol3 => __ContextSymbol3.___c00) .ToList<Cube>()).ToList<Cube>(); } int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: if(!(UnityEngine.Input.GetKeyDown(KeyCode.Space))) { s1 = -1; return; }else { goto case 0; } case 0: Cubes = new Cons<Cube>(new Cube(), (Cubes)).ToList<Cube>(); s1 = -1; return; default: return;}} } public class Cube{ public int frame; public bool JustEntered = true; public int ID; public Cube() {JustEntered = false; frame = World.frame; UnityCube = UnityCube.Instantiate(); Factor = 0f; } public UnityEngine.Color Color{ set{UnityCube.Color = value; } } public System.Boolean Destroyed{ get { return UnityCube.Destroyed; } set{UnityCube.Destroyed = value; } } public System.Single Factor; public System.Single Scale{ get { return UnityCube.Scale; } set{UnityCube.Scale = value; } } public UnityCube UnityCube; public UnityEngine.Animation animation{ get { return UnityCube.animation; } } public UnityEngine.AudioSource audio{ get { return UnityCube.audio; } } public UnityEngine.Camera camera{ get { return UnityCube.camera; } } public UnityEngine.Collider collider{ get { return UnityCube.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityCube.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityCube.constantForce; } } public System.Boolean enabled{ get { return UnityCube.enabled; } set{UnityCube.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityCube.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityCube.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityCube.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityCube.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityCube.hideFlags; } set{UnityCube.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityCube.hingeJoint; } } public UnityEngine.Light light{ get { return UnityCube.light; } } public System.String name{ get { return UnityCube.name; } set{UnityCube.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityCube.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityCube.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityCube.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityCube.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityCube.rigidbody2D; } } public System.String tag{ get { return UnityCube.tag; } set{UnityCube.tag = value; } } public UnityEngine.Transform transform{ get { return UnityCube.transform; } } public System.Boolean useGUILayout{ get { return UnityCube.useGUILayout; } set{UnityCube.useGUILayout = value; } } public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule3(dt, world); } public void Rule0(float dt, World world) { Color = Color.Lerp(Color.white,Color.blue,Factor); } int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: if(!(((((Factor) > (2f))) || (((Factor) == (2f)))))) { s1 = -1; return; }else { goto case 0; } case 0: Destroyed = true; s1 = -1; return; default: return;}} int s2=-1; public void Rule2(float dt, World world){ switch (s2) { case -1: Scale = ((1f) - (((Factor) / (2f)))); s2 = -1; return; default: return;}} int s3=-1; public void Rule3(float dt, World world){ switch (s3) { case -1: Factor = ((Factor) + (0.02f)); s3 = -1; return; default: return;}} } }
using System.Collections.Generic; using System.Linq; namespace EZData { public delegate void ItemInsertDelegate(int position, Context insertedItem); public delegate void ItemRemoveDelegate(int position); public delegate void ItemsClearDelegate(); public delegate void SelectionChangeDelegate(); public delegate void ItemsReorderDelegate(int oldPosition, int newPosition); public abstract class Collection : Context { public event ItemInsertDelegate OnItemInsert; public event ItemRemoveDelegate OnItemRemove; public event ItemsClearDelegate OnItemsClear; public event SelectionChangeDelegate OnSelectionChange; public event ItemsReorderDelegate OnItemsReorder; protected void InvokeOnItemInsert(int position, Context insertedItem) { if (OnItemInsert != null) OnItemInsert(position, insertedItem); } protected void InvokeOnItemRemove(int position) { if (OnItemRemove != null) OnItemRemove(position); } protected void InvokeOnItemsClear() { if (OnItemsClear != null) OnItemsClear(); } protected void InvokeOnSelectionChange() { if (OnSelectionChange != null) OnSelectionChange(); } protected void InvokeOnItemsReorder(int from, int to) { if (OnItemsReorder != null) OnItemsReorder(from, to); } public abstract int ItemsCount { get; protected set; } public abstract int SelectedIndex { get; set; } public abstract bool FirstItemSelected { get; protected set; } public abstract bool LastItemSelected { get; protected set; } public abstract Context GetBaseItem(int index); public abstract void SelectItem(int index); public abstract void MoveItem(int from, int to); public abstract void Remove(int index); public abstract IEnumerable<Context> BaseItems { get; } public abstract VariableContext GetItemPlaceholder(int collectionItemIndex); } public class Collection<T> : Collection where T : Context { private readonly bool _autoSelect; public Collection() : this(false) { } public Collection(bool autoSelect) { _autoSelect = autoSelect; SelectedIndex = -1; } public override Context GetBaseItem(int index) { #if UNITY_FLASH return ((object)GetItem(index)) as Context; // forcing explicit cast in AS3 #else return GetItem(index); #endif } public T GetItem(int index) { if (index < 0 || index >= _items.Count) return null; return _items[index]; } public override void SelectItem(int index) { if (index < 0 || index >= _items.Count) SetSelectedItem(-1, null); else SetSelectedItem(index, _items[index]); } public override void MoveItem(int from, int to) { if (from < 0 || from >= _items.Count || to < 0 || to >= _items.Count) return; if (from == to) return; var temp = GetItem(from); _items.RemoveAt(from); _items.Insert(to, temp); UpdateAuxProperties(); InvokeOnItemsReorder(from, to); } public override IEnumerable<Context> BaseItems { get { var baseItems = new List<Context>(); foreach(var i in _items) { baseItems.Add(i); } return baseItems; } } public IEnumerable<T> Items { get { return _items; } } public void Add(T item) { Insert(_items.Count, item); } public void Remove(T item) { for (var i = 0; i < _items.Count; i++) { if (_items[i] != item) continue; if (SelectedItem == _items[i]) SelectItem(-1); Remove(i); break; } } public void Insert(int position, T item) { if (position < 0 || position >= _items.Count) position = _items.Count; // Do not change the order of actions here, if you think that you need inserted item to be in the // collection when you're inside of OnItemInsert, think again. Inserted item is available as // an argument of a notifiation, you can use that. And changing the order here for convenience // in your tool, may cause logical bugs in another tools that rely on this library. // General pattern with this notifications is based on two rules (that you can only rely on): // 1 - notification happens before collection is affected // 2 - affected item is somehow available inside the notification routine InvokeOnItemInsert(position, item); _items.Insert(position, item); UpdateAuxProperties(); if (_autoSelect && _items.Count == 1) SelectItem(0); } public override void Remove(int index) { if (index < 0 || index >= _items.Count) return; // Do not change the order of actions here, if you think that item shouldn't already exist in // collection when you're inside of OnItemRemove, think again. Removed item may be still needed there. // And changing the order here for convenience in your tool, may (and will) cause logical bugs in another // tools that rely on this library. // General pattern with this notifications is based on two rules (that you can only rely on): // 1 - notification happens before collection is affected // 2 - affected item is somehow available inside the notification routine InvokeOnItemRemove(index); _items.RemoveAt(index); UpdateAuxProperties(); if (_autoSelect && _items.Count > 0) { SelectItem(System.Math.Max(0, System.Math.Min(SelectedIndex, _items.Count - 1))); } else { SelectItem(SelectedIndex); } } public void Clear() { // Do not change the order of actions here, if you think that collection should be already empty // when you're inside of OnItemsClear, think again. Changing the order here for convenience // in your tool, may cause logical bugs in another tools that rely on this library. // General pattern with this notifications is based on two rules (that you can only rely on): // 1 - notification happens before collection is affected // 2 - affected item is somehow available inside the notification routine InvokeOnItemsClear(); SelectItem(-1); _items.Clear(); UpdateAuxProperties(); } public int Count { get { return ItemsCount; } } private readonly ReadonlyProperty<int> _selectedIndexProperty = new ReadonlyProperty<int>(); public ReadonlyProperty<int> SelectedIndexProperty { get { return _selectedIndexProperty; } } public override int SelectedIndex { get { return SelectedIndexProperty.GetValue(); } set { SelectedIndexProperty.InternalSetValue(value); } } #region SelectedItem public readonly EZData.VariableContext<T> SelectedItemEzVariableContext = new EZData.VariableContext<T>(null); public T SelectedItem { get { return SelectedItemEzVariableContext.Value; } set { SelectedItemEzVariableContext.Value = value; } } #endregion private readonly ReadonlyProperty<int> _itemsCountProperty = new ReadonlyProperty<int>(); public ReadonlyProperty<int> ItemsCountProperty { get { return _itemsCountProperty; } } public override int ItemsCount { get { return ItemsCountProperty.GetValue(); } protected set { ItemsCountProperty.InternalSetValue(value); } } private readonly ReadonlyProperty<bool> _hasItemsProperty = new ReadonlyProperty<bool>(); public ReadonlyProperty<bool> HasItemsProperty { get { return _hasItemsProperty; } } public bool HasItems { get { return HasItemsProperty.GetValue(); } set { HasItemsProperty.InternalSetValue(value); } } private readonly ReadonlyProperty<bool> _hasSelectionProperty = new ReadonlyProperty<bool>(); public ReadonlyProperty<bool> HasSelectionProperty { get { return _hasSelectionProperty; } } public bool HasSelection { get { return HasSelectionProperty.GetValue(); } set { HasSelectionProperty.InternalSetValue(value); } } private readonly ReadonlyProperty<bool> _firstItemSelectedProperty = new ReadonlyProperty<bool>(); public ReadonlyProperty<bool> FirstItemSelectedProperty { get { return _firstItemSelectedProperty; } } public override bool FirstItemSelected { get { return FirstItemSelectedProperty.GetValue(); } protected set { FirstItemSelectedProperty.InternalSetValue(value); } } private readonly ReadonlyProperty<bool> _lastItemSelectedProperty = new ReadonlyProperty<bool>(); public ReadonlyProperty<bool> LastItemSelectedProperty { get { return _lastItemSelectedProperty; } } public override bool LastItemSelected { get { return LastItemSelectedProperty.GetValue(); } protected set { LastItemSelectedProperty.InternalSetValue(value); } } protected override void AddBindingDependency(IBinding binding) { if (binding == null) return; if (_dependencies.Contains(binding)) return; _dependencies.Add(binding); } private void SetSelectedItem(int index, T item) { SelectedIndex = index; SelectedItem = item; HasSelection = (index >= 0); FirstItemSelected = (index == 0) && (ItemsCount > 0); LastItemSelected = (index == ItemsCount - 1) && (ItemsCount > 0); var temp = new List<IBinding>(_dependencies); _dependencies.Clear(); foreach (var binding in temp) { try { binding.OnContextChange(); } catch(UnityEngine.MissingReferenceException) { } } InvokeOnSelectionChange(); } private void UpdateAuxProperties() { ItemsCount = _items.Count; HasItems = _items.Count > 0; HasSelection = (SelectedIndex >= 0); FirstItemSelected = (SelectedIndex == 0) && (ItemsCount > 0); LastItemSelected = (SelectedIndex == ItemsCount - 1) && (ItemsCount > 0); UpdatePlaceholders(); } private void UpdatePlaceholders() { foreach (var p in _indexedPlaceholders) { p.Value.Value = (p.Key >= _items.Count) ? null : _items[p.Key]; } } public override VariableContext GetItemPlaceholder(int collectionItemIndex) { VariableContext<Context> placeholder; if (_indexedPlaceholders.TryGetValue(collectionItemIndex, out placeholder)) return placeholder; placeholder = new VariableContext<Context>((collectionItemIndex >= _items.Count) ? null : _items[collectionItemIndex]); _indexedPlaceholders.Add(collectionItemIndex, placeholder); return placeholder; } private readonly Dictionary<int, VariableContext<Context>> _indexedPlaceholders = new Dictionary<int, VariableContext<Context>>(); private readonly List<T> _items = new List<T>(); private readonly List<IBinding> _dependencies = new List<IBinding>(); } }
namespace NerdCats.JsonSchemaDefaults.Tests { using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Schema; using System; [TestClass] public class UnitTests { [TestMethod] public void Test_Reading_Defaults_From_Schema_Gets_Default_Json() { var schemaDefaultGenerator = new SchemaDefaultGenerator(); var defaultJSON = schemaDefaultGenerator.GetDefaults(JObject.Parse("{" + "\"title\": \"Album Options\", " + "\"type\": \"object\"," + "\"properties\": {" + " \"sort\": {" + " \"type\": \"string\"," + " \"default\": \"id\"" + " }," + " \"per_page\": {" + " \"default\": 30," + " \"type\": \"integer\"" + " }" + "}}")); var expectedResult = JObject.Parse("{ sort: 'id', per_page: 30 }"); Assert.IsTrue(JToken.DeepEquals(defaultJSON, expectedResult)); } [TestMethod] public void Test_Reading_Defaults_From_String_Schema_Gets_Default_Json() { var schemaDefaultGenerator = new SchemaDefaultGenerator(); var defaultJSON = schemaDefaultGenerator.GetDefaults("{" + "\"title\": \"Album Options\", " + "\"type\": \"object\"," + "\"properties\": {" + " \"sort\": {" + " \"type\": \"string\"," + " \"default\": \"id\"" + " }," + " \"per_page\": {" + " \"default\": 30," + " \"type\": \"integer\"" + " }" + "}}"); var expectedResult = JObject.Parse("{ sort: 'id', per_page: 30 }"); Assert.IsTrue(JToken.DeepEquals(defaultJSON, expectedResult)); } [TestMethod] public void Test_Reading_Defaults_From_Int_Array_Schema_With_String_Defaults_Throws_Exception() { Assert.ThrowsException<JSchemaValidationException>(() => { var schemaDefaultGenerator = new SchemaDefaultGenerator(); var defaultJSON = schemaDefaultGenerator.GetDefaults("{" + "type: 'array'," + "items : {" + " type : 'number'" + "}," + "default: ['getchute', 'chute']" + "}"); }); } [TestMethod] public void Test_Reading_Defaults_From_String_Array_Schema_Gets_Default_Data() { var schemaDefaultGenerator = new SchemaDefaultGenerator(); var defaultJSON = schemaDefaultGenerator.GetDefaults("{" + "type: 'array'," + "items : {" + " type : 'string'" + "}," + "default: ['getchute', 'chute']" + "}"); var expectedResult = JArray.Parse("['getchute', 'chute']"); Assert.IsTrue(JToken.DeepEquals(defaultJSON, expectedResult)); } [TestMethod] public void Test_Reading_Defaults_From_String_Schema_With_Enum_And_Wrong_Defaults_Throws() { Assert.ThrowsException<JSchemaValidationException>(() => { var schemaDefaultGenerator = new SchemaDefaultGenerator(); var defaultJSON = schemaDefaultGenerator.GetDefaults("{" + "\"title\": \"Album Options\", " + "\"type\": \"object\"," + "\"properties\": {" + " \"sort\": {" + " \"type\": \"string\"," + " enum: ['somethingElse']," + " \"default\": \"id\"" + " }," + " \"per_page\": {" + " \"default\": 30," + " \"type\": \"integer\"" + " }" + "}}"); }); } [TestMethod] public void Test_Reading_Defaults_From_String_Schema_With_Enum_Gets_Defaults() { var schemaDefaultGenerator = new SchemaDefaultGenerator(); var defaultJSON = schemaDefaultGenerator.GetDefaults("{" + "\"title\": \"Album Options\", " + "\"type\": \"object\"," + "\"properties\": {" + " \"sort\": {" + " \"type\": \"string\"," + " enum: ['id']," + " \"default\": \"id\"" + " }," + " \"per_page\": {" + " \"default\": 30," + " \"type\": \"integer\"" + " }" + "}}"); var expectedResult = JObject.Parse("{ sort: 'id', per_page: 30 }"); Assert.IsTrue(JToken.DeepEquals(defaultJSON, expectedResult)); } [TestMethod] public void Test_Reading_Defaults_From_String_Schema_With_Local_Reference() { var schemaDefaultGenerator = new SchemaDefaultGenerator(); var schemaJson = "{" + "type: 'object'," + "properties: {" + "farewell_to_arms: { " + "allOf: [" + "{'$ref': '#/definitions/book'}," + "{'properties': {" + "price: {" + "default : 30" + "}" + "}" + "}]" + "}," + "for_whom_the_bell_tolls: {" + "allOf: [" + "{'$ref': '#/definitions/book'}, " + "{ properties: { " + " price: { " + "default: 100 " + "}" + "}" + "}" + "]" + "}" + "}," + "definitions: {" + "book: {" + "type: 'object'," + "properties: {" + "author: {" + "type: 'string'," + "default: 'Hemingway'" + "}," + "price: {" + "type: 'integer'," + "default: 10" + "}" + "}" + "}" + "}" + "}"; var defaultJson = schemaDefaultGenerator.GetDefaults(schemaJson); var expectedDefault = JObject.Parse("{ farewell_to_arms: { author: 'Hemingway', price: 30 }, for_whom_the_bell_tolls: { author: 'Hemingway', price: 100 } }"); Assert.IsTrue(JToken.DeepEquals(defaultJson, expectedDefault)); } [TestMethod] public void Test_Reading_Defaults_From_Schema_Using_Extension_Gets_Default_Json() { var schema = JSchema.Parse("{" + "\"title\": \"Album Options\", " + "\"type\": \"object\"," + "\"properties\": {" + " \"sort\": {" + " \"type\": \"string\"," + " \"default\": \"id\"" + " }," + " \"per_page\": {" + " \"default\": 30," + " \"type\": \"integer\"" + " }" + "}}"); var defaultJSON = schema.GetDefaultJSON(); var expectedResult = JObject.Parse("{ sort: 'id', per_page: 30 }"); Assert.IsTrue(JToken.DeepEquals(defaultJSON, expectedResult)); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Buildalyzer.Construction; using Buildalyzer.Environment; using Buildalyzer.Logger; using Buildalyzer.Logging; using Microsoft.Build.Construction; using Microsoft.Build.Logging; using Microsoft.Extensions.Logging; using MsBuildPipeLogger; using ILogger = Microsoft.Build.Framework.ILogger; namespace Buildalyzer { public class ProjectAnalyzer : IProjectAnalyzer { private readonly List<ILogger> _buildLoggers = new List<ILogger>(); // Project-specific global properties and environment variables private readonly ConcurrentDictionary<string, string> _globalProperties = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase); private readonly ConcurrentDictionary<string, string> _environmentVariables = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase); public AnalyzerManager Manager { get; } public IProjectFile ProjectFile { get; } public EnvironmentFactory EnvironmentFactory { get; } public string SolutionDirectory { get; } public ProjectInSolution ProjectInSolution { get; } /// <inheritdoc/> public Guid ProjectGuid { get; } /// <inheritdoc/> public IReadOnlyDictionary<string, string> GlobalProperties => GetEffectiveGlobalProperties(null); /// <inheritdoc/> public IReadOnlyDictionary<string, string> EnvironmentVariables => GetEffectiveEnvironmentVariables(null); public IEnumerable<ILogger> BuildLoggers => _buildLoggers; public ILogger<ProjectAnalyzer> Logger { get; set; } /// <inheritdoc/> public bool IgnoreFaultyImports { get; set; } = true; // The project file path should already be normalized internal ProjectAnalyzer(AnalyzerManager manager, string projectFilePath, ProjectInSolution projectInSolution) { Manager = manager; Logger = Manager.LoggerFactory?.CreateLogger<ProjectAnalyzer>(); ProjectFile = new ProjectFile(projectFilePath); EnvironmentFactory = new EnvironmentFactory(Manager, ProjectFile); ProjectInSolution = projectInSolution; SolutionDirectory = (string.IsNullOrEmpty(manager.SolutionFilePath) ? Path.GetDirectoryName(projectFilePath) : Path.GetDirectoryName(manager.SolutionFilePath)) + Path.DirectorySeparatorChar; // Get (or create) a project GUID ProjectGuid = projectInSolution == null ? GuidUtility.Create(GuidUtility.UrlNamespace, ProjectFile.Name) : Guid.Parse(projectInSolution.ProjectGuid); // Set the solution directory global property SetGlobalProperty(MsBuildProperties.SolutionDir, SolutionDirectory); } /// <inheritdoc/> public IAnalyzerResults Build(string[] targetFrameworks) => Build(targetFrameworks, new EnvironmentOptions()); /// <inheritdoc/> public IAnalyzerResults Build(string[] targetFrameworks, EnvironmentOptions environmentOptions) { if (environmentOptions == null) { throw new ArgumentNullException(nameof(environmentOptions)); } // If the set of target frameworks is empty, just build the default if (targetFrameworks == null || targetFrameworks.Length == 0) { targetFrameworks = new string[] { null }; } // Create a new build environment for each target AnalyzerResults results = new AnalyzerResults(); foreach (string targetFramework in targetFrameworks) { BuildEnvironment buildEnvironment = EnvironmentFactory.GetBuildEnvironment(targetFramework, environmentOptions); BuildTargets(buildEnvironment, targetFramework, buildEnvironment.TargetsToBuild, results); } return results; } /// <inheritdoc/> public IAnalyzerResults Build(string[] targetFrameworks, BuildEnvironment buildEnvironment) { if (buildEnvironment == null) { throw new ArgumentNullException(nameof(buildEnvironment)); } // If the set of target frameworks is empty, just build the default if (targetFrameworks == null || targetFrameworks.Length == 0) { targetFrameworks = new string[] { null }; } AnalyzerResults results = new AnalyzerResults(); foreach (string targetFramework in targetFrameworks) { BuildTargets(buildEnvironment, targetFramework, buildEnvironment.TargetsToBuild, results); } return results; } /// <inheritdoc/> public IAnalyzerResults Build(string targetFramework) => Build(targetFramework, EnvironmentFactory.GetBuildEnvironment(targetFramework)); /// <inheritdoc/> public IAnalyzerResults Build(string targetFramework, EnvironmentOptions environmentOptions) => Build( targetFramework, EnvironmentFactory.GetBuildEnvironment( targetFramework, environmentOptions ?? throw new ArgumentNullException(nameof(environmentOptions)))); /// <inheritdoc/> public IAnalyzerResults Build(string targetFramework, BuildEnvironment buildEnvironment) => BuildTargets( buildEnvironment ?? throw new ArgumentNullException(nameof(buildEnvironment)), targetFramework, buildEnvironment.TargetsToBuild, new AnalyzerResults()); /// <inheritdoc/> public IAnalyzerResults Build() => Build((string)null); /// <inheritdoc/> public IAnalyzerResults Build(EnvironmentOptions environmentOptions) => Build((string)null, environmentOptions); /// <inheritdoc/> public IAnalyzerResults Build(BuildEnvironment buildEnvironment) => Build((string)null, buildEnvironment); // This is where the magic happens - returns one result per result target framework private IAnalyzerResults BuildTargets(BuildEnvironment buildEnvironment, string targetFramework, string[] targetsToBuild, AnalyzerResults results) { using (CancellationTokenSource cancellation = new CancellationTokenSource()) { using (AnonymousPipeLoggerServer pipeLogger = new AnonymousPipeLoggerServer(cancellation.Token)) { using (EventProcessor eventProcessor = new EventProcessor(Manager, this, BuildLoggers, pipeLogger, results != null)) { // Run MSBuild int exitCode; string fileName = GetCommand(buildEnvironment, targetFramework, targetsToBuild, pipeLogger.GetClientHandle(), out string arguments); using (ProcessRunner processRunner = new ProcessRunner(fileName, arguments, Path.GetDirectoryName(ProjectFile.Path), GetEffectiveEnvironmentVariables(buildEnvironment), Manager.LoggerFactory)) { processRunner.Start(); pipeLogger.ReadAll(); processRunner.WaitForExit(); exitCode = processRunner.ExitCode; } // Collect the results results?.Add(eventProcessor.Results, exitCode == 0 && eventProcessor.OverallSuccess); } } } return results; } private string GetCommand(BuildEnvironment buildEnvironment, string targetFramework, string[] targetsToBuild, string pipeLoggerClientHandle, out string arguments) { // Get the executable and the initial set of arguments string fileName = buildEnvironment.MsBuildExePath; string initialArguments = string.Empty; bool isDotNet = false; // false=MSBuild.exe, true=dotnet.exe if (string.IsNullOrWhiteSpace(buildEnvironment.MsBuildExePath) || Path.GetExtension(buildEnvironment.MsBuildExePath).Equals(".dll", StringComparison.OrdinalIgnoreCase)) { // in case of no MSBuild path or a path to the MSBuild dll, run dotnet fileName = buildEnvironment.DotnetExePath; isDotNet = true; if (!string.IsNullOrWhiteSpace(buildEnvironment.MsBuildExePath)) { // pass path to MSBuild .dll to dotnet if provided initialArguments = $"\"{buildEnvironment.MsBuildExePath}\""; } } // Environment arguments string environmentArguments = buildEnvironment.Arguments.Any() ? string.Join(" ", buildEnvironment.Arguments) : string.Empty; // Get the logger arguments (/l) string loggerPath = typeof(BuildalyzerLogger).Assembly.Location; bool logEverything = _buildLoggers.Count > 0; string loggerArgStart = "/l"; // in case of MSBuild.exe use slash as parameter prefix for logger if (isDotNet) { // in case of dotnet.exe use dash as parameter prefix for logger loggerArgStart = "-l"; } string loggerArgument = loggerArgStart + $":{nameof(BuildalyzerLogger)},{FormatArgument(loggerPath)};{pipeLoggerClientHandle};{logEverything}"; // Get the properties arguments (/property) Dictionary<string, string> effectiveGlobalProperties = GetEffectiveGlobalProperties(buildEnvironment); if (!string.IsNullOrEmpty(targetFramework)) { // Setting the TargetFramework MSBuild property tells MSBuild which target framework to use for the outer build effectiveGlobalProperties[MsBuildProperties.TargetFramework] = targetFramework; } if (Path.GetExtension(ProjectFile.Path).Equals(".fsproj", StringComparison.OrdinalIgnoreCase) && effectiveGlobalProperties.ContainsKey(MsBuildProperties.SkipCompilerExecution)) { // We can't skip the compiler for design-time builds in F# (it causes strange errors regarding file copying) effectiveGlobalProperties.Remove(MsBuildProperties.SkipCompilerExecution); } string propertyArgStart = "/property"; // in case of MSBuild.exe use slash as parameter prefix for property if (isDotNet) { // in case of dotnet.exe use dash as parameter prefix for property propertyArgStart = "-p"; } string propertyArgument = effectiveGlobalProperties.Count == 0 ? string.Empty : propertyArgStart + $":{string.Join(";", effectiveGlobalProperties.Select(x => $"{x.Key}={FormatArgument(x.Value)}"))}"; // Get the target argument (/target) string targetArgument = targetsToBuild == null || targetsToBuild.Length == 0 ? string.Empty : $"/target:{string.Join(";", targetsToBuild)}"; // Get the restore argument (/restore) string restoreArgument = buildEnvironment.Restore ? "/restore" : string.Empty; arguments = string.Empty; if (!isDotNet || !string.IsNullOrEmpty(initialArguments)) { // these are the first arguments for MSBuild.exe or dotnet.exe with MSBuild.dll, they are not needed for pure dotnet.exe calls arguments = $"{initialArguments} /noconsolelogger "; } arguments += $"{environmentArguments} {restoreArgument} {targetArgument} {propertyArgument} {loggerArgument} {FormatArgument(ProjectFile.Path)}"; return fileName; } private static string FormatArgument(string argument) { // Escape inner quotes argument = argument.Replace("\"", "\\\""); // Also escape trailing slashes so they don't escape the closing quote if (argument.EndsWith("\\")) { argument = $"{argument}\\"; } // Surround with quotes return $"\"{argument}\""; } public void SetGlobalProperty(string key, string value) { _globalProperties[key] = value; } public void RemoveGlobalProperty(string key) { // Nulls are removed before passing to MSBuild and can be used to ignore values in lower-precedence collections _globalProperties[key] = null; } public void SetEnvironmentVariable(string key, string value) { _environmentVariables[key] = value; } // Note the order of precedence (from least to most) private Dictionary<string, string> GetEffectiveGlobalProperties(BuildEnvironment buildEnvironment) => GetEffectiveDictionary( true, // Remove nulls to avoid passing null global properties. But null can be used in higher-precident dictionaries to ignore a lower-precident dictionary's value. buildEnvironment?.GlobalProperties, Manager.GlobalProperties, _globalProperties); // Note the order of precedence (from least to most) private Dictionary<string, string> GetEffectiveEnvironmentVariables(BuildEnvironment buildEnvironment) => GetEffectiveDictionary( false, // Don't remove nulls as a null value will unset the env var which may be set by a calling process. buildEnvironment?.EnvironmentVariables, Manager.EnvironmentVariables, _environmentVariables); private static Dictionary<string, string> GetEffectiveDictionary( bool removeNulls, params IReadOnlyDictionary<string, string>[] innerDictionaries) { Dictionary<string, string> effectiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (IReadOnlyDictionary<string, string> innerDictionary in innerDictionaries.Where(x => x != null)) { foreach (KeyValuePair<string, string> pair in innerDictionary) { if (removeNulls && pair.Value == null) { effectiveDictionary.Remove(pair.Key); } else { effectiveDictionary[pair.Key] = pair.Value; } } } return effectiveDictionary; } public void AddBinaryLogger( string binaryLogFilePath = null, BinaryLogger.ProjectImportsCollectionMode collectProjectImports = BinaryLogger.ProjectImportsCollectionMode.Embed) => AddBuildLogger(new BinaryLogger { Parameters = binaryLogFilePath ?? Path.ChangeExtension(ProjectFile.Path, "binlog"), CollectProjectImports = collectProjectImports, Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic }); /// <inheritdoc/> public void AddBuildLogger(ILogger logger) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } _buildLoggers.Add(logger); } /// <inheritdoc/> public void RemoveBuildLogger(ILogger logger) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } _buildLoggers.Remove(logger); } } }
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; namespace MonoJavaBridge { partial class JNIEnv { private Delegates.AllocObject allocObject; private Delegates.CallBooleanMethod callBooleanMethod; private Delegates.CallByteMethod callByteMethod; private Delegates.CallCharMethod callCharMethod; private Delegates.CallDoubleMethod callDoubleMethod; private Delegates.CallFloatMethod callFloatMethod; private Delegates.CallIntMethod callIntMethod; private Delegates.CallLongMethod callLongMethod; private Delegates.CallNonvirtualBooleanMethod callNonvirtualBooleanMethod; private Delegates.CallNonvirtualByteMethod callNonvirtualByteMethod; private Delegates.CallNonvirtualCharMethod callNonvirtualCharMethod; private Delegates.CallNonvirtualDoubleMethod callNonvirtualDoubleMethod; private Delegates.CallNonvirtualFloatMethod callNonvirtualFloatMethod; private Delegates.CallNonvirtualIntMethod callNonvirtualIntMethod; private Delegates.CallNonvirtualLongMethod callNonvirtualLongMethod; private Delegates.CallNonvirtualObjectMethod callNonvirtualObjectMethod; private Delegates.CallNonvirtualShortMethod callNonvirtualShortMethod; private Delegates.CallNonvirtualVoidMethod callNonvirtualVoidMethod; private Delegates.CallObjectMethod callObjectMethod; private Delegates.CallShortMethod callShortMethod; private Delegates.CallStaticBooleanMethod callStaticBooleanMethod; private Delegates.CallStaticByteMethod callStaticByteMethod; private Delegates.CallStaticCharMethod callStaticCharMethod; private Delegates.CallStaticDoubleMethod callStaticDoubleMethod; private Delegates.CallStaticFloatMethod callStaticFloatMethod; private Delegates.CallStaticIntMethod callStaticIntMethod; private Delegates.CallStaticLongMethod callStaticLongMethod; private Delegates.CallStaticObjectMethod callStaticObjectMethod; private Delegates.CallStaticShortMethod callStaticShortMethod; private Delegates.CallStaticVoidMethod callStaticVoidMethod; private Delegates.CallVoidMethod callVoidMethod; private Delegates.DefineClass defineClass; private Delegates.DeleteGlobalRef deleteGlobalRef; private Delegates.DeleteLocalRef deleteLocalRef; private Delegates.DeleteWeakGlobalRef deleteWeakGlobalRef; private Delegates.EnsureLocalCapacity ensureLocalCapacity; private Delegates.ExceptionCheck exceptionCheck; private Delegates.ExceptionClear exceptionClear; private Delegates.ExceptionDescribe exceptionDescribe; private Delegates.ExceptionOccurred exceptionOccurred; private Delegates.FatalError fatalError; private Delegates.FindClass findClass; private Delegates.FromReflectedField fromReflectedField; private Delegates.FromReflectedMethod fromReflectedMethod; private Delegates.GetArrayLength getArrayLength; private Delegates.GetBooleanArrayElements getBooleanArrayElements; private Delegates.GetBooleanArrayRegion getBooleanArrayRegion; private Delegates.GetBooleanField getBooleanField; private Delegates.GetByteArrayElements getByteArrayElements; private Delegates.GetByteArrayRegion getByteArrayRegion; private Delegates.GetByteField getByteField; private Delegates.GetCharArrayElements getCharArrayElements; private Delegates.GetCharArrayRegion getCharArrayRegion; private Delegates.GetCharField getCharField; private Delegates.GetDirectBufferAddress getDirectBufferAddress; private Delegates.GetDirectBufferCapacity getDirectBufferCapacity; private Delegates.GetDoubleArrayElements getDoubleArrayElements; private Delegates.GetDoubleArrayRegion getDoubleArrayRegion; private Delegates.GetDoubleField getDoubleField; private Delegates.GetFieldID getFieldID; private Delegates.GetFloatArrayElements getFloatArrayElements; private Delegates.GetFloatArrayRegion getFloatArrayRegion; private Delegates.GetFloatField getFloatField; private Delegates.GetIntArrayElements getIntArrayElements; private Delegates.GetIntArrayRegion getIntArrayRegion; private Delegates.GetIntField getIntField; private Delegates.GetJavaVM getJavaVM; private Delegates.GetLongArrayElements getLongArrayElements; private Delegates.GetLongArrayRegion getLongArrayRegion; private Delegates.GetLongField getLongField; private Delegates.GetMethodID getMethodID; private Delegates.GetObjectArrayElement getObjectArrayElement; private Delegates.GetObjectClass getObjectClass; private Delegates.GetObjectField getObjectField; private Delegates.GetPrimitiveArrayCritical getPrimitiveArrayCritical; private Delegates.GetShortArrayElements getShortArrayElements; private Delegates.GetShortArrayRegion getShortArrayRegion; private Delegates.GetShortField getShortField; private Delegates.GetStaticBooleanField getStaticBooleanField; private Delegates.GetStaticByteField getStaticByteField; private Delegates.GetStaticCharField getStaticCharField; private Delegates.GetStaticDoubleField getStaticDoubleField; private Delegates.GetStaticFieldID getStaticFieldID; private Delegates.GetStaticFloatField getStaticFloatField; private Delegates.GetStaticIntField getStaticIntField; private Delegates.GetStaticLongField getStaticLongField; private Delegates.GetStaticMethodID getStaticMethodID; private Delegates.GetStaticObjectField getStaticObjectField; private Delegates.GetStaticShortField getStaticShortField; private Delegates.GetStringChars getStringChars; private Delegates.GetStringCritical getStringCritical; private Delegates.GetStringLength getStringLength; private Delegates.GetStringRegion getStringRegion; private Delegates.GetStringUTFChars getStringUTFChars; private Delegates.GetStringUTFLength getStringUTFLength; private Delegates.GetStringUTFRegion getStringUTFRegion; private Delegates.GetVersion getVersion; private Delegates.IsSameObject isSameObject; private Delegates.MonitorEnter monitorEnter; private Delegates.MonitorExit monitorExit; private Delegates.NewBooleanArray newBooleanArray; private Delegates.NewByteArray newByteArray; private Delegates.NewCharArray newCharArray; private Delegates.NewDirectByteBuffer newDirectByteBuffer; private Delegates.NewDoubleArray newDoubleArray; private Delegates.NewFloatArray newFloatArray; private Delegates.NewGlobalRef newGlobalRef; private Delegates.NewIntArray newIntArray; private Delegates.NewLocalRef newLocalRef; private Delegates.NewLongArray newLongArray; private Delegates.NewObject newObject; private Delegates.NewObjectArray newObjectArray; private Delegates.NewShortArray newShortArray; private Delegates.NewString newString; private Delegates.NewStringUTF newStringUTF; private Delegates.NewWeakGlobalRef newWeakGlobalRef; private Delegates.PopLocalFrame popLocalFrame; private Delegates.PushLocalFrame pushLocalFrame; private Delegates.RegisterNatives registerNatives; private Delegates.UnregisterNatives unregisterNatives; private Delegates.ReleaseBooleanArrayElements releaseBooleanArrayElements; private Delegates.ReleaseByteArrayElements releaseByteArrayElements; private Delegates.ReleaseCharArrayElements releaseCharArrayElements; private Delegates.ReleaseDoubleArrayElements releaseDoubleArrayElements; private Delegates.ReleaseFloatArrayElements releaseFloatArrayElements; private Delegates.ReleaseIntArrayElements releaseIntArrayElements; private Delegates.ReleaseLongArrayElements releaseLongArrayElements; private Delegates.ReleasePrimitiveArrayCritical releasePrimitiveArrayCritical; private Delegates.ReleaseShortArrayElements releaseShortArrayElements; private Delegates.ReleaseStringChars releaseStringChars; private Delegates.ReleaseStringCritical releaseStringCritical; private Delegates.ReleaseStringUTFChars releaseStringUTFChars; private Delegates.SetBooleanArrayRegion setBooleanArrayRegion; private Delegates.SetBooleanField setBooleanField; private Delegates.SetByteArrayRegion setByteArrayRegion; private Delegates.SetByteField setByteField; private Delegates.SetCharArrayRegion setCharArrayRegion; private Delegates.SetCharField setCharField; private Delegates.SetDoubleArrayRegion setDoubleArrayRegion; private Delegates.SetDoubleField setDoubleField; private Delegates.SetFloatArrayRegion setFloatArrayRegion; private Delegates.SetFloatField setFloatField; private Delegates.SetIntArrayRegion setIntArrayRegion; private Delegates.SetIntField setIntField; private Delegates.SetLongArrayRegion setLongArrayRegion; private Delegates.SetLongField setLongField; private Delegates.SetObjectArrayElement setObjectArrayElement; private Delegates.SetObjectField setObjectField; private Delegates.SetShortArrayRegion setShortArrayRegion; private Delegates.SetShortField setShortField; private Delegates.SetStaticBooleanField setStaticBooleanField; private Delegates.SetStaticByteField setStaticByteField; private Delegates.SetStaticCharField setStaticCharField; private Delegates.SetStaticDoubleField setStaticDoubleField; private Delegates.SetStaticFloatField setStaticFloatField; private Delegates.SetStaticIntField setStaticIntField; private Delegates.SetStaticLongField setStaticLongField; private Delegates.SetStaticObjectField setStaticObjectField; private Delegates.SetStaticShortField setStaticShortField; private Delegates.Throw @throw; private Delegates.ThrowNew throwNew; private Delegates.ToReflectedField toReflectedField; private Delegates.ToReflectedMethod toReflectedMethod; internal unsafe void InitMethods() { Helper.GetDelegateForFunctionPointer(functions.CallBooleanMethod, ref callBooleanMethod); Helper.GetDelegateForFunctionPointer(functions.CallByteMethod, ref callByteMethod); Helper.GetDelegateForFunctionPointer(functions.CallCharMethod, ref callCharMethod); Helper.GetDelegateForFunctionPointer(functions.CallDoubleMethod, ref callDoubleMethod); Helper.GetDelegateForFunctionPointer(functions.CallFloatMethod, ref callFloatMethod); Helper.GetDelegateForFunctionPointer(functions.CallIntMethod, ref callIntMethod); Helper.GetDelegateForFunctionPointer(functions.CallLongMethod, ref callLongMethod); Helper.GetDelegateForFunctionPointer(functions.CallObjectMethod, ref callObjectMethod); Helper.GetDelegateForFunctionPointer(functions.CallShortMethod, ref callShortMethod); Helper.GetDelegateForFunctionPointer(functions.CallVoidMethod, ref callVoidMethod); Helper.GetDelegateForFunctionPointer(functions.CallStaticBooleanMethod, ref callStaticBooleanMethod); Helper.GetDelegateForFunctionPointer(functions.CallStaticByteMethod, ref callStaticByteMethod); Helper.GetDelegateForFunctionPointer(functions.CallStaticCharMethod, ref callStaticCharMethod); Helper.GetDelegateForFunctionPointer(functions.CallStaticDoubleMethod, ref callStaticDoubleMethod); Helper.GetDelegateForFunctionPointer(functions.CallStaticFloatMethod, ref callStaticFloatMethod); Helper.GetDelegateForFunctionPointer(functions.CallStaticIntMethod, ref callStaticIntMethod); Helper.GetDelegateForFunctionPointer(functions.CallStaticLongMethod, ref callStaticLongMethod); Helper.GetDelegateForFunctionPointer(functions.CallStaticObjectMethod, ref callStaticObjectMethod); Helper.GetDelegateForFunctionPointer(functions.CallStaticShortMethod, ref callStaticShortMethod); Helper.GetDelegateForFunctionPointer(functions.CallStaticVoidMethod, ref callStaticVoidMethod); Helper.GetDelegateForFunctionPointer(functions.GetStaticObjectField, ref getStaticObjectField); Helper.GetDelegateForFunctionPointer(functions.GetStaticBooleanField, ref getStaticBooleanField); Helper.GetDelegateForFunctionPointer(functions.GetStaticByteField, ref getStaticByteField); Helper.GetDelegateForFunctionPointer(functions.GetStaticCharField, ref getStaticCharField); Helper.GetDelegateForFunctionPointer(functions.GetStaticShortField, ref getStaticShortField); Helper.GetDelegateForFunctionPointer(functions.GetStaticIntField, ref getStaticIntField); Helper.GetDelegateForFunctionPointer(functions.GetStaticLongField, ref getStaticLongField); Helper.GetDelegateForFunctionPointer(functions.GetStaticFloatField, ref getStaticFloatField); Helper.GetDelegateForFunctionPointer(functions.GetStaticDoubleField, ref getStaticDoubleField); Helper.GetDelegateForFunctionPointer(functions.SetStaticObjectField, ref setStaticObjectField); Helper.GetDelegateForFunctionPointer(functions.SetStaticBooleanField, ref setStaticBooleanField); Helper.GetDelegateForFunctionPointer(functions.SetStaticByteField, ref setStaticByteField); Helper.GetDelegateForFunctionPointer(functions.SetStaticCharField, ref setStaticCharField); Helper.GetDelegateForFunctionPointer(functions.SetStaticShortField, ref setStaticShortField); Helper.GetDelegateForFunctionPointer(functions.SetStaticIntField, ref setStaticIntField); Helper.GetDelegateForFunctionPointer(functions.SetStaticLongField, ref setStaticLongField); Helper.GetDelegateForFunctionPointer(functions.SetStaticFloatField, ref setStaticFloatField); Helper.GetDelegateForFunctionPointer(functions.SetStaticDoubleField, ref setStaticDoubleField); Helper.GetDelegateForFunctionPointer(functions.GetObjectField, ref getObjectField); Helper.GetDelegateForFunctionPointer(functions.GetBooleanField, ref getBooleanField); Helper.GetDelegateForFunctionPointer(functions.GetByteField, ref getByteField); Helper.GetDelegateForFunctionPointer(functions.GetCharField, ref getCharField); Helper.GetDelegateForFunctionPointer(functions.GetShortField, ref getShortField); Helper.GetDelegateForFunctionPointer(functions.GetIntField, ref getIntField); Helper.GetDelegateForFunctionPointer(functions.GetLongField, ref getLongField); Helper.GetDelegateForFunctionPointer(functions.GetFloatField, ref getFloatField); Helper.GetDelegateForFunctionPointer(functions.GetDoubleField, ref getDoubleField); Helper.GetDelegateForFunctionPointer(functions.SetObjectField, ref setObjectField); Helper.GetDelegateForFunctionPointer(functions.SetBooleanField, ref setBooleanField); Helper.GetDelegateForFunctionPointer(functions.SetByteField, ref setByteField); Helper.GetDelegateForFunctionPointer(functions.SetCharField, ref setCharField); Helper.GetDelegateForFunctionPointer(functions.SetShortField, ref setShortField); Helper.GetDelegateForFunctionPointer(functions.SetIntField, ref setIntField); Helper.GetDelegateForFunctionPointer(functions.SetLongField, ref setLongField); Helper.GetDelegateForFunctionPointer(functions.SetFloatField, ref setFloatField); Helper.GetDelegateForFunctionPointer(functions.SetDoubleField, ref setDoubleField); Helper.GetDelegateForFunctionPointer(functions.DeleteGlobalRef, ref deleteGlobalRef); Helper.GetDelegateForFunctionPointer(functions.DeleteLocalRef, ref deleteLocalRef); Helper.GetDelegateForFunctionPointer(functions.EnsureLocalCapacity, ref ensureLocalCapacity); Helper.GetDelegateForFunctionPointer(functions.ExceptionCheck, ref exceptionCheck); Helper.GetDelegateForFunctionPointer(functions.FindClass, ref findClass); Helper.GetDelegateForFunctionPointer(functions.GetDirectBufferAddress, ref getDirectBufferAddress); Helper.GetDelegateForFunctionPointer(functions.GetDirectBufferCapacity, ref getDirectBufferCapacity); Helper.GetDelegateForFunctionPointer(functions.GetFieldID, ref getFieldID); Helper.GetDelegateForFunctionPointer(functions.GetJavaVM, ref getJavaVM); Helper.GetDelegateForFunctionPointer(functions.GetMethodID, ref getMethodID); Helper.GetDelegateForFunctionPointer(functions.GetObjectClass, ref getObjectClass); Helper.GetDelegateForFunctionPointer(functions.GetStaticFieldID, ref getStaticFieldID); Helper.GetDelegateForFunctionPointer(functions.GetStaticMethodID, ref getStaticMethodID); Helper.GetDelegateForFunctionPointer(functions.GetStringChars, ref getStringChars); Helper.GetDelegateForFunctionPointer(functions.GetVersion, ref getVersion); Helper.GetDelegateForFunctionPointer(functions.IsSameObject, ref isSameObject); Helper.GetDelegateForFunctionPointer(functions.NewDirectByteBuffer, ref newDirectByteBuffer); Helper.GetDelegateForFunctionPointer(functions.NewGlobalRef, ref newGlobalRef); Helper.GetDelegateForFunctionPointer(functions.NewLocalRef, ref newLocalRef); Helper.GetDelegateForFunctionPointer(functions.NewString, ref newString); Helper.GetDelegateForFunctionPointer(functions.PopLocalFrame, ref popLocalFrame); Helper.GetDelegateForFunctionPointer(functions.PushLocalFrame, ref pushLocalFrame); Helper.GetDelegateForFunctionPointer(functions.RegisterNatives, ref registerNatives); Helper.GetDelegateForFunctionPointer(functions.UnregisterNatives, ref unregisterNatives); Helper.GetDelegateForFunctionPointer(functions.ReleaseStringChars, ref releaseStringChars); Helper.GetDelegateForFunctionPointer(functions.ToReflectedField, ref toReflectedField); Helper.GetDelegateForFunctionPointer(functions.ToReflectedMethod, ref toReflectedMethod); Helper.GetDelegateForFunctionPointer(functions.FromReflectedMethod, ref fromReflectedMethod); Helper.GetDelegateForFunctionPointer(functions.FromReflectedField, ref fromReflectedField); Helper.GetDelegateForFunctionPointer(functions.GetArrayLength, ref getArrayLength); Helper.GetDelegateForFunctionPointer(functions.GetObjectArrayElement, ref getObjectArrayElement); Helper.GetDelegateForFunctionPointer(functions.NewBooleanArray, ref newBooleanArray); Helper.GetDelegateForFunctionPointer(functions.NewByteArray, ref newByteArray); Helper.GetDelegateForFunctionPointer(functions.NewCharArray, ref newCharArray); Helper.GetDelegateForFunctionPointer(functions.NewDoubleArray, ref newDoubleArray); Helper.GetDelegateForFunctionPointer(functions.NewFloatArray, ref newFloatArray); Helper.GetDelegateForFunctionPointer(functions.NewIntArray, ref newIntArray); Helper.GetDelegateForFunctionPointer(functions.NewLongArray, ref newLongArray); Helper.GetDelegateForFunctionPointer(functions.NewObjectArray, ref newObjectArray); Helper.GetDelegateForFunctionPointer(functions.NewShortArray, ref newShortArray); Helper.GetDelegateForFunctionPointer(functions.SetObjectArrayElement, ref setObjectArrayElement); Helper.GetDelegateForFunctionPointer(functions.AllocObject, ref allocObject); Helper.GetDelegateForFunctionPointer(functions.NewObject, ref newObject); Helper.GetDelegateForFunctionPointer(functions.Throw, ref @throw); Helper.GetDelegateForFunctionPointer(functions.ThrowNew, ref throwNew); Helper.GetDelegateForFunctionPointer(functions.ExceptionOccurred, ref exceptionOccurred); Helper.GetDelegateForFunctionPointer(functions.ExceptionDescribe, ref exceptionDescribe); Helper.GetDelegateForFunctionPointer(functions.ExceptionClear, ref exceptionClear); Helper.GetDelegateForFunctionPointer(functions.FatalError, ref fatalError); Helper.GetDelegateForFunctionPointer(functions.DefineClass, ref defineClass); Helper.GetDelegateForFunctionPointer(functions.MonitorEnter, ref monitorEnter); Helper.GetDelegateForFunctionPointer(functions.MonitorExit, ref monitorExit); Helper.GetDelegateForFunctionPointer(functions.GetStringRegion, ref getStringRegion); Helper.GetDelegateForFunctionPointer(functions.GetStringUTFRegion, ref getStringUTFRegion); Helper.GetDelegateForFunctionPointer(functions.GetPrimitiveArrayCritical, ref getPrimitiveArrayCritical); Helper.GetDelegateForFunctionPointer(functions.ReleasePrimitiveArrayCritical, ref releasePrimitiveArrayCritical); Helper.GetDelegateForFunctionPointer(functions.GetStringCritical, ref getStringCritical); Helper.GetDelegateForFunctionPointer(functions.ReleaseStringCritical, ref releaseStringCritical); Helper.GetDelegateForFunctionPointer(functions.NewWeakGlobalRef, ref newWeakGlobalRef); Helper.GetDelegateForFunctionPointer(functions.DeleteWeakGlobalRef, ref deleteWeakGlobalRef); Helper.GetDelegateForFunctionPointer(functions.CallNonvirtualObjectMethod, ref callNonvirtualObjectMethod); Helper.GetDelegateForFunctionPointer(functions.CallNonvirtualBooleanMethod, ref callNonvirtualBooleanMethod); Helper.GetDelegateForFunctionPointer(functions.CallNonvirtualByteMethod, ref callNonvirtualByteMethod); Helper.GetDelegateForFunctionPointer(functions.CallNonvirtualCharMethod, ref callNonvirtualCharMethod); Helper.GetDelegateForFunctionPointer(functions.CallNonvirtualShortMethod, ref callNonvirtualShortMethod); Helper.GetDelegateForFunctionPointer(functions.CallNonvirtualIntMethod, ref callNonvirtualIntMethod); Helper.GetDelegateForFunctionPointer(functions.CallNonvirtualLongMethod, ref callNonvirtualLongMethod); Helper.GetDelegateForFunctionPointer(functions.CallNonvirtualFloatMethod, ref callNonvirtualFloatMethod); Helper.GetDelegateForFunctionPointer(functions.CallNonvirtualDoubleMethod, ref callNonvirtualDoubleMethod); Helper.GetDelegateForFunctionPointer(functions.CallNonvirtualVoidMethod, ref callNonvirtualVoidMethod); Helper.GetDelegateForFunctionPointer(functions.GetStringLength, ref getStringLength); Helper.GetDelegateForFunctionPointer(functions.NewStringUTF, ref newStringUTF); Helper.GetDelegateForFunctionPointer(functions.GetStringUTFLength, ref getStringUTFLength); Helper.GetDelegateForFunctionPointer(functions.GetStringUTFChars, ref getStringUTFChars); Helper.GetDelegateForFunctionPointer(functions.ReleaseStringUTFChars, ref releaseStringUTFChars); Helper.GetDelegateForFunctionPointer(functions.GetBooleanArrayElements, ref getBooleanArrayElements); Helper.GetDelegateForFunctionPointer(functions.GetByteArrayElements, ref getByteArrayElements); Helper.GetDelegateForFunctionPointer(functions.GetCharArrayElements, ref getCharArrayElements); Helper.GetDelegateForFunctionPointer(functions.GetShortArrayElements, ref getShortArrayElements); Helper.GetDelegateForFunctionPointer(functions.GetIntArrayElements, ref getIntArrayElements); Helper.GetDelegateForFunctionPointer(functions.GetLongArrayElements, ref getLongArrayElements); Helper.GetDelegateForFunctionPointer(functions.GetFloatArrayElements, ref getFloatArrayElements); Helper.GetDelegateForFunctionPointer(functions.GetDoubleArrayElements, ref getDoubleArrayElements); Helper.GetDelegateForFunctionPointer(functions.ReleaseBooleanArrayElements, ref releaseBooleanArrayElements); Helper.GetDelegateForFunctionPointer(functions.ReleaseByteArrayElements, ref releaseByteArrayElements); Helper.GetDelegateForFunctionPointer(functions.ReleaseCharArrayElements, ref releaseCharArrayElements); Helper.GetDelegateForFunctionPointer(functions.ReleaseShortArrayElements, ref releaseShortArrayElements); Helper.GetDelegateForFunctionPointer(functions.ReleaseIntArrayElements, ref releaseIntArrayElements); Helper.GetDelegateForFunctionPointer(functions.ReleaseLongArrayElements, ref releaseLongArrayElements); Helper.GetDelegateForFunctionPointer(functions.ReleaseFloatArrayElements, ref releaseFloatArrayElements); Helper.GetDelegateForFunctionPointer(functions.ReleaseDoubleArrayElements, ref releaseDoubleArrayElements); Helper.GetDelegateForFunctionPointer(functions.GetBooleanArrayRegion, ref getBooleanArrayRegion); Helper.GetDelegateForFunctionPointer(functions.GetByteArrayRegion, ref getByteArrayRegion); Helper.GetDelegateForFunctionPointer(functions.GetCharArrayRegion, ref getCharArrayRegion); Helper.GetDelegateForFunctionPointer(functions.GetShortArrayRegion, ref getShortArrayRegion); Helper.GetDelegateForFunctionPointer(functions.GetIntArrayRegion, ref getIntArrayRegion); Helper.GetDelegateForFunctionPointer(functions.GetLongArrayRegion, ref getLongArrayRegion); Helper.GetDelegateForFunctionPointer(functions.GetFloatArrayRegion, ref getFloatArrayRegion); Helper.GetDelegateForFunctionPointer(functions.GetDoubleArrayRegion, ref getDoubleArrayRegion); Helper.GetDelegateForFunctionPointer(functions.SetBooleanArrayRegion, ref setBooleanArrayRegion); Helper.GetDelegateForFunctionPointer(functions.SetByteArrayRegion, ref setByteArrayRegion); Helper.GetDelegateForFunctionPointer(functions.SetCharArrayRegion, ref setCharArrayRegion); Helper.GetDelegateForFunctionPointer(functions.SetShortArrayRegion, ref setShortArrayRegion); Helper.GetDelegateForFunctionPointer(functions.SetIntArrayRegion, ref setIntArrayRegion); Helper.GetDelegateForFunctionPointer(functions.SetLongArrayRegion, ref setLongArrayRegion); Helper.GetDelegateForFunctionPointer(functions.SetFloatArrayRegion, ref setFloatArrayRegion); Helper.GetDelegateForFunctionPointer(functions.SetDoubleArrayRegion, ref setDoubleArrayRegion); } #region Nested type: JNINativeInterface [StructLayout(LayoutKind.Sequential), NativeCppClass] public struct JNINativeInterface { public IntPtr reserved0; public IntPtr reserved1; public IntPtr reserved2; public IntPtr reserved3; public IntPtr GetVersion; public IntPtr DefineClass; public IntPtr FindClass; public IntPtr FromReflectedMethod; public IntPtr FromReflectedField; public IntPtr ToReflectedMethod; public IntPtr GetSuperclass; public IntPtr IsAssignableFrom; public IntPtr ToReflectedField; public IntPtr Throw; public IntPtr ThrowNew; public IntPtr ExceptionOccurred; public IntPtr ExceptionDescribe; public IntPtr ExceptionClear; public IntPtr FatalError; public IntPtr PushLocalFrame; public IntPtr PopLocalFrame; public IntPtr NewGlobalRef; public IntPtr DeleteGlobalRef; public IntPtr DeleteLocalRef; public IntPtr IsSameObject; public IntPtr NewLocalRef; public IntPtr EnsureLocalCapacity; public IntPtr AllocObject; public IntPtr __NewObject; public IntPtr __NewObjectV; public IntPtr NewObject; public IntPtr GetObjectClass; public IntPtr IsInstanceOf; public IntPtr GetMethodID; public IntPtr __CallObjectMethod; public IntPtr __CallObjectMethodV; public IntPtr CallObjectMethod; public IntPtr __CallBooleanMethod; public IntPtr __CallBooleanMethodV; public IntPtr CallBooleanMethod; public IntPtr __CallByteMethod; public IntPtr __CallByteMethodV; public IntPtr CallByteMethod; public IntPtr __CallCharMethod; public IntPtr __CallCharMethodV; public IntPtr CallCharMethod; public IntPtr __CallShortMethod; public IntPtr __CallShortMethodV; public IntPtr CallShortMethod; public IntPtr __CallIntMethod; public IntPtr __CallIntMethodV; public IntPtr CallIntMethod; public IntPtr __CallLongMethod; public IntPtr __CallLongMethodV; public IntPtr CallLongMethod; public IntPtr __CallFloatMethod; public IntPtr __CallFloatMethodV; public IntPtr CallFloatMethod; public IntPtr __CallDoubleMethod; public IntPtr __CallDoubleMethodV; public IntPtr CallDoubleMethod; public IntPtr __CallVoidMethod; public IntPtr __CallVoidMethodV; public IntPtr CallVoidMethod; public IntPtr __CallNonvirtualObjectMethod; public IntPtr __CallNonvirtualObjectMethodV; public IntPtr CallNonvirtualObjectMethod; public IntPtr __CallNonvirtualBooleanMethod; public IntPtr __CallNonvirtualBooleanMethodV; public IntPtr CallNonvirtualBooleanMethod; public IntPtr __CallNonvirtualByteMethod; public IntPtr __CallNonvirtualByteMethodV; public IntPtr CallNonvirtualByteMethod; public IntPtr __CallNonvirtualCharMethod; public IntPtr __CallNonvirtualCharMethodV; public IntPtr CallNonvirtualCharMethod; public IntPtr __CallNonvirtualShortMethod; public IntPtr __CallNonvirtualShortMethodV; public IntPtr CallNonvirtualShortMethod; public IntPtr __CallNonvirtualIntMethod; public IntPtr __CallNonvirtualIntMethodV; public IntPtr CallNonvirtualIntMethod; public IntPtr __CallNonvirtualLongMethod; public IntPtr __CallNonvirtualLongMethodV; public IntPtr CallNonvirtualLongMethod; public IntPtr __CallNonvirtualFloatMethod; public IntPtr __CallNonvirtualFloatMethodV; public IntPtr CallNonvirtualFloatMethod; public IntPtr __CallNonvirtualDoubleMethod; public IntPtr __CallNonvirtualDoubleMethodV; public IntPtr CallNonvirtualDoubleMethod; public IntPtr __CallNonvirtualVoidMethod; public IntPtr __CallNonvirtualVoidMethodV; public IntPtr CallNonvirtualVoidMethod; public IntPtr GetFieldID; public IntPtr GetObjectField; public IntPtr GetBooleanField; public IntPtr GetByteField; public IntPtr GetCharField; public IntPtr GetShortField; public IntPtr GetIntField; public IntPtr GetLongField; public IntPtr GetFloatField; public IntPtr GetDoubleField; public IntPtr SetObjectField; public IntPtr SetBooleanField; public IntPtr SetByteField; public IntPtr SetCharField; public IntPtr SetShortField; public IntPtr SetIntField; public IntPtr SetLongField; public IntPtr SetFloatField; public IntPtr SetDoubleField; public IntPtr GetStaticMethodID; public IntPtr __CallStaticObjectMethod; public IntPtr __CallStaticObjectMethodV; public IntPtr CallStaticObjectMethod; public IntPtr __CallStaticBooleanMethod; public IntPtr __CallStaticBooleanMethodV; public IntPtr CallStaticBooleanMethod; public IntPtr __CallStaticByteMethod; public IntPtr __CallStaticByteMethodV; public IntPtr CallStaticByteMethod; public IntPtr __CallStaticCharMethod; public IntPtr __CallStaticCharMethodV; public IntPtr CallStaticCharMethod; public IntPtr __CallStaticShortMethod; public IntPtr __CallStaticShortMethodV; public IntPtr CallStaticShortMethod; public IntPtr __CallStaticIntMethod; public IntPtr __CallStaticIntMethodV; public IntPtr CallStaticIntMethod; public IntPtr __CallStaticLongMethod; public IntPtr __CallStaticLongMethodV; public IntPtr CallStaticLongMethod; public IntPtr __CallStaticFloatMethod; public IntPtr __CallStaticFloatMethodV; public IntPtr CallStaticFloatMethod; public IntPtr __CallStaticDoubleMethod; public IntPtr __CallStaticDoubleMethodV; public IntPtr CallStaticDoubleMethod; public IntPtr __CallStaticVoidMethod; public IntPtr __CallStaticVoidMethodV; public IntPtr CallStaticVoidMethod; public IntPtr GetStaticFieldID; public IntPtr GetStaticObjectField; public IntPtr GetStaticBooleanField; public IntPtr GetStaticByteField; public IntPtr GetStaticCharField; public IntPtr GetStaticShortField; public IntPtr GetStaticIntField; public IntPtr GetStaticLongField; public IntPtr GetStaticFloatField; public IntPtr GetStaticDoubleField; public IntPtr SetStaticObjectField; public IntPtr SetStaticBooleanField; public IntPtr SetStaticByteField; public IntPtr SetStaticCharField; public IntPtr SetStaticShortField; public IntPtr SetStaticIntField; public IntPtr SetStaticLongField; public IntPtr SetStaticFloatField; public IntPtr SetStaticDoubleField; public IntPtr NewString; public IntPtr GetStringLength; public IntPtr GetStringChars; public IntPtr ReleaseStringChars; public IntPtr NewStringUTF; public IntPtr GetStringUTFLength; public IntPtr GetStringUTFChars; public IntPtr ReleaseStringUTFChars; public IntPtr GetArrayLength; public IntPtr NewObjectArray; public IntPtr GetObjectArrayElement; public IntPtr SetObjectArrayElement; public IntPtr NewBooleanArray; public IntPtr NewByteArray; public IntPtr NewCharArray; public IntPtr NewShortArray; public IntPtr NewIntArray; public IntPtr NewLongArray; public IntPtr NewFloatArray; public IntPtr NewDoubleArray; public IntPtr GetBooleanArrayElements; public IntPtr GetByteArrayElements; public IntPtr GetCharArrayElements; public IntPtr GetShortArrayElements; public IntPtr GetIntArrayElements; public IntPtr GetLongArrayElements; public IntPtr GetFloatArrayElements; public IntPtr GetDoubleArrayElements; public IntPtr ReleaseBooleanArrayElements; public IntPtr ReleaseByteArrayElements; public IntPtr ReleaseCharArrayElements; public IntPtr ReleaseShortArrayElements; public IntPtr ReleaseIntArrayElements; public IntPtr ReleaseLongArrayElements; public IntPtr ReleaseFloatArrayElements; public IntPtr ReleaseDoubleArrayElements; public IntPtr GetBooleanArrayRegion; public IntPtr GetByteArrayRegion; public IntPtr GetCharArrayRegion; public IntPtr GetShortArrayRegion; public IntPtr GetIntArrayRegion; public IntPtr GetLongArrayRegion; public IntPtr GetFloatArrayRegion; public IntPtr GetDoubleArrayRegion; public IntPtr SetBooleanArrayRegion; public IntPtr SetByteArrayRegion; public IntPtr SetCharArrayRegion; public IntPtr SetShortArrayRegion; public IntPtr SetIntArrayRegion; public IntPtr SetLongArrayRegion; public IntPtr SetFloatArrayRegion; public IntPtr SetDoubleArrayRegion; public IntPtr RegisterNatives; public IntPtr UnregisterNatives; public IntPtr MonitorEnter; public IntPtr MonitorExit; public IntPtr GetJavaVM; public IntPtr GetStringRegion; public IntPtr GetStringUTFRegion; public IntPtr GetPrimitiveArrayCritical; public IntPtr ReleasePrimitiveArrayCritical; public IntPtr GetStringCritical; public IntPtr ReleaseStringCritical; public IntPtr NewWeakGlobalRef; public IntPtr DeleteWeakGlobalRef; public IntPtr ExceptionCheck; public IntPtr NewDirectByteBuffer; public IntPtr GetDirectBufferAddress; public IntPtr GetDirectBufferCapacity; } #endregion } }
/* Copyright (c) 2004-2006 Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using System.Web; using System.Web.SessionState; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Collections; using System.Collections.Generic; using System.Web.Configuration; namespace PHP.Core { /// <summary> /// A session state. /// </summary> public enum SessionStates { /// <summary> /// Session is being started. Session handler's /// <see cref="SessionHandler.Load"/> method is called during this phase. /// </summary> Starting, /// <summary> /// Session has been started. /// </summary> Started, /// <summary> /// Session is being closed. Session handler's /// <see cref="SessionHandler.Persist"/> method is called during this phase. /// </summary> Closing, /// <summary> /// Session has been closed. /// </summary> Closed } /// <summary> /// Exception thrown by a Phalanger session manager. /// </summary> public sealed class SessionException : Exception { internal SessionException(string message) : base(message) { } } #region SessionHandler /// <summary> /// Base abstract class for custom session handlers. /// </summary> public abstract class SessionHandler : MarshalByRefObject { /// <summary> /// Gets a name of the handler. /// </summary> public abstract string Name { get; } /// <summary> /// Loads variables stored in the session. /// </summary> /// <returns>The array containing session variables. Can return a <B>null</B> reference.</returns> /// <param name="context">A current script context. Can't be a <B>null</B> reference.</param> /// <param name="httpContext">A current HTTP context. Can't be a <B>null</B> reference.</param> internal protected abstract PhpArray Load(ScriptContext context, HttpContext httpContext); /// <summary> /// Persists session variables. /// </summary> /// <param name="variables">Session variables to be persisted.</param> /// <param name="context">A current script context. Can't be a <B>null</B> reference.</param> /// <param name="httpContext">A current HTTP context. Can't be a <B>null</B> reference.</param> internal protected abstract void Persist(PhpArray variables, ScriptContext context, HttpContext httpContext); /// <summary> /// Called immediately before the session is abandoned. /// </summary> /// <param name="context">A current script context. Can't be a <B>null</B> reference.</param> /// <param name="httpContext">A current HTTP context. Can't be a <B>null</B> reference.</param> internal protected abstract void Abandoning(ScriptContext context, HttpContext httpContext); /// <summary> /// Returns <c>true</c> iff this session handled is able to persist data after session id change. /// </summary> /// <remarks>E.g. ASP.NET session handler does not.</remarks> public virtual bool AllowsSessionIdChange { get { return true; } } /// <summary> /// Keeps the object living forever. /// </summary> [System.Security.SecurityCritical] public override object InitializeLifetimeService() { return null; } /// <summary> /// Gets current session name. /// </summary> /// <param name="request">Valid request context.</param> /// <returns>Session name.</returns> public virtual string GetSessionName(RequestContext/*!*/request) { return AspNetSessionHandler.AspNetSessionName; } /// <summary> /// Sets new session name. /// </summary> /// <param name="request">Valid request context.</param> /// <param name="name">New session name.</param> /// <returns>Whether session name was changed successfully.</returns> public virtual bool SetSessionName(RequestContext/*!*/request, string name) { PhpException.FunctionNotSupported(PhpError.Notice); return false; } } #endregion #region AspNetSessionHandler /// <summary> /// Session handler based of ASP.NET sessions. /// </summary> public sealed class AspNetSessionHandler : SessionHandler { private AspNetSessionHandler() { } #region AspNetSessionName public static string AspNetSessionName { get { return _aspNetSessionNmame ?? (_aspNetSessionNmame = GetSessionIdCookieName()); } } private static string _aspNetSessionNmame = null; private static string GetSessionIdCookieName() { var section = WebConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection; return (section != null) ? section.CookieName : "ASP.NET_SessionId"; } #endregion public const string PhpNetSessionVars = "Phalanger.SessionVars"; internal const string DummySessionItem = "Phalanger_DummySessionKeepAliveItem(\uffff)"; /// <summary> /// Singleton instance. /// </summary> public static readonly AspNetSessionHandler Default = new AspNetSessionHandler(); /// <summary> /// Gets a string representation. /// </summary> /// <returns>The name of the handler.</returns> public override string ToString() { return Name; } /// <summary> /// Gets a name of the handler used in the configuration. /// </summary> public override string Name { get { return "aspnet"; } } /// <summary> /// Loads variables from ASP.NET session to an array. /// </summary> internal protected override PhpArray Load(ScriptContext context, HttpContext httpContext) { HttpSessionState state = httpContext.Session; PhpArray result = null; if (state.Mode == SessionStateMode.InProc) { result = new PhpArray(); foreach (string name in state) { result[name] = state[name]; } context.AcquireArray(result); } else { byte[] data = state[PhpNetSessionVars] as byte[]; if (data != null) { MemoryStream stream = new MemoryStream(data); BinaryFormatter formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Persistence)); result = formatter.Deserialize(stream) as PhpArray; } } return (result != null) ? result : new PhpArray(); } /// <summary> /// Stores session variables to ASP.NET session. /// </summary> internal protected override void Persist(PhpArray variables, ScriptContext context, HttpContext httpContext) { HttpSessionState state = httpContext.Session; if (state.Mode == SessionStateMode.InProc) { context.ReleaseArray(variables); // removes all items (some could be changed or removed in PHP): // TODO: some session variables could be added in ASP.NET application state.Clear(); // populates session collection from variables: foreach (KeyValuePair<IntStringKey, object> entry in variables) { // skips resources: if (!(entry.Value is PhpResource)) state.Add(entry.Key.ToString(), entry.Value); } } else { // if the session is maintained out-of-process, serialize the entire $_SESSION autoglobal MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Persistence)); formatter.Serialize(stream, variables); // add the serialized $_SESSION to ASP.NET session: state[PhpNetSessionVars] = stream.ToArray(); } } /// <summary> /// Called immediately before the session is abandoned. /// </summary> internal protected override void Abandoning(ScriptContext context, HttpContext httpContext) { } /// <summary> /// ASP.NET session handler won't persist data if session id has been changed. New session will be created. /// </summary> public override bool AllowsSessionIdChange { get { return false; } } /// <summary> /// Gets session cookie associated with a specified HTTP context. /// </summary> /// <param name="context">The context.</param> /// <returns>The cookie.</returns> public static HttpCookie GetCookie(HttpContext/*!*/ context) { if (context == null) throw new ArgumentNullException("context"); // no cookies available: if (context.Session == null || context.Session.IsCookieless) return null; // gets cookie from request: return context.Request.Cookies[AspNetSessionName]; } } #endregion #region SessionHandlers /// <summary> /// Maintains known session handler set. /// </summary> /// <threadsafety static="true"/> public sealed class SessionHandlers { /// <summary> /// Registered handlers. /// </summary> private static Dictionary<string, SessionHandler>/*!!*/handlers; /// <summary> /// Initializes static list of handlers to contain an ASP.NET handler. /// </summary> static SessionHandlers() { handlers = new Dictionary<string, SessionHandler>(3); RegisterHandler(AspNetSessionHandler.Default); } /// <summary> /// Registeres a new session handler. /// </summary> /// <param name="handler">The handler.</param> /// <returns>Whether handler has been successfuly registered. Two handlers with the same names can't be registered.</returns> /// <exception cref="ArgumentNullException"><paramref name="handler"/> is a <B>null</B> reference.</exception> public static bool RegisterHandler(SessionHandler handler) { if (handler == null) throw new ArgumentNullException("handler"); if (handler.Name == null) return false; lock (handlers) { if (handlers.ContainsKey(handler.Name)) return false; handlers.Add(handler.Name, handler); } return true; } /// <summary> /// Gets a session handler by specified name. /// </summary> /// <param name="name">The name of the handler.</param> /// <returns>The handler or <B>null</B> reference if such handler has not been registered.</returns> /// <exception cref="ArgumentNullException"><paramref name="name"/> is a <B>null</B> reference.</exception> public static SessionHandler GetHandler(string name) { if (name == null) throw new ArgumentNullException("name"); SessionHandler value; lock (handlers) handlers.TryGetValue(name, out value); return value; } } #endregion }
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Collections; using System.Security.Cryptography; using LumiSoft.Net.IMAP.Server; namespace LumiSoft.Net.IMAP.Client { /// <summary> /// IMAP client. /// </summary> /// <example> /// <code> /// using(IMAP_Client c = new IMAP_Client()){ /// c.Connect("ivx",143); /// c.Authenticate("test","test"); /// /// c.SelectFolder("Inbox"); /// /// // Get messages header here /// IMAP_FetchItem msgsInfo = c.FetchMessages(1,-1,false,true,true); /// /// // Do your suff /// } /// </code> /// </example> public class IMAP_Client : IDisposable { private BufferedSocket m_pSocket = null; private bool m_Connected = false; private bool m_Authenticated = false; private string m_SelectedFolder = ""; private int m_MsgCount = 0; private int m_NewMsgCount = 0; /// <summary> /// Default constructor. /// </summary> public IMAP_Client() { } #region method Dispose /// <summary> /// Clean up any resources being used. /// </summary> public void Dispose() { Disconnect(); } #endregion #region method Connect /// <summary> /// Connects to IMAP server. /// </summary> /// <param name="host">Host name.</param> /// <param name="port">Port number.</param> public void Connect(string host,int port) { if(!m_Connected){ // m_pSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); // IPEndPoint ipdest = new IPEndPoint(System.Net.Dns.Resolve(host).AddressList[0],port); // m_pSocket.Connect(ipdest); Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); IPEndPoint ipdest = new IPEndPoint(System.Net.Dns.Resolve(host).AddressList[0],port); s.Connect(ipdest); s.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.NoDelay,1); m_pSocket = new BufferedSocket(s); string reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ m_pSocket.Close(); m_pSocket = null; throw new Exception("Server returned:" + reply); } m_Connected = true; } } #endregion #region method Disconnect /// <summary> /// Disconnects from IMAP server. /// </summary> public void Disconnect() { if(m_pSocket != null && m_pSocket.Connected){ // Send QUIT m_pSocket.SendLine("a1 LOGOUT"); // m_pSocket.Close(); m_pSocket = null; } m_Connected = false; m_Authenticated = false; } #endregion #region method Authenticate /// <summary> /// Authenticates user. /// </summary> /// <param name="userName">User name.</param> /// <param name="password">Password.</param> public void Authenticate(string userName,string password) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(m_Authenticated){ throw new Exception("You are already authenticated !"); } m_pSocket.SendLine("a1 LOGIN \"" + userName + "\" \"" + password + "\""); string reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(reply.ToUpper().StartsWith("OK")){ m_Authenticated = true; } else{ throw new Exception("Server returned:" + reply); } } #endregion #region method CreateFolder /// <summary> /// Creates specified folder. /// </summary> /// <param name="folderName">Folder name. Eg. test, Inbox/SomeSubFolder. NOTE: use GetFolderSeparator() to get right folder separator.</param> public void CreateFolder(string folderName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("a1 CREATE \"" + EncodeUtf7(folderName) + "\""); string reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } } #endregion #region method DeleteFolder /// <summary> /// Deletes specified folder. /// </summary> /// <param name="folderName">Folder name.</param> public void DeleteFolder(string folderName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("a1 DELETE \"" + EncodeUtf7(folderName) + "\""); string reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } } #endregion #region method RenameFolder /// <summary> /// Renames specified folder. /// </summary> /// <param name="sourceFolderName">Source folder name.</param> /// <param name="destinationFolderName">Destination folder name.</param> public void RenameFolder(string sourceFolderName,string destinationFolderName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("a1 RENAME \"" + EncodeUtf7(sourceFolderName) + "\" \"" + EncodeUtf7(destinationFolderName) + "\""); string reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } } #endregion #region method GetFolders /// <summary> /// Gets all available folders. /// </summary> /// <returns></returns> public string[] GetFolders() { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } ArrayList list = new ArrayList(); m_pSocket.SendLine("a1 LIST \"\" \"*\""); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO string reply = m_pSocket.ReadLine(); if(reply.StartsWith("*")){ // Read multiline response while(reply.StartsWith("*")){ // don't show not selectable folders if(reply.ToLower().IndexOf("\\noselect") == -1){ reply = reply.Substring(reply.IndexOf(")") + 1).Trim(); // Remove * LIST(..) reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Folder separator // Folder name between "" if(reply.IndexOf("\"") > -1){ list.Add(DecodeUtf7(reply.Substring(reply.IndexOf("\"") + 1,reply.Length - reply.IndexOf("\"") - 2))); } else{ list.Add(DecodeUtf7(reply.Trim())); } } reply = m_pSocket.ReadLine(); } } reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } string[] retVal = new string[list.Count]; list.CopyTo(retVal); return retVal; } #endregion #region method GetSubscribedFolders /// <summary> /// Gets all subscribed folders. /// </summary> /// <returns></returns> public string[] GetSubscribedFolders() { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } ArrayList list = new ArrayList(); m_pSocket.SendLine("a1 LSUB \"\" \"*\""); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO string reply = m_pSocket.ReadLine(); if(reply.StartsWith("*")){ // Read multiline response while(reply.StartsWith("*")){ // string folder = reply.Substring(reply.LastIndexOf(" ")).Trim().Replace("\"",""); list.Add(DecodeUtf7(folder)); reply = m_pSocket.ReadLine(); } } reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } string[] retVal = new string[list.Count]; list.CopyTo(retVal); return retVal; } #endregion #region method SubscribeFolder /// <summary> /// Subscribes specified folder. /// </summary> /// <param name="folderName">Folder name.</param> public void SubscribeFolder(string folderName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("a1 SUBSCRIBE \"" + EncodeUtf7(folderName) + "\""); string reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } } #endregion #region method UnSubscribeFolder /// <summary> /// UnSubscribes specified folder. /// </summary> /// <param name="folderName">Folder name,</param> public void UnSubscribeFolder(string folderName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("a1 UNSUBSCRIBE \"" + EncodeUtf7(folderName) + "\""); string reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } } #endregion #region method SelectFolder /// <summary> /// Selects specified folder. /// </summary> /// <param name="folderName">Folder name.</param> public void SelectFolder(string folderName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("a1 SELECT \"" + EncodeUtf7(folderName) + "\""); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO string reply = m_pSocket.ReadLine(); if(reply.StartsWith("*")){ // Read multiline response while(reply.StartsWith("*")){ // Get rid of * reply = reply.Substring(1).Trim(); if(reply.ToUpper().IndexOf("EXISTS") > -1 && reply.ToUpper().IndexOf("FLAGS") == -1){ m_MsgCount = Convert.ToInt32(reply.Substring(0,reply.IndexOf(" ")).Trim()); } else if(reply.ToUpper().IndexOf("RECENT") > -1 && reply.ToUpper().IndexOf("FLAGS") == -1){ m_NewMsgCount = Convert.ToInt32(reply.Substring(0,reply.IndexOf(" ")).Trim()); } reply = m_pSocket.ReadLine(); } } reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } m_SelectedFolder = folderName; } #endregion /// <summary> /// TODO: /// </summary> /// <param name="folderName"></param> public void GetFolderACL(string folderName) { throw new Exception("TODO:"); } #region method SetFolderACL /// <summary> /// Sets specified user ACL permissions for specified folder. /// </summary> /// <param name="folderName">Folder name which ACL to set.</param> /// <param name="userName">User name who's ACL to set.</param> /// <param name="acl">ACL permissions to set.</param> public void SetFolderACL(string folderName,string userName,IMAP_ACL_Flags acl) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("a1 SETACL \"" + EncodeUtf7(folderName) + "\" \"" + userName + "\" " + IMAP_Utils.ACL_to_String(acl)); string reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } } #endregion #region method DeleteFolderACL /// <summary> /// Deletes specifieed user access to specified folder. /// </summary> /// <param name="folderName">Folder which ACL to remove.</param> /// <param name="userName">User name who's ACL to remove.</param> public void DeleteFolderACL(string folderName,string userName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("a1 DELETEACL \"" + EncodeUtf7(folderName) + "\" \"" + userName + "\""); string reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } } #endregion #region method GetFolderMyrights /// <summary> /// Gets myrights to specified folder. /// </summary> /// <param name="folderName"></param> /// <returns></returns> public IMAP_ACL_Flags GetFolderMyrights(string folderName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } IMAP_ACL_Flags aclFlags = IMAP_ACL_Flags.None; m_pSocket.SendLine("a1 MYRIGHTS \"" + EncodeUtf7(folderName) + "\""); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO string reply = m_pSocket.ReadLine(); if(reply.StartsWith("*")){ // Read multiline response while(reply.StartsWith("*")){ // Get rid of * reply = reply.Substring(1).Trim(); if(reply.ToUpper().IndexOf("MYRIGHTS") > -1){ aclFlags = IMAP_Utils.ACL_From_String(reply.Substring(0,reply.IndexOf(" ")).Trim()); } reply = m_pSocket.ReadLine(); } } reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } return aclFlags; } #endregion #region method CopyMessages /// <summary> /// Makes copy of messages to specified folder. /// </summary> /// <param name="startMsgNo">Start message number.</param> /// <param name="endMsgNo">End message number. -1 = last.</param> /// <param name="destFolder">Folder where to cpoy messages.</param> /// <param name="uidCopy">Specifies if startMsgNo and endMsgNo is message UIDs.</param> public void CopyMessages(int startMsgNo,int endMsgNo,string destFolder,bool uidCopy) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } if(m_SelectedFolder.Length == 0){ throw new Exception("You must select folder first !"); } string endMsg = endMsgNo.ToString(); if(endMsgNo < 1){ endMsg = "*"; } string uidC = ""; if(uidCopy){ uidC = "UID "; } m_pSocket.SendLine("a1 " + uidC + "COPY " + startMsgNo + ":" + endMsg + " \"" + EncodeUtf7(destFolder) + "\""); string reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } } #endregion #region method MoveMessages /// <summary> /// Moves messages to specified folder. /// </summary> /// <param name="startMsgNo">Start message number.</param> /// <param name="endMsgNo">End message number. -1 = last.</param> /// <param name="destFolder">Folder where to cpoy messages.</param> /// <param name="uidMove">Specifies if startMsgNo and endMsgNo is message UIDs.</param> public void MoveMessages(int startMsgNo,int endMsgNo,string destFolder,bool uidMove) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } if(m_SelectedFolder.Length == 0){ throw new Exception("You must select folder first !"); } CopyMessages(startMsgNo,endMsgNo,destFolder,uidMove); DeleteMessages(startMsgNo,endMsgNo,uidMove); } #endregion #region method DeleteMessages /// <summary> /// Deletes specified messages. /// </summary> /// <param name="startMsgNo">Start message number.</param> /// <param name="endMsgNo">End message number. -1 = last.</param> /// <param name="uidDelete">Specifies if startMsgNo and endMsgNo is message UIDs.</param> public void DeleteMessages(int startMsgNo,int endMsgNo,bool uidDelete) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } if(m_SelectedFolder.Length == 0){ throw new Exception("You must select folder first !"); } string endMsg = endMsgNo.ToString(); if(endMsgNo < 1){ endMsg = "*"; } string uidD = ""; if(uidDelete){ uidD = "UID "; } // 1) Set deleted flag // 2) Delete messages with EXPUNGE command m_pSocket.SendLine("a1 " + uidD + "STORE " + startMsgNo + ":" + endMsg + " +FLAGS.SILENT (\\Deleted)"); string reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } m_pSocket.SendLine("a1 EXPUNGE"); reply = m_pSocket.ReadLine(); // Read multiline response, just skip these lines while(reply.StartsWith("*")){ reply = m_pSocket.ReadLine(); } reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } } #endregion #region method StoreMessage /// <summary> /// Stores message to specified folder. /// </summary> /// <param name="folderName">Folder where to store message.</param> /// <param name="data">Message data which to store.</param> public void StoreMessage(string folderName,byte[] data) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("a1 APPEND \"" + EncodeUtf7(folderName) + "\" (\\Seen) {" + data.Length + "}"); // ToDo: server may return status response there. // must get reply with starting + string reply = m_pSocket.ReadLine(); if(reply.StartsWith("+")){ // Send message m_pSocket.Send(data); // Why must send this ??? m_pSocket.Send(new byte[]{(byte)'\r',(byte)'\n'}); // Read store result reply = m_pSocket.ReadLine(); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove command tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } } else{ throw new Exception("Server returned:" + reply); } } #endregion #region method FetchMessages /// <summary> /// Fetches messages headers or full messages data. /// </summary> /// <param name="startMsgNo">Start message number.</param> /// <param name="endMsgNo">End message number. -1 = last.</param> /// <param name="uidFetch">Specifies if startMsgNo and endMsgNo is message UIDs.</param> /// <param name="headersOnly">If true message headers are retrieved, otherwise full message retrieved.</param> /// <param name="setSeenFlag">If true message seen flag is setted.</param> /// <returns></returns> public IMAP_FetchItem[] FetchMessages(int startMsgNo,int endMsgNo,bool uidFetch,bool headersOnly,bool setSeenFlag) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } if(m_SelectedFolder.Length == 0){ throw new Exception("You must select folder first !"); } ArrayList fetchItems = new ArrayList(); string endMsg = endMsgNo.ToString(); if(endMsgNo < 1){ endMsg = "*"; } string headers = ""; if(headersOnly){ headers = "HEADER"; } string uidF = ""; if(uidFetch){ uidF = "UID "; } string seenFl = ""; if(!setSeenFlag){ seenFl = ".PEEK"; } m_pSocket.SendLine("a1 " + uidF + "FETCH " + startMsgNo + ":" + endMsg + " (UID RFC822.SIZE FLAGS BODY" + seenFl + "[" + headers + "])"); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO string reply = m_pSocket.ReadLine(); // if(reply.StartsWith("*")){ // Read multiline response while(reply.StartsWith("*")){ // Fetch may return status response there, skip them if(IsStatusResponse(reply)){ continue; } // Get rid of * 1 FETCH and parse params. Reply:* 1 FETCH (UID 12 BODY[] ...) reply = reply.Substring(reply.IndexOf("FETCH (") + 7); int uid = 0; int size = 0; byte[] data = null; bool isNewMsg = true; bool isAnswered = false; // Loop fetch result fields // for(int i=0;i<4;i++){ while(reply.Length > 0){ // UID field if(reply.ToUpper().StartsWith("UID")){ reply = reply.Substring(3).Trim(); // Remove UID word from reply if(reply.IndexOf(" ") > -1){ uid = Convert.ToInt32(reply.Substring(0,reply.IndexOf(" "))); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove UID value from reply } else{ // Last param, no ending ' ' uid = Convert.ToInt32(reply.Substring(0)); reply = ""; } } // RFC822.SIZE field else if(reply.ToUpper().StartsWith("RFC822.SIZE")){ reply = reply.Substring(11).Trim(); // Remove RFC822.SIZE word from reply if(reply.IndexOf(" ") > -1){ size = Convert.ToInt32(reply.Substring(0,reply.IndexOf(" "))); reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove RFC822.SIZE value from reply } else{ // Last param, no ending ' ' size = Convert.ToInt32(reply.Substring(0)); reply = ""; } } // BODY.PEEK field else if(reply.ToUpper().StartsWith("BODY")){ // Get data. Find {dataLen} int dataLen = Convert.ToInt32(reply.Substring(reply.IndexOf("{") + 1,reply.IndexOf("}") - reply.IndexOf("{") - 1)); MemoryStream storeStrm = new MemoryStream(dataLen); ReadReplyCode code = m_pSocket.ReadData(storeStrm,dataLen,true); if(code != ReadReplyCode.Ok){ throw new Exception("Read data:" + code.ToString()); } data = storeStrm.ToArray(); // Read last fetch line, can be ')' or some params')'. reply = m_pSocket.ReadLine().Trim(); if(!reply.EndsWith(")")){ throw new Exception("UnExpected fetch end ! value:" + reply); } else{ reply = reply.Substring(0,reply.Length - 1).Trim(); // Remove ')' from reply } } // FLAGS field else if(reply.ToUpper().StartsWith("FLAGS")){ if(reply.ToUpper().IndexOf("\\SEEN") > -1){ isNewMsg = false; } if(reply.ToUpper().IndexOf("\\ANSWERED") > -1){ isAnswered = true; } reply = reply.Substring(reply.IndexOf(")") + 1).Trim(); // Remove FLAGS value from reply } else{ throw new Exception("Not supported fetch reply"); } } fetchItems.Add(new IMAP_FetchItem(uid,size,data,headersOnly,isNewMsg,isAnswered)); reply = m_pSocket.ReadLine(); } // } reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ if(!reply.ToUpper().StartsWith("NO")){ throw new Exception("Server returned:" + reply); } } IMAP_FetchItem[] retVal = new IMAP_FetchItem[fetchItems.Count]; fetchItems.CopyTo(retVal); return retVal; } #endregion #region method StoreMessageFlags /// <summary> /// Stores message folgs to sepcified messages range. /// </summary> /// <param name="startMsgNo">Start message number.</param> /// <param name="endMsgNo">End message number.</param> /// <param name="uidStore">Sepcifies if message numbers are message UID numbers.</param> /// <param name="msgFlags">Message flags to store.</param> public void StoreMessageFlags(int startMsgNo,int endMsgNo,bool uidStore,IMAP_MessageFlags msgFlags) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } if(m_SelectedFolder.Length == 0){ throw new Exception("You must select folder first !"); } if(uidStore){ m_pSocket.SendLine("a1 UID STORE " + startMsgNo + ":" + endMsgNo + " FLAGS (" + IMAP_Utils.MessageFlagsToString(msgFlags) + ")"); } else{ m_pSocket.SendLine("a1 STORE " + startMsgNo + ":" + endMsgNo + " FLAGS (" + IMAP_Utils.MessageFlagsToString(msgFlags) + ")"); } // Must get lines with * and cmdTag + OK or cmdTag BAD/NO string reply = m_pSocket.ReadLine(); if(reply.StartsWith("*")){ // Read multiline response while(reply.StartsWith("*")){ // Get rid of * reply = reply.Substring(1).Trim(); reply = m_pSocket.ReadLine(); } } reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ throw new Exception("Server returned:" + reply); } } #endregion #region method GetMessagesTotalSize /// <summary> /// Gets messages total size in selected folder. /// </summary> /// <returns></returns> public int GetMessagesTotalSize() { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } if(m_SelectedFolder.Length == 0){ throw new Exception("You must select folder first !"); } int totalSize = 0; m_pSocket.SendLine("a1 FETCH 1:* (RFC822.SIZE)"); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO string reply = m_pSocket.ReadLine(); if(reply.StartsWith("*")){ // Read multiline response while(reply.StartsWith("*")){ // Get rid of * 1 FETCH and parse params. Reply:* 1 FETCH (UID 12 BODY[] ...) reply = reply.Substring(reply.IndexOf("FETCH (") + 7); // RFC822.SIZE field if(reply.ToUpper().StartsWith("RFC822.SIZE")){ reply = reply.Substring(11).Trim(); // Remove RFC822.SIZE word from reply totalSize += Convert.ToInt32(reply.Substring(0,reply.Length - 1).Trim()); // Remove ending ')' } reply = m_pSocket.ReadLine(); } } reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ if(!reply.ToUpper().StartsWith("NO")){ throw new Exception("Server returned:" + reply); } } return totalSize; } #endregion #region method GetUnseenMessagesCount /// <summary> /// Gets unseen messages count in selected folder. /// </summary> /// <returns></returns> public int GetUnseenMessagesCount() { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } if(m_SelectedFolder.Length == 0){ throw new Exception("You must select folder first !"); } int count = 0; m_pSocket.SendLine("a1 FETCH 1:* (FLAGS)"); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO string reply = m_pSocket.ReadLine(); if(reply.StartsWith("*")){ // Read multiline response while(reply.StartsWith("*")){ // Get rid of * 1 FETCH and parse params. Reply:* 1 FETCH (UID 12 BODY[] ...) reply = reply.Substring(reply.IndexOf("FETCH (") + 7); if(reply.ToUpper().IndexOf("\\SEEN") == -1){ count++; } reply = m_pSocket.ReadLine(); } } reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ if(!reply.ToUpper().StartsWith("NO")){ throw new Exception("Server returned:" + reply); } } return count; } #endregion #region method GetFolderSeparator /// <summary> /// Gets IMAP server folder separator char. /// </summary> /// <returns></returns> public string GetFolderSeparator() { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } string folderSeparator = ""; m_pSocket.SendLine("a1 LIST \"\" \"\""); // Must get lines with * and cmdTag + OK or cmdTag BAD/NO string reply = m_pSocket.ReadLine(); if(reply.StartsWith("*")){ // Read multiline response while(reply.StartsWith("*")){ reply = reply.Substring(reply.IndexOf(")") + 1).Trim(); // Remove * LIST(..) // get folder separator folderSeparator = reply.Substring(0,reply.IndexOf(" ")).Trim(); reply = m_pSocket.ReadLine(); } } reply = reply.Substring(reply.IndexOf(" ")).Trim(); // Remove Cmd tag if(!reply.ToUpper().StartsWith("OK")){ if(!reply.ToUpper().StartsWith("NO")){ throw new Exception("Server returned:" + reply); } } reply = reply.Substring(reply.IndexOf(")") + 1).Trim(); // Remove * LIST(..) return folderSeparator.Replace("\"",""); } #endregion #region method DecodeUtf7 private string DecodeUtf7(string str) { str = str.Replace("&","+"); return System.Text.Encoding.UTF7.GetString(System.Text.Encoding.ASCII.GetBytes(str)); } #endregion #region method EncodeUtf7 private string EncodeUtf7(string str) { return System.Text.Encoding.Default.GetString(System.Text.Encoding.UTF7.GetBytes(str)).Replace("+","&"); } #endregion #region method IsStatusResponse private bool IsStatusResponse(string line) { // * 1 EXISTS // * 1 RECENT if(line.ToLower().IndexOf("exists") > -1){ return true; } if(line.ToLower().IndexOf("recent") > -1 && line.ToLower().IndexOf("flags") == -1){ return true; } return false; } #endregion #region Properties Implementation /// <summary> /// Gets selected folder. /// </summary> public string SelectedFolder { get{ return m_SelectedFolder; } } /// <summary> /// Gets numbers of recent(not accessed messages) in selected folder. /// </summary> public int RecentMessagesCount { get{ return m_NewMsgCount; } } /// <summary> /// Gets numbers of messages in selected folder. /// </summary> public int MessagesCount { get{ return m_MsgCount; } } #endregion } }
/* Copyright 2014 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. */ using System; using System.Collections.Generic; using System.IO; namespace DriveProxy.Utils { internal class IniFile { private string _filePath = ""; public IniFile() { } public IniFile(string filePath) { try { Open(filePath); } catch (Exception exception) { Log.Error(exception); } } public string FilePath { get { return _filePath; } } public bool IsOpen { get { if (_filePath != "") { return true; } return false; } } public void Close() { try { _filePath = ""; } catch (Exception exception) { Log.Error(exception); } } public string GetValue(string section, string key) { try { if (String.IsNullOrEmpty(FilePath)) { throw new Exception("FilePath is blank."); } if (!System.IO.File.Exists(FilePath)) { throw new Exception("FilePath " + FilePath + " does not exist."); } if (String.IsNullOrEmpty(section)) { throw new Exception("Section is blank."); } if (String.IsNullOrEmpty(key)) { throw new Exception("Key is blank."); } string[] lines = System.IO.File.ReadAllLines(FilePath); bool foundSection = false; foreach (string line in lines) { if (!foundSection) { if (String.Equals(line, "[" + section + "]", StringComparison.CurrentCultureIgnoreCase)) { foundSection = true; } } else { string[] values = line.Split('='); if (values.Length != 2) { return ""; } if (String.Equals(values[0], key, StringComparison.CurrentCultureIgnoreCase)) { return values[1]; } } } return ""; } catch (Exception exception) { Log.Error(exception); return null; } } public void Open(string filePath) { try { if (String.IsNullOrEmpty(filePath)) { throw new Exception("FilePath is blank."); } this._filePath = filePath; } catch (Exception exception) { Log.Error(exception); } } public void SetValue(string section, string key, string value) { try { if (String.IsNullOrEmpty(FilePath)) { throw new Exception("FilePath is blank."); } if (String.IsNullOrEmpty(section)) { throw new Exception("Section is blank."); } if (String.IsNullOrEmpty(key)) { throw new Exception("Key is blank."); } if (value == null) { value = ""; } if (!System.IO.File.Exists(FilePath)) { System.IO.FileStream fileStream = null; try { fileStream = new System.IO.FileStream(FilePath, FileMode.CreateNew, FileAccess.Write, FileShare.Write); } catch (Exception exception) { throw exception; } finally { if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); fileStream = null; } } } string[] lines = System.IO.File.ReadAllLines(FilePath); var lineList = new List<string>(); bool foundSection = false; bool foundKey = false; foreach (string t in lines) { string line = t; if (!foundSection) { if (String.Equals(line, "[" + section + "]", StringComparison.CurrentCultureIgnoreCase)) { foundSection = true; } } else if (!foundKey) { string[] values = line.Split('='); if (values.Length != 2) { string newLine = key + "=" + value; lineList.Add(newLine); foundKey = true; } else if (String.Equals(values[0], key, StringComparison.CurrentCultureIgnoreCase)) { line = values[0] + "=" + value; foundKey = true; } } lineList.Add(line); } if (!foundSection) { lineList.Add("[" + section + "]"); lineList.Add(key + "=" + value); } else if (!foundKey) { lineList.Add(key + "=" + value); } System.IO.File.WriteAllLines(FilePath, lineList.ToArray()); } catch (Exception exception) { Log.Error(exception); } } } }
using System; using System.Xml; using System.Data; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; using MyMeta; namespace MyGeneration { /// <summary> /// Summary description for LanguageMappings. /// </summary> public class LanguageMappings : DockContent, IMyGenContent { private IMyGenerationMDI mdi; GridLayoutHelper gridLayoutHelper; private System.ComponentModel.IContainer components; private System.Windows.Forms.ComboBox cboxLanguage; private System.Windows.Forms.DataGrid XmlEditor; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.ToolBar toolBar1; private System.Windows.Forms.ToolBarButton toolBarButton_Save; private System.Windows.Forms.ToolBarButton toolBarButton_New; private System.Windows.Forms.ToolBarButton toolBarButton1; private System.Windows.Forms.ToolBarButton toolBarButton_Delete; private System.Windows.Forms.DataGridTextBoxColumn col_From; private System.Windows.Forms.DataGridTextBoxColumn col_To; private System.Windows.Forms.DataGridTableStyle MyXmlStyle; public LanguageMappings(IMyGenerationMDI mdi) { InitializeComponent(); this.mdi = mdi; this.ShowHint = DockState.DockRight; } protected override string GetPersistString() { return this.GetType().FullName; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LanguageMappings)); this.cboxLanguage = new System.Windows.Forms.ComboBox(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.XmlEditor = new System.Windows.Forms.DataGrid(); this.MyXmlStyle = new System.Windows.Forms.DataGridTableStyle(); this.col_From = new System.Windows.Forms.DataGridTextBoxColumn(); this.col_To = new System.Windows.Forms.DataGridTextBoxColumn(); this.toolBar1 = new System.Windows.Forms.ToolBar(); this.toolBarButton_Save = new System.Windows.Forms.ToolBarButton(); this.toolBarButton_New = new System.Windows.Forms.ToolBarButton(); this.toolBarButton1 = new System.Windows.Forms.ToolBarButton(); this.toolBarButton_Delete = new System.Windows.Forms.ToolBarButton(); ((System.ComponentModel.ISupportInitialize)(this.XmlEditor)).BeginInit(); this.SuspendLayout(); // // cboxLanguage // this.cboxLanguage.Dock = System.Windows.Forms.DockStyle.Top; this.cboxLanguage.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboxLanguage.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cboxLanguage.Location = new System.Drawing.Point(2, 2); this.cboxLanguage.Name = "cboxLanguage"; this.cboxLanguage.Size = new System.Drawing.Size(494, 21); this.cboxLanguage.TabIndex = 11; this.cboxLanguage.SelectionChangeCommitted += new System.EventHandler(this.cboxLanguage_SelectionChangeCommitted); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Magenta; this.imageList1.Images.SetKeyName(0, ""); this.imageList1.Images.SetKeyName(1, ""); this.imageList1.Images.SetKeyName(2, ""); // // XmlEditor // this.XmlEditor.AlternatingBackColor = System.Drawing.Color.Moccasin; this.XmlEditor.BackColor = System.Drawing.Color.LightGray; this.XmlEditor.BackgroundColor = System.Drawing.Color.LightGray; this.XmlEditor.CaptionVisible = false; this.XmlEditor.DataMember = ""; this.XmlEditor.Dock = System.Windows.Forms.DockStyle.Fill; this.XmlEditor.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold); this.XmlEditor.GridLineColor = System.Drawing.Color.BurlyWood; this.XmlEditor.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.XmlEditor.Location = new System.Drawing.Point(2, 49); this.XmlEditor.Name = "XmlEditor"; this.XmlEditor.Size = new System.Drawing.Size(494, 951); this.XmlEditor.TabIndex = 7; this.XmlEditor.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.MyXmlStyle}); // // MyXmlStyle // this.MyXmlStyle.AlternatingBackColor = System.Drawing.Color.LightGray; this.MyXmlStyle.BackColor = System.Drawing.Color.LightSteelBlue; this.MyXmlStyle.DataGrid = this.XmlEditor; this.MyXmlStyle.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] { this.col_From, this.col_To}); this.MyXmlStyle.GridLineColor = System.Drawing.Color.DarkGray; this.MyXmlStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.MyXmlStyle.MappingName = "Language"; // // col_From // this.col_From.Format = ""; this.col_From.FormatInfo = null; this.col_From.HeaderText = "From"; this.col_From.MappingName = "From"; this.col_From.NullText = ""; this.col_From.Width = 75; // // col_To // this.col_To.Format = ""; this.col_To.FormatInfo = null; this.col_To.HeaderText = "To"; this.col_To.MappingName = "To"; this.col_To.NullText = ""; this.col_To.Width = 75; // // toolBar1 // this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat; this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { this.toolBarButton_Save, this.toolBarButton_New, this.toolBarButton1, this.toolBarButton_Delete}); this.toolBar1.Divider = false; this.toolBar1.DropDownArrows = true; this.toolBar1.ImageList = this.imageList1; this.toolBar1.Location = new System.Drawing.Point(2, 23); this.toolBar1.Name = "toolBar1"; this.toolBar1.ShowToolTips = true; this.toolBar1.Size = new System.Drawing.Size(494, 26); this.toolBar1.TabIndex = 13; this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick); // // toolBarButton_Save // this.toolBarButton_Save.ImageIndex = 0; this.toolBarButton_Save.Name = "toolBarButton_Save"; this.toolBarButton_Save.Tag = "save"; this.toolBarButton_Save.ToolTipText = "Save Language Mappings"; // // toolBarButton_New // this.toolBarButton_New.ImageIndex = 2; this.toolBarButton_New.Name = "toolBarButton_New"; this.toolBarButton_New.Tag = "new"; this.toolBarButton_New.ToolTipText = "Create New Language Mapping"; // // toolBarButton1 // this.toolBarButton1.Name = "toolBarButton1"; this.toolBarButton1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator; // // toolBarButton_Delete // this.toolBarButton_Delete.ImageIndex = 1; this.toolBarButton_Delete.Name = "toolBarButton_Delete"; this.toolBarButton_Delete.Tag = "delete"; this.toolBarButton_Delete.ToolTipText = "Delete Language Mappings"; // // LanguageMappings // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(498, 1002); this.Controls.Add(this.XmlEditor); this.Controls.Add(this.toolBar1); this.Controls.Add(this.cboxLanguage); this.HideOnClose = true; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "LanguageMappings"; this.Padding = new System.Windows.Forms.Padding(2); this.TabText = "Language Mappings"; this.Text = "Language Mappings"; this.Load += new System.EventHandler(this.LanguageMappings_Load); ((System.ComponentModel.ISupportInitialize)(this.XmlEditor)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion /*public void DefaultSettingsChanged(DefaultSettings settings) { PromptForSave(false); this.dbDriver = settings.DbDriver; PopulateComboBox(settings); PopulateGrid(this.dbDriver); MarkAsDirty(false); }*/ public bool CanClose(bool allowPrevent) { return PromptForSave(allowPrevent); } private bool PromptForSave(bool allowPrevent) { bool canClose = true; if(this.isDirty) { DialogResult result; if(allowPrevent) { result = MessageBox.Show("The Language Mappings have been Modified, Do you wish to save them?", "Language Mappings", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); } else { result = MessageBox.Show("The Language Mappings have been Modified, Do you wish to save them?", "Language Mappings", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } switch(result) { case DialogResult.Yes: { DefaultSettings settings = DefaultSettings.Instance; xml.Save(settings.LanguageMappingFile); MarkAsDirty(false); } break; case DialogResult.Cancel: canClose = false; break; } } return canClose; } private void MarkAsDirty(bool isDirty) { this.isDirty = isDirty; this.toolBarButton_Save.Visible = isDirty; } public new void Show(DockPanel dockManager) { DefaultSettings settings = DefaultSettings.Instance; if (!System.IO.File.Exists(settings.LanguageMappingFile)) { MessageBox.Show(this, "Language Mapping File does not exist at: " + settings.LanguageMappingFile + "\r\nPlease fix this in DefaultSettings."); } else { base.Show(dockManager); } } private void LanguageMappings_Load(object sender, System.EventArgs e) { this.col_From.TextBox.BorderStyle = BorderStyle.None; this.col_To.TextBox.BorderStyle = BorderStyle.None; this.col_From.TextBox.Move += new System.EventHandler(this.ColorTextBox); this.col_To.TextBox.Move += new System.EventHandler(this.ColorTextBox); DefaultSettings settings = DefaultSettings.Instance; this.dbDriver = settings.DbDriver; this.xml.Load(settings.LanguageMappingFile); PopulateComboBox(settings); PopulateGrid(this.dbDriver); MarkAsDirty(false); gridLayoutHelper = new GridLayoutHelper(XmlEditor, MyXmlStyle, new decimal[] { 0.50M, 0.50M }, new int[] { 100, 100 }); } private void cboxLanguage_SelectionChangeCommitted(object sender, System.EventArgs e) { DefaultSettings settings = DefaultSettings.Instance; PopulateGrid(this.dbDriver); } private void PopulateComboBox(DefaultSettings settings) { this.cboxLanguage.Items.Clear(); // Populate the ComboBox dbRoot myMeta = new dbRoot(); myMeta.LanguageMappingFileName = settings.LanguageMappingFile; myMeta.Language = settings.Language; string[] languages = myMeta.GetLanguageMappings(settings.DbDriver); if(null != languages) { for(int i = 0; i < languages.Length; i++) { this.cboxLanguage.Items.Add(languages[i]); } this.cboxLanguage.SelectedItem = myMeta.Language; if(this.cboxLanguage.SelectedIndex == -1) { // The default doesn't exist, set it to the first in the list this.cboxLanguage.SelectedIndex = 0; } } } private void PopulateGrid(string dbDriver) { string language; if(this.cboxLanguage.SelectedItem != null) { XmlEditor.Enabled = true; language = this.cboxLanguage.SelectedItem as String; } else { XmlEditor.Enabled = false; language = ""; } this.Text = "Language Mappings for " + dbDriver; langNode = this.xml.SelectSingleNode(@"//Languages/Language[@From='" + dbDriver + "' and @To='" + language + "']"); DataSet ds = new DataSet(); DataTable dt = new DataTable("this"); dt.Columns.Add("this", Type.GetType("System.Object")); ds.Tables.Add(dt); dt.Rows.Add(new object[] { this }); dt = new DataTable("Language"); DataColumn from = dt.Columns.Add("From", Type.GetType("System.String")); from.AllowDBNull = false; DataColumn to = dt.Columns.Add("To", Type.GetType("System.String")); to.AllowDBNull = false; ds.Tables.Add(dt); UniqueConstraint pk = new UniqueConstraint(from, false); dt.Constraints.Add(pk); ds.EnforceConstraints = true; if(null != langNode) { foreach(XmlNode mappingpNode in langNode.ChildNodes) { XmlAttributeCollection attrs = mappingpNode.Attributes; string sFrom = attrs["From"].Value; string sTo = attrs["To"].Value; dt.Rows.Add( new object[] { sFrom, sTo } ); } dt.AcceptChanges(); } XmlEditor.DataSource = dt; dt.RowChanged += new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting += new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted += new DataRowChangeEventHandler(GridRowDeleted); } private static void GridRowChanged(object sender, DataRowChangeEventArgs e) { LanguageMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as LanguageMappings; This.MarkAsDirty(true); This.GridRowChangedEvent(sender, e); } private static void GridRowDeleting(object sender, DataRowChangeEventArgs e) { LanguageMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as LanguageMappings; This.MarkAsDirty(true); This.GridRowDeletingEvent(sender, e); } private static void GridRowDeleted(object sender, DataRowChangeEventArgs e) { LanguageMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as LanguageMappings; This.MarkAsDirty(true); This.GridRowDeletedEvent(sender, e); } private void GridRowChangedEvent(object sender, DataRowChangeEventArgs e) { try { string sFrom = e.Row["From"] as string; string sTo = e.Row["To"] as string; string xPath; XmlNode typeNode; switch(e.Row.RowState) { case DataRowState.Added: { typeNode = langNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Type", null); langNode.AppendChild(typeNode); XmlAttribute attr; attr = langNode.OwnerDocument.CreateAttribute("From"); attr.Value = sFrom; typeNode.Attributes.Append(attr); attr = langNode.OwnerDocument.CreateAttribute("To"); attr.Value = sTo; typeNode.Attributes.Append(attr); } break; case DataRowState.Modified: { xPath = @"./Type[@From='" + sFrom + "']"; typeNode = langNode.SelectSingleNode(xPath); typeNode.Attributes["To"].Value = sTo; } break; } } catch {} } private void GridRowDeletingEvent(object sender, DataRowChangeEventArgs e) { string xPath = @"./Type[@From='" + e.Row["From"] + "' and @To='" + e.Row["To"] + "']"; XmlNode node = langNode.SelectSingleNode(xPath); if(node != null) { node.ParentNode.RemoveChild(node); } } private void GridRowDeletedEvent(object sender, DataRowChangeEventArgs e) { DataTable dt = e.Row.Table; dt.RowChanged -= new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting -= new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted -= new DataRowChangeEventHandler(GridRowDeleted); dt.AcceptChanges(); dt.RowChanged += new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting += new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted += new DataRowChangeEventHandler(GridRowDeleted); } private void ColorTextBox(object sender, System.EventArgs e) { TextBox txtBox = (TextBox)sender; // Bail if we're in la la land Size size = txtBox.Size; if(size.Width == 0 && size.Height == 0) { return; } int row = this.XmlEditor.CurrentCell.RowNumber; int col = this.XmlEditor.CurrentCell.ColumnNumber; if(isEven(row)) txtBox.BackColor = Color.LightSteelBlue; else txtBox.BackColor = Color.LightGray; if(col == 0) { if(txtBox.Text == string.Empty) txtBox.ReadOnly = false; else txtBox.ReadOnly = true; } } private bool isEven(int x) { return (x & 1) == 0; } private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) { DefaultSettings settings = DefaultSettings.Instance; switch(e.Button.Tag as string) { case "save": xml.Save(settings.LanguageMappingFile); MarkAsDirty(false); break; case "new": { int count = this.cboxLanguage.Items.Count; string[] languages = new string[count]; for(int i = 0; i < this.cboxLanguage.Items.Count; i++) { languages[i] = this.cboxLanguage.Items[i] as string; } AddLanguageMappingDialog dialog = new AddLanguageMappingDialog(languages, this.dbDriver); if(dialog.ShowDialog() == DialogResult.OK) { if(dialog.BasedUpon != string.Empty) { string xPath = @"//Languages/Language[@From='" + this.dbDriver + "' and @To='" + dialog.BasedUpon + "']"; XmlNode node = xml.SelectSingleNode(xPath); XmlNode newNode = node.CloneNode(true); newNode.Attributes["To"].Value = dialog.NewLanguage; node.ParentNode.AppendChild(newNode); } else { XmlNode parentNode = xml.SelectSingleNode(@"//Languages"); XmlAttribute attr; // Language Node langNode = xml.CreateNode(XmlNodeType.Element, "Language", null); parentNode.AppendChild(langNode); attr = xml.CreateAttribute("From"); attr.Value = settings.DbDriver; langNode.Attributes.Append(attr); attr = xml.CreateAttribute("To"); attr.Value = dialog.NewLanguage; langNode.Attributes.Append(attr); } this.cboxLanguage.Items.Add(dialog.NewLanguage); this.cboxLanguage.SelectedItem = dialog.NewLanguage; PopulateGrid(this.dbDriver); MarkAsDirty(true); } } break; case "delete": if(this.cboxLanguage.SelectedItem != null) { string language = this.cboxLanguage.SelectedItem as String; DialogResult result = MessageBox.Show("Delete '" + language + "' Mappings. Are you sure?", "Delete Language Mappings", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if(result == DialogResult.Yes) { string xPath = @"//Languages/Language[@From='" + this.dbDriver + "' and @To='" + language + "']"; XmlNode node = xml.SelectSingleNode(xPath); node.ParentNode.RemoveChild(node); this.cboxLanguage.Items.Remove(language); if(this.cboxLanguage.Items.Count > 0) { this.cboxLanguage.SelectedItem = this.cboxLanguage.SelectedIndex = 0; } PopulateGrid(this.dbDriver); MarkAsDirty(true); } } break; } } private XmlDocument xml = new XmlDocument(); private XmlNode langNode = null; private string dbDriver = ""; private bool isDirty = false; #region IMyGenContent Members public ToolStrip ToolStrip { get { return null; } } public void ProcessAlert(IMyGenContent sender, string command, params object[] args) { if (command.Equals("UpdateDefaultSettings", StringComparison.CurrentCultureIgnoreCase)) { DefaultSettings settings = DefaultSettings.Instance; PromptForSave(false); this.dbDriver = settings.DbDriver; PopulateComboBox(settings); PopulateGrid(this.dbDriver); MarkAsDirty(false); } } public DockContent DockContent { get { return this; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using Validation; namespace System.Collections.Immutable { /// <summary> /// A set of initialization methods for instances of <see cref="ImmutableSortedDictionary{TKey, TValue}"/>. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public static class ImmutableSortedDictionary { /// <summary> /// Returns an empty collection. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <returns>The immutable collection.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>() { return ImmutableSortedDictionary<TKey, TValue>.Empty; } /// <summary> /// Returns an empty collection. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <returns>The immutable collection.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>(IComparer<TKey> keyComparer) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer); } /// <summary> /// Returns an empty collection. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <returns>The immutable collection.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableSortedDictionary<TKey, TValue>.Empty.AddRange(items); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IComparer<TKey> keyComparer, IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer).AddRange(items); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(items); } /// <summary> /// Creates a new immutable sorted dictionary builder. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <returns>The immutable collection builder.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>() { return Create<TKey, TValue>().ToBuilder(); } /// <summary> /// Creates a new immutable sorted dictionary builder. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <returns>The immutable collection builder.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IComparer<TKey> keyComparer) { return Create<TKey, TValue>(keyComparer).ToBuilder(); } /// <summary> /// Creates a new immutable sorted dictionary builder. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <returns>The immutable collection builder.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { return Create<TKey, TValue>(keyComparer, valueComparer).ToBuilder(); } /// <summary> /// Constructs an immutable sorted dictionary based on some transformation of a sequence. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <typeparam name="TKey">The type of key in the resulting map.</typeparam> /// <typeparam name="TValue">The type of value in the resulting map.</typeparam> /// <param name="source">The sequence to enumerate to generate the map.</param> /// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param> /// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param> /// <param name="keyComparer">The key comparer to use for the map.</param> /// <param name="valueComparer">The value comparer to use for the map.</param> /// <returns>The immutable map.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { Requires.NotNull(source, "source"); Requires.NotNull(keySelector, "keySelector"); Requires.NotNull(elementSelector, "elementSelector"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer) .AddRange(source.Select(element => new KeyValuePair<TKey, TValue>(keySelector(element), elementSelector(element)))); } /// <summary> /// Constructs an immutable sorted dictionary based on some transformation of a sequence. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <typeparam name="TKey">The type of key in the resulting map.</typeparam> /// <typeparam name="TValue">The type of value in the resulting map.</typeparam> /// <param name="source">The sequence to enumerate to generate the map.</param> /// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param> /// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param> /// <param name="keyComparer">The key comparer to use for the map.</param> /// <returns>The immutable map.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IComparer<TKey> keyComparer) { return ToImmutableSortedDictionary(source, keySelector, elementSelector, keyComparer, null); } /// <summary> /// Constructs an immutable sorted dictionary based on some transformation of a sequence. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <typeparam name="TKey">The type of key in the resulting map.</typeparam> /// <typeparam name="TValue">The type of value in the resulting map.</typeparam> /// <param name="source">The sequence to enumerate to generate the map.</param> /// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param> /// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param> /// <returns>The immutable map.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector) { return ToImmutableSortedDictionary(source, keySelector, elementSelector, null, null); } /// <summary> /// Creates an immutable sorted dictionary given a sequence of key=value pairs. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="source">The sequence of key=value pairs.</param> /// <param name="keyComparer">The key comparer to use when building the immutable map.</param> /// <param name="valueComparer">The value comparer to use for the immutable map.</param> /// <returns>An immutable map.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { Requires.NotNull(source, "source"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); var existingDictionary = source as ImmutableSortedDictionary<TKey, TValue>; if (existingDictionary != null) { return existingDictionary.WithComparers(keyComparer, valueComparer); } return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(source); } /// <summary> /// Creates an immutable sorted dictionary given a sequence of key=value pairs. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="source">The sequence of key=value pairs.</param> /// <param name="keyComparer">The key comparer to use when building the immutable map.</param> /// <returns>An immutable map.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IComparer<TKey> keyComparer) { return ToImmutableSortedDictionary(source, keyComparer, null); } /// <summary> /// Creates an immutable sorted dictionary given a sequence of key=value pairs. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="source">The sequence of key=value pairs.</param> /// <returns>An immutable map.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source) { return ToImmutableSortedDictionary(source, null, null); } } }
/* XML-RPC.NET library Copyright (c) 2001-2011, Charles Cook <[email protected]> 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 CookComputing.XmlRpc { using System; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Threading; public class XmlRpcAsyncResult : IAsyncResult { public XmlRpcFormatSettings XmlRpcFormatSettings { get; private set; } // IAsyncResult members public object AsyncState { get { return userAsyncState; } } public WaitHandle AsyncWaitHandle { get { bool completed = isCompleted; if (manualResetEvent == null) { lock(this) { if (manualResetEvent == null) manualResetEvent = new ManualResetEvent(completed); } } if (!completed && isCompleted) manualResetEvent.Set(); return manualResetEvent; } } public bool CompletedSynchronously { get { return completedSynchronously; } set { if (completedSynchronously) completedSynchronously = value; } } public bool IsCompleted { get { return isCompleted; } } public CookieCollection ResponseCookies { get { return _responseCookies; } } public WebHeaderCollection ResponseHeaders { get { return _responseHeaders; } } // public members public void Abort() { if (request != null) request.Abort(); } public Exception Exception { get { return exception; } } public XmlRpcClientProtocol ClientProtocol { get { return clientProtocol; } } //internal members internal XmlRpcAsyncResult( XmlRpcClientProtocol ClientProtocol, XmlRpcRequest XmlRpcReq, XmlRpcFormatSettings xmlRpcFormatSettings, WebRequest Request, AsyncCallback UserCallback, object UserAsyncState, int retryNumber) { xmlRpcRequest = XmlRpcReq; clientProtocol = ClientProtocol; request = Request; userAsyncState = UserAsyncState; userCallback = UserCallback; completedSynchronously = true; XmlRpcFormatSettings = xmlRpcFormatSettings; } internal void Complete( Exception ex) { exception = ex; Complete(); } internal void Complete() { try { if (responseStream != null) { responseStream.Close(); responseStream = null; } if (responseBufferedStream != null) responseBufferedStream.Position = 0; } catch(Exception ex) { if (exception == null) exception = ex; } isCompleted = true; try { if (manualResetEvent != null) manualResetEvent.Set(); } catch(Exception ex) { if (exception == null) exception = ex; } if (userCallback != null) userCallback(this); } internal WebResponse WaitForResponse() { if (!isCompleted) AsyncWaitHandle.WaitOne(); if (exception != null) throw exception; return response; } internal bool EndSendCalled { get { return endSendCalled; } set { endSendCalled = value; } } internal byte[] Buffer { get { return buffer; } set { buffer = value; } } internal WebRequest Request { get { return request; } } internal WebResponse Response { get { return response; } set { response = value; } } internal Stream ResponseStream { get { return responseStream; } set { responseStream = value; } } internal XmlRpcRequest XmlRpcRequest { get { return xmlRpcRequest; } set { xmlRpcRequest = value; } } internal Stream ResponseBufferedStream { get { return responseBufferedStream; } set { responseBufferedStream = value; } } XmlRpcClientProtocol clientProtocol; WebRequest request; AsyncCallback userCallback; object userAsyncState; bool completedSynchronously; bool isCompleted; bool endSendCalled = false; ManualResetEvent manualResetEvent; Exception exception; WebResponse response; Stream responseStream; Stream responseBufferedStream; byte[] buffer; XmlRpcRequest xmlRpcRequest; internal CookieCollection _responseCookies; internal WebHeaderCollection _responseHeaders; } }
// 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 ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.extension02.extension02 { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an Extension method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public static class Extension { public static int Foo(this Parent p, dynamic x = null) { return 0; } } public class Parent { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.extension02a.extension02a { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an Extension method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public static class Extension { public static int Foo(this Parent p, int? x = 1) { return 0; } } public class Parent { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); try { p.Foo(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.NoSuchMember, e.Message, "Parent", "Foo"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.extension02b.extension02b { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of an Extension method with optional parameters</Description> // <Expects status=success></Expects> // <Code> public static class Extension { public static int Foo(this Parent p, int? x = 1) { return x == null ? 0 : 1; } } public class Parent { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = null; try { p.Foo(d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.NoSuchMember, e.Message, "Parent", "Foo"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.partial04b.partial04b { public partial class Parent { partial void Foo(int? i = 0); } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.partial04b.partial04b { // <Area>Declaration of Methods with Optional Parameters</Area> // <Title>Declaration of Optional Params</Title> // <Description>Simple Declaration of a Partial class with OPs</Description> // <Expects status=success></Expects> // <Code> public partial class Parent { public Parent() { TestOk = false; } public bool TestOk { get; set; } public void FooTest() { Foo(); } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); p.FooTest(); if (p.TestOk) return 1; return 0; } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array01.array01 { // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic[] i = null) { if (i == null) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array01a.array01a { // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int?[] i = null) { if (i == null) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); return p.Foo(); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array01b.array01b { // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int?[] i = null) { if (i[0] == null && i[1] == 1) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new int?[] { null, 1 } ; dynamic p = new Parent(); return p.Foo(d); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array03.array03 { // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic[] i = null) { if (i[1] == 2) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(new object[] { 1, 2, 3 } ); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array03a.array03a { // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int?[] i = null) { if (i[1] == 2) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = new int?[] { 1, 2, 3 } ; return p.Foo(d); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array04.array04 { // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(dynamic[] i = null) { if (i[1] == 2) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Parent p = new Parent(); return p.Foo(i: new object[] { 1, 2, 3 } ); } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.other.array04a.array04a { // <Area>Use of optional Params</Area> // <Title>Use of optional arrays</Title> // <Description>should be able to have a default array</Description> // <Expects status=success></Expects> // <Code> public class Parent { public int Foo(int?[] i = null) { if (i[1] == 2) return 0; return 1; } } public class Test { private const int i = 5; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic p = new Parent(); dynamic d = new int?[] { 1, 2, null } ; return p.Foo(i: d); } } }
using System; using System.Globalization; using Umbraco.Core; using Umbraco.Core.Models; using UmbracoSettings = Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Web.Configuration; using umbraco; using umbraco.cms.businesslogic.web; namespace Umbraco.Web.Routing { /// <summary> /// Represents a request for one specified Umbraco IPublishedContent to be rendered /// by one specified template, using one specified Culture and RenderingEngine. /// </summary> public class PublishedContentRequest { private bool _readonly; /// <summary> /// Triggers once the published content request has been prepared, but before it is processed. /// </summary> /// <remarks>When the event triggers, preparation is done ie domain, culture, document, template, /// rendering engine, etc. have been setup. It is then possible to change anything, before /// the request is actually processed and rendered by Umbraco.</remarks> public static event EventHandler<EventArgs> Prepared; // the engine that does all the processing // because in order to keep things clean and separated, // the content request is just a data holder private readonly PublishedContentRequestEngine _engine; /// <summary> /// Initializes a new instance of the <see cref="PublishedContentRequest"/> class with a specific Uri and routing context. /// </summary> /// <param name="uri">The request <c>Uri</c>.</param> /// <param name="routingContext">A routing context.</param> internal PublishedContentRequest(Uri uri, RoutingContext routingContext) { if (uri == null) throw new ArgumentNullException("uri"); if (routingContext == null) throw new ArgumentNullException("routingContext"); Uri = uri; RoutingContext = routingContext; _engine = new PublishedContentRequestEngine(this); RenderingEngine = RenderingEngine.Unknown; } /// <summary> /// Gets the engine associated to the request. /// </summary> internal PublishedContentRequestEngine Engine { get { return _engine; } } /// <summary> /// Prepares the request. /// </summary> internal void Prepare() { _engine.PrepareRequest(); } /// <summary> /// Updates the request when there is no template to render the content. /// </summary> internal void UpdateOnMissingTemplate() { var __readonly = _readonly; _readonly = false; _engine.UpdateRequestOnMissingTemplate(); _readonly = __readonly; } /// <summary> /// Triggers the Prepared event. /// </summary> internal void OnPrepared() { if (Prepared != null) Prepared(this, EventArgs.Empty); if (!HasPublishedContent) Is404 = true; // safety _readonly = true; } /// <summary> /// Gets or sets the cleaned up Uri used for routing. /// </summary> /// <remarks>The cleaned up Uri has no virtual directory, no trailing slash, no .aspx extension, etc.</remarks> public Uri Uri { get; private set; } private void EnsureWriteable() { if (_readonly) throw new InvalidOperationException("Cannot modify a PublishedContentRequest once it is read-only."); } #region PublishedContent /// <summary> /// The requested IPublishedContent, if any, else <c>null</c>. /// </summary> private IPublishedContent _publishedContent; /// <summary> /// The initial requested IPublishedContent, if any, else <c>null</c>. /// </summary> /// <remarks>The initial requested content is the content that was found by the finders, /// before anything such as 404, redirect... took place.</remarks> private IPublishedContent _initialPublishedContent; /// <summary> /// Gets or sets the requested content. /// </summary> /// <remarks>Setting the requested content clears <c>Template</c>.</remarks> public IPublishedContent PublishedContent { get { return _publishedContent; } set { EnsureWriteable(); _publishedContent = value; IsInternalRedirectPublishedContent = false; TemplateModel = null; } } /// <summary> /// Sets the requested content, following an internal redirect. /// </summary> /// <param name="content">The requested content.</param> /// <remarks>Depending on <c>UmbracoSettings.InternalRedirectPreservesTemplate</c>, will /// preserve or reset the template, if any.</remarks> public void SetInternalRedirectPublishedContent(IPublishedContent content) { EnsureWriteable(); // unless a template has been set already by the finder, // template should be null at that point. // IsInternalRedirect if IsInitial, or already IsInternalRedirect var isInternalRedirect = IsInitialPublishedContent || IsInternalRedirectPublishedContent; // redirecting to self if (content.Id == PublishedContent.Id) // neither can be null { // no need to set PublishedContent, we're done IsInternalRedirectPublishedContent = isInternalRedirect; return; } // else // save var template = _template; var renderingEngine = RenderingEngine; // set published content - this resets the template, and sets IsInternalRedirect to false PublishedContent = content; IsInternalRedirectPublishedContent = isInternalRedirect; // must restore the template if it's an internal redirect & the config option is set if (isInternalRedirect && UmbracoSettings.For<WebRouting>().InternalRedirectPreservesTemplate) { // restore _template = template; RenderingEngine = renderingEngine; } } /// <summary> /// Gets the initial requested content. /// </summary> /// <remarks>The initial requested content is the content that was found by the finders, /// before anything such as 404, redirect... took place.</remarks> public IPublishedContent InitialPublishedContent { get { return _initialPublishedContent; } } /// <summary> /// Gets value indicating whether the current published content is the initial one. /// </summary> public bool IsInitialPublishedContent { get { return _initialPublishedContent != null && _initialPublishedContent == _publishedContent; } } /// <summary> /// Indicates that the current PublishedContent is the initial one. /// </summary> public void SetIsInitialPublishedContent() { EnsureWriteable(); // note: it can very well be null if the initial content was not found _initialPublishedContent = _publishedContent; IsInternalRedirectPublishedContent = false; } /// <summary> /// Gets or sets a value indicating whether the current published content has been obtained /// from the initial published content following internal redirections exclusively. /// </summary> /// <remarks>Used by PublishedContentRequestEngine.FindTemplate() to figure out whether to /// apply the internal redirect or not, when content is not the initial content.</remarks> public bool IsInternalRedirectPublishedContent { get; private set; } /// <summary> /// Gets a value indicating whether the content request has a content. /// </summary> public bool HasPublishedContent { get { return PublishedContent != null; } } #endregion #region Template /// <summary> /// The template model, if any, else <c>null</c>. /// </summary> private ITemplate _template; /// <summary> /// Gets or sets the template model to use to display the requested content. /// </summary> internal ITemplate TemplateModel { get { return _template; } set { _template = value; RenderingEngine = RenderingEngine.Unknown; // reset if (_template != null) RenderingEngine = _engine.FindTemplateRenderingEngine(_template.Alias); } } /// <summary> /// Gets the alias of the template to use to display the requested content. /// </summary> public string TemplateAlias { get { return _template == null ? null : _template.Alias; } } /// <summary> /// Tries to set the template to use to display the requested content. /// </summary> /// <param name="alias">The alias of the template.</param> /// <returns>A value indicating whether a valid template with the specified alias was found.</returns> /// <remarks> /// <para>Successfully setting the template does refresh <c>RenderingEngine</c>.</para> /// <para>If setting the template fails, then the previous template (if any) remains in place.</para> /// </remarks> public bool TrySetTemplate(string alias) { EnsureWriteable(); if (string.IsNullOrWhiteSpace(alias)) { TemplateModel = null; return true; } // NOTE - can we stil get it with whitespaces in it due to old legacy bugs? alias = alias.Replace(" ", ""); var model = ApplicationContext.Current.Services.FileService.GetTemplate(alias); if (model == null) return false; TemplateModel = model; return true; } /// <summary> /// Sets the template to use to display the requested content. /// </summary> /// <param name="template">The template.</param> /// <remarks>Setting the template does refresh <c>RenderingEngine</c>.</remarks> public void SetTemplate(ITemplate template) { EnsureWriteable(); TemplateModel = template; } /// <summary> /// Gets a value indicating whether the content request has a template. /// </summary> public bool HasTemplate { get { return _template != null; } } #endregion #region Domain and Culture /// <summary> /// Gets or sets the content request's domain. /// </summary> public Domain Domain { get; internal set; } /// <summary> /// Gets or sets the content request's domain Uri. /// </summary> /// <remarks>The <c>Domain</c> may contain "example.com" whereas the <c>Uri</c> will be fully qualified eg "http://example.com/".</remarks> public Uri DomainUri { get; internal set; } /// <summary> /// Gets a value indicating whether the content request has a domain. /// </summary> public bool HasDomain { get { return Domain != null; } } private CultureInfo _culture; /// <summary> /// Gets or sets the content request's culture. /// </summary> public CultureInfo Culture { get { return _culture; } set { EnsureWriteable(); _culture = value; } } // note: do we want to have an ordered list of alternate cultures, // to allow for fallbacks when doing dictionnary lookup and such? #endregion #region Rendering /// <summary> /// Gets or sets whether the rendering engine is MVC or WebForms. /// </summary> public RenderingEngine RenderingEngine { get; internal set; } #endregion /// <summary> /// Gets or sets the current RoutingContext. /// </summary> public RoutingContext RoutingContext { get; private set; } /// <summary> /// The "umbraco page" object. /// </summary> private page _umbracoPage; /// <summary> /// Gets or sets the "umbraco page" object. /// </summary> /// <remarks> /// This value is only used for legacy/webforms code. /// </remarks> internal page UmbracoPage { get { if (_umbracoPage == null) throw new InvalidOperationException("The umbraco page object is only available once Finalize()"); return _umbracoPage; } set { _umbracoPage = value; } } #region Status /// <summary> /// Gets or sets a value indicating whether the requested content could not be found. /// </summary> /// <remarks>This is set in the <c>PublishedContentRequestBuilder</c>.</remarks> public bool Is404 { get; internal set; } /// <summary> /// Indicates that the requested content could not be found. /// </summary> /// <remarks>This is for public access, in custom content finders or <c>Prepared</c> event handlers, /// where we want to allow developers to indicate a request is 404 but not to cancel it.</remarks> public void SetIs404() { EnsureWriteable(); Is404 = true; } /// <summary> /// Gets a value indicating whether the content request triggers a redirect (permanent or not). /// </summary> public bool IsRedirect { get { return !string.IsNullOrWhiteSpace(RedirectUrl); } } /// <summary> /// Gets or sets a value indicating whether the redirect is permanent. /// </summary> public bool IsRedirectPermanent { get; private set; } /// <summary> /// Gets or sets the url to redirect to, when the content request triggers a redirect. /// </summary> public string RedirectUrl { get; private set; } /// <summary> /// Indicates that the content request should trigger a redirect (302). /// </summary> /// <param name="url">The url to redirect to.</param> /// <remarks>Does not actually perform a redirect, only registers that the response should /// redirect. Redirect will or will not take place in due time.</remarks> public void SetRedirect(string url) { EnsureWriteable(); RedirectUrl = url; IsRedirectPermanent = false; } /// <summary> /// Indicates that the content request should trigger a permanent redirect (301). /// </summary> /// <param name="url">The url to redirect to.</param> /// <remarks>Does not actually perform a redirect, only registers that the response should /// redirect. Redirect will or will not take place in due time.</remarks> public void SetRedirectPermanent(string url) { EnsureWriteable(); RedirectUrl = url; IsRedirectPermanent = true; } /// <summary> /// Indicates that the content requet should trigger a redirect, with a specified status code. /// </summary> /// <param name="url">The url to redirect to.</param> /// <param name="status">The status code (300-308).</param> /// <remarks>Does not actually perform a redirect, only registers that the response should /// redirect. Redirect will or will not take place in due time.</remarks> public void SetRedirect(string url, int status) { EnsureWriteable(); if (status < 300 || status > 308) throw new ArgumentOutOfRangeException("status", "Valid redirection status codes 300-308."); RedirectUrl = url; IsRedirectPermanent = (status == 301 || status == 308); if (status != 301 && status != 302) // default redirect statuses ResponseStatusCode = status; } /// <summary> /// Gets or sets the content request http response status code. /// </summary> /// <remarks>Does not actually set the http response status code, only registers that the response /// should use the specified code. The code will or will not be used, in due time.</remarks> public int ResponseStatusCode { get; private set; } /// <summary> /// Gets or sets the content request http response status description. /// </summary> /// <remarks>Does not actually set the http response status description, only registers that the response /// should use the specified description. The description will or will not be used, in due time.</remarks> public string ResponseStatusDescription { get; private set; } /// <summary> /// Sets the http response status code, along with an optional associated description. /// </summary> /// <param name="code">The http status code.</param> /// <param name="description">The description.</param> /// <remarks>Does not actually set the http response status code and description, only registers that /// the response should use the specified code and description. The code and description will or will /// not be used, in due time.</remarks> public void SetResponseStatus(int code, string description = null) { EnsureWriteable(); // .Status is deprecated // .SubStatusCode is IIS 7+ internal, ignore ResponseStatusCode = code; ResponseStatusDescription = description; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using Xunit; namespace Microsoft.AspNetCore.Mvc.ModelBinding { public class ModelAttributesTest { [Fact] public void GetAttributesForBaseProperty_IncludesMetadataAttributes() { // Arrange var modelType = typeof(BaseViewModel); var property = modelType.GetRuntimeProperties().FirstOrDefault(p => p.Name == nameof(BaseModel.BaseProperty)); // Act var attributes = ModelAttributes.GetAttributesForProperty(modelType, property); // Assert Assert.Single(attributes.Attributes.OfType<RequiredAttribute>()); Assert.Single(attributes.Attributes.OfType<StringLengthAttribute>()); Assert.Single(attributes.PropertyAttributes.OfType<RequiredAttribute>()); Assert.Single(attributes.PropertyAttributes.OfType<StringLengthAttribute>()); } [Fact] public void GetAttributesForTestProperty_ModelOverridesMetadataAttributes() { // Arrange var modelType = typeof(BaseViewModel); var property = modelType.GetRuntimeProperties().FirstOrDefault(p => p.Name == nameof(BaseModel.TestProperty)); // Act var attributes = ModelAttributes.GetAttributesForProperty(modelType, property); // Assert var rangeAttributes = attributes.Attributes.OfType<RangeAttribute>().ToArray(); Assert.NotNull(rangeAttributes[0]); Assert.Equal(0, (int)rangeAttributes[0].Minimum); Assert.Equal(10, (int)rangeAttributes[0].Maximum); Assert.NotNull(rangeAttributes[1]); Assert.Equal(10, (int)rangeAttributes[1].Minimum); Assert.Equal(100, (int)rangeAttributes[1].Maximum); Assert.Single(attributes.Attributes.OfType<FromHeaderAttribute>()); rangeAttributes = attributes.PropertyAttributes.OfType<RangeAttribute>().ToArray(); Assert.NotNull(rangeAttributes[0]); Assert.Equal(0, (int)rangeAttributes[0].Minimum); Assert.Equal(10, (int)rangeAttributes[0].Maximum); Assert.NotNull(rangeAttributes[1]); Assert.Equal(10, (int)rangeAttributes[1].Minimum); Assert.Equal(100, (int)rangeAttributes[1].Maximum); Assert.Single(attributes.PropertyAttributes.OfType<FromHeaderAttribute>()); } [Fact] public void GetAttributesForBasePropertyFromDerivedModel_IncludesMetadataAttributes() { // Arrange var modelType = typeof(DerivedViewModel); var property = modelType.GetRuntimeProperties().FirstOrDefault(p => p.Name == nameof(BaseModel.BaseProperty)); // Act var attributes = ModelAttributes.GetAttributesForProperty(modelType, property); // Assert Assert.Single(attributes.Attributes.OfType<RequiredAttribute>()); Assert.Single(attributes.Attributes.OfType<StringLengthAttribute>()); Assert.Single(attributes.PropertyAttributes.OfType<RequiredAttribute>()); Assert.Single(attributes.PropertyAttributes.OfType<StringLengthAttribute>()); } [Fact] public void GetAttributesForTestPropertyFromDerived_IncludesMetadataAttributes() { // Arrange var modelType = typeof(DerivedViewModel); var property = modelType.GetRuntimeProperties().FirstOrDefault(p => p.Name == nameof(BaseModel.TestProperty)); // Act var attributes = ModelAttributes.GetAttributesForProperty(modelType, property); // Assert Assert.Single(attributes.Attributes.OfType<RequiredAttribute>()); Assert.Single(attributes.Attributes.OfType<StringLengthAttribute>()); Assert.DoesNotContain(typeof(RangeAttribute), attributes.Attributes); Assert.Single(attributes.PropertyAttributes.OfType<RequiredAttribute>()); Assert.Single(attributes.PropertyAttributes.OfType<StringLengthAttribute>()); Assert.DoesNotContain(typeof(RangeAttribute), attributes.PropertyAttributes); } [Fact] public void GetAttributesForVirtualPropertyFromDerived_IncludesMetadataAttributes() { // Arrange var modelType = typeof(DerivedViewModel); var property = modelType.GetRuntimeProperties().FirstOrDefault(p => p.Name == nameof(BaseModel.VirtualProperty)); // Act var attributes = ModelAttributes.GetAttributesForProperty(modelType, property); // Assert Assert.Single(attributes.Attributes.OfType<RequiredAttribute>()); Assert.Single(attributes.Attributes.OfType<RangeAttribute>()); Assert.Single(attributes.PropertyAttributes.OfType<RequiredAttribute>()); Assert.Single(attributes.PropertyAttributes.OfType<RangeAttribute>()); } [Fact] public void GetFromServiceAttributeFromBase_IncludesMetadataAttributes() { // Arrange var modelType = typeof(DerivedViewModel); var property = modelType.GetRuntimeProperties().FirstOrDefault(p => p.Name == nameof(BaseModel.RouteValue)); // Act var attributes = ModelAttributes.GetAttributesForProperty(modelType, property); // Assert Assert.Single(attributes.Attributes.OfType<RequiredAttribute>()); Assert.Single(attributes.Attributes.OfType<FromRouteAttribute>()); Assert.Single(attributes.PropertyAttributes.OfType<RequiredAttribute>()); Assert.Single(attributes.PropertyAttributes.OfType<FromRouteAttribute>()); } [Fact] public void GetAttributesForType_IncludesMetadataAttributes() { // Arrange & Act var attributes = ModelAttributes.GetAttributesForType(typeof(BaseViewModel)); // Assert Assert.Single(attributes.Attributes.OfType<ClassValidator>()); Assert.Single(attributes.TypeAttributes.OfType<ClassValidator>()); } [Fact] public void GetAttributesForType_PropertyAttributes_IsNull() { // Arrange & Act var attributes = ModelAttributes.GetAttributesForType(typeof(BaseViewModel)); // Assert Assert.Null(attributes.PropertyAttributes); } [Fact] public void GetAttributesForProperty_MergedAttributes() { // Arrange var property = typeof(MergedAttributes).GetRuntimeProperty(nameof(MergedAttributes.Property)); // Act var attributes = ModelAttributes.GetAttributesForProperty(typeof(MergedAttributes), property); // Assert Assert.Equal(3, attributes.Attributes.Count); Assert.IsType<RequiredAttribute>(attributes.Attributes[0]); Assert.IsType<RangeAttribute>(attributes.Attributes[1]); Assert.IsType<ClassValidator>(attributes.Attributes[2]); Assert.Equal(2, attributes.PropertyAttributes.Count); Assert.IsType<RequiredAttribute>(attributes.PropertyAttributes[0]); Assert.IsType<RangeAttribute>(attributes.PropertyAttributes[1]); var attribute = Assert.Single(attributes.TypeAttributes); Assert.IsType<ClassValidator>(attribute); } [Fact] public void GetAttributesForParameter_NoAttributes() { // Arrange & Act var attributes = ModelAttributes.GetAttributesForParameter( typeof(MethodWithParamAttributesType) .GetMethod(nameof(MethodWithParamAttributesType.Method)) .GetParameters()[0]); // Assert // Not exactly "no attributes" due to SerializableAttribute on object. Assert.IsType<SerializableAttribute>(Assert.Single(attributes.Attributes)); Assert.Empty(attributes.ParameterAttributes); Assert.Null(attributes.PropertyAttributes); Assert.Equal(attributes.Attributes, attributes.TypeAttributes); } [Fact] public void GetAttributesForParameter_SomeAttributes() { // Arrange & Act var attributes = ModelAttributes.GetAttributesForParameter( typeof(MethodWithParamAttributesType) .GetMethod(nameof(MethodWithParamAttributesType.Method)) .GetParameters()[1]); // Assert Assert.Collection( // Take(2) to ignore ComVisibleAttribute, SerializableAttribute, ... on int. attributes.Attributes.Take(2), attribute => Assert.IsType<RequiredAttribute>(attribute), attribute => Assert.IsType<RangeAttribute>(attribute)); Assert.Collection( attributes.ParameterAttributes, attribute => Assert.IsType<RequiredAttribute>(attribute), attribute => Assert.IsType<RangeAttribute>(attribute)); Assert.Null(attributes.PropertyAttributes); Assert.Collection( // Take(1) because the attribute or attributes after SerializableAttribute are framework-specific. attributes.TypeAttributes.Take(1), attribute => Assert.IsType<SerializableAttribute>(attribute)); } [Fact] public void GetAttributesForParameter_IncludesTypeAttributes() { // Arrange var parameters = typeof(MethodWithParamAttributesType) .GetMethod(nameof(MethodWithParamAttributesType.Method)) .GetParameters(); // Act var attributes = ModelAttributes.GetAttributesForParameter(parameters[2]); // Assert Assert.Collection(attributes.Attributes, attribute => Assert.IsType<BindRequiredAttribute>(attribute), attribute => Assert.IsType<ClassValidator>(attribute)); Assert.IsType<BindRequiredAttribute>(Assert.Single(attributes.ParameterAttributes)); Assert.Null(attributes.PropertyAttributes); Assert.IsType<ClassValidator>(Assert.Single(attributes.TypeAttributes)); } [Fact] public void GetAttributesForParameter_WithModelType_IncludesTypeAttributes() { // Arrange var parameters = typeof(MethodWithParamAttributesType) .GetMethod(nameof(MethodWithParamAttributesType.Method)) .GetParameters(); // Act var attributes = ModelAttributes.GetAttributesForParameter(parameters[2], typeof(DerivedModelWithAttributes)); // Assert Assert.Collection( attributes.Attributes, attribute => Assert.IsType<BindRequiredAttribute>(attribute), attribute => Assert.IsType<ModelBinderAttribute>(attribute), attribute => Assert.IsType<ClassValidator>(attribute)); Assert.IsType<BindRequiredAttribute>(Assert.Single(attributes.ParameterAttributes)); Assert.Null(attributes.PropertyAttributes); Assert.Collection( attributes.TypeAttributes, attribute => Assert.IsType<ModelBinderAttribute>(attribute), attribute => Assert.IsType<ClassValidator>(attribute)); } [Fact] public void GetAttributesForProperty_WithModelType_IncludesTypeAttributes() { // Arrange var property = typeof(MergedAttributes) .GetProperty(nameof(MergedAttributes.BaseModel)); // Act var attributes = ModelAttributes.GetAttributesForProperty(typeof(MergedAttributes), property, typeof(DerivedModelWithAttributes)); // Assert Assert.Collection( attributes.Attributes, attribute => Assert.IsType<BindRequiredAttribute>(attribute), attribute => Assert.IsType<ModelBinderAttribute>(attribute), attribute => Assert.IsType<ClassValidator>(attribute)); Assert.IsType<BindRequiredAttribute>(Assert.Single(attributes.PropertyAttributes)); Assert.Null(attributes.ParameterAttributes); Assert.Collection( attributes.TypeAttributes, attribute => Assert.IsType<ModelBinderAttribute>(attribute), attribute => Assert.IsType<ClassValidator>(attribute)); } [ClassValidator] private class BaseModel { [StringLength(10)] public string BaseProperty { get; set; } [Range(10,100)] [FromHeader] public string TestProperty { get; set; } [Required] public virtual int VirtualProperty { get; set; } [FromRoute] public string RouteValue { get; set; } } private class DerivedModel : BaseModel { [Required] public string DerivedProperty { get; set; } [Required] public new string TestProperty { get; set; } [Range(10,100)] public override int VirtualProperty { get; set; } } [ModelBinder(Name = "Custom")] private class DerivedModelWithAttributes : BaseModel { } [ModelMetadataType(typeof(BaseModel))] private class BaseViewModel { [Range(0,10)] public string TestProperty { get; set; } [Required] public string BaseProperty { get; set; } [Required] public string RouteValue { get; set; } } [ModelMetadataType(typeof(DerivedModel))] private class DerivedViewModel : BaseViewModel { [StringLength(2)] public new string TestProperty { get; set; } public int VirtualProperty { get; set; } } public interface ICalculator { int Operation(char @operator, int left, int right); } private class ClassValidator : ValidationAttribute { public override bool IsValid(object value) { return true; } } [ModelMetadataType(typeof(MergedAttributesMetadata))] private class MergedAttributes { [Required] public PropertyType Property { get; set; } [BindRequired] public BaseModel BaseModel { get; set; } } private class MergedAttributesMetadata { [Range(0, 10)] public MetadataPropertyType Property { get; set; } } [ClassValidator] private class PropertyType { } [Bind] private class MetadataPropertyType { } [IrrelevantAttribute] // We verify this is ignored private class MethodWithParamAttributesType { [IrrelevantAttribute] // We verify this is ignored public void Method( object noAttributes, [Required, Range(1, 100)] int validationAttributes, [BindRequired] BaseModel mergedAttributes) { } } private class IrrelevantAttribute : Attribute { } } }
// 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. // // // All P/invokes used by internal Interop code goes here // // !!IMPORTANT!! // // Do not rely on MCG to generate marshalling code for these p/invokes as MCG might not see them at all // due to not seeing dependency to those calls (before the MCG generated code is generated). Instead, // always manually marshal the arguments using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; // TODO : Remove the remaning methods in this file to correct interop*.cs files under Interop folder partial class Interop { #if TARGET_CORE_API_SET internal const string CORE_SYNCH_L2 = "api-ms-win-core-synch-l1-2-0.dll"; #else // // Define dll names for previous version of Windows earlier than Windows 8 // internal const string CORE_SYNCH_L2 = "kernel32.dll"; internal const string CORE_COM = "ole32.dll"; internal const string CORE_COM_AUT = "OleAut32.dll"; #endif internal unsafe partial class COM { // // IIDs // internal static Guid IID_IUnknown = new Guid(0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); internal static Guid IID_IMarshal = new Guid(0x00000003, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); internal static Guid IID_IAgileObject = new Guid(unchecked((int)0x94ea2b94), unchecked((short)0xe9cc), 0x49e0, 0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90); internal static Guid IID_IContextCallback = new Guid(0x000001da, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); internal static Guid IID_IEnterActivityWithNoLock = new Guid(unchecked((int)0xd7174f82), 0x36b8, 0x4aa8, 0x80, 0x0a, 0xe9, 0x63, 0xab, 0x2d, 0xfa, 0xb9); internal static Guid IID_ICustomPropertyProvider = new Guid(unchecked(((int)(0x7C925755u))), unchecked(((short)(0x3E48))), unchecked(((short)(0x42B4))), 0x86, 0x77, 0x76, 0x37, 0x22, 0x67, 0x3, 0x3F); internal static Guid IID_IInspectable = new Guid(unchecked((int)0xAF86E2E0), unchecked((short)0xB12D), 0x4c6a, 0x9C, 0x5A, 0xD7, 0xAA, 0x65, 0x10, 0x1E, 0x90); internal static Guid IID_IWeakReferenceSource = new Guid(0x00000038, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); internal static Guid IID_IWeakReference = new Guid(0x00000037, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); internal static Guid IID_IFindDependentWrappers = new Guid(0x04b3486c, 0x4687, 0x4229, 0x8d, 0x14, 0x50, 0x5a, 0xb5, 0x84, 0xdd, 0x88); internal static Guid IID_IStringable = new Guid(unchecked((int)0x96369f54), unchecked((short)0x8eb6), 0x48f0, 0xab, 0xce, 0xc1, 0xb2, 0x11, 0xe6, 0x27, 0xc3); internal static Guid IID_IRestrictedErrorInfo = new Guid(unchecked((int)0x82ba7092), unchecked((short)0x4c88), unchecked((short)0x427d), 0xa7, 0xbc, 0x16, 0xdd, 0x93, 0xfe, 0xb6, 0x7e); internal static Guid IID_ILanguageExceptionErrorInfo = new Guid(unchecked((int)0x04a2dbf3), unchecked((short)0xdf83), unchecked((short)0x116c), 0x09, 0x46, 0x08, 0x12, 0xab, 0xf6, 0xe0, 0x7d); internal static Guid IID_INoMarshal = new Guid(unchecked((int)0xECC8691B), unchecked((short)0xC1DB), 0x4DC0, 0x85, 0x5E, 0x65, 0xF6, 0xC5, 0x51, 0xAF, 0x49); internal static Guid IID_IStream = new Guid(0x0000000C, 0x0000, 0x0000, 0xC0, 0x00, 0x00,0x00,0x00, 0x00,0x00, 0x46); internal static Guid IID_ISequentialStream = new Guid(unchecked((int)0x0C733A30), 0x2A1C, 0x11CE, 0xAD, 0xE5, 0x00, 0xAA, 0x00, 0x44, 0x77, 0x3D); internal static Guid IID_IDispatch = new Guid(0x00020400, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); internal static Guid IID_IManagedActivationFactory = new Guid(0x60D27C8D, 0x5F61, 0x4CCE, 0xB7, 0x51, 0x69, 0x0F, 0xAE, 0x66, 0xAA, 0x53); internal static Guid IID_IActivationFactoryInternal = new Guid(0x00000035, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); // CBE53FB5-F967-4258-8D34-42F5E25833DE internal static Guid IID_ILanguageExceptionStackBackTrace = new Guid(unchecked((int)0xCBE53FB5), unchecked((short)0xF967), 0x4258, 0x8D, 0x34, 0x42, 0xF5, 0xE2, 0x58, 0x33,0xDE); // // Jupiter IIDs. // // Note that the Windows sources refer to these IIDs via different names: // // IClrServices = Windows.UI.Xaml.Hosting.IReferenceTrackerHost // IJupiterObject = Windows.UI.Xaml.Hosting.IReferenceTracker // ICCW = Windows.UI.Xaml.Hosting.IReferenceTrackerTarget // internal static Guid IID_ICLRServices = new Guid(0x29a71c6a, 0x3c42, 0x4416, 0xa3, 0x9d, 0xe2, 0x82, 0x5a, 0x07, 0xa7, 0x73); internal static Guid IID_IJupiterObject = new Guid(0x11d3b13a, 0x180e, 0x4789, 0xa8, 0xbe, 0x77, 0x12, 0x88, 0x28, 0x93, 0xe6); internal static Guid IID_ICCW = new Guid(0x64bd43f8, unchecked((short)0xbfee), 0x4ec4, 0xb7, 0xeb, 0x29, 0x35, 0x15, 0x8d, 0xae, 0x21); // // CLSIDs // internal static Guid CLSID_InProcFreeMarshaler = new Guid(0x0000033A, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); [StructLayout(LayoutKind.Sequential)] internal struct MULTI_QI { internal IntPtr pIID; internal IntPtr pItf; internal int hr; } [StructLayout(LayoutKind.Sequential)] internal struct COSERVERINFO { internal int Reserved1; internal IntPtr Name; internal IntPtr AuthInfo; internal int Reserved2; } [Flags] internal enum CLSCTX : int { CLSCTX_INPROC_SERVER = 0x1, CLSCTX_LOCAL_SERVER = 0x4, CLSCTX_REMOTE_SERVER = 0x10, CLSCTX_SERVER = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER } [MethodImplAttribute(MethodImplOptions.NoInlining)] static unsafe internal string ConvertBSTRToString(IntPtr pBSTR) { String myString = null; if (pBSTR != default(IntPtr)) { myString = new String((char*)pBSTR, 0, (int)ExternalInterop.SysStringLen(pBSTR)); } return myString; } // // Constants and enums // internal enum MSHCTX : uint { MSHCTX_LOCAL = 0, // unmarshal context is local (eg.shared memory) MSHCTX_NOSHAREDMEM = 1, // unmarshal context has no shared memory access MSHCTX_DIFFERENTMACHINE = 2,// unmarshal context is on a different machine MSHCTX_INPROC = 3, // unmarshal context is on different thread } [Flags] internal enum MSHLFLAGS : uint { MSHLFLAGS_NORMAL = 0, // normal marshaling via proxy/stub MSHLFLAGS_TABLESTRONG = 1, // keep object alive; must explicitly release MSHLFLAGS_TABLEWEAK = 2, // doesn't hold object alive; still must release MSHLFLAGS_NOPING = 4 // remote clients dont 'ping' to keep objects alive } internal enum STREAM_SEEK : uint { STREAM_SEEK_SET = 0, STREAM_SEEK_CUR = 1, STREAM_SEEK_END = 2 } // // HRESULTs // internal const int S_OK = 0; internal const int S_FALSE = 0x00000001; internal const int E_FAIL = unchecked((int)0x80004005); internal const int E_OUTOFMEMORY = unchecked((int)0x8007000E); internal const int E_NOTIMPL = unchecked((int)0x80004001); internal const int E_NOINTERFACE = unchecked((int)0x80004002); internal const int E_INVALIDARG = unchecked((int)0x80070057); internal const int E_BOUNDS = unchecked((int)0x8000000B); internal const int E_POINTER = unchecked((int)0x80004003); internal const int E_CHANGED_STATE = unchecked((int)0x8000000C); internal const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622); internal const int RO_E_CLOSED = unchecked((int)0x80000013); internal const int TYPE_E_TYPEMISMATCH = unchecked((int)0x80028CA0); internal const int DISP_E_OVERFLOW = unchecked((int)0x8002000A); internal const int CLASS_E_NOAGGREGATION = unchecked((int)0x80040110); internal const int CLASS_E_CLASSNOTAVAILABLE = unchecked((int)0x80040111); /// <summary> /// Error indicates that you are accessing a CCW whose target object has already been garbage /// collected while the CCW still has non-0 jupiter ref counts /// </summary> internal const int COR_E_ACCESSING_CCW = unchecked((int)0x80131544); #pragma warning disable 649, 169 // Field 'blah' is never assigned to/Field 'blah' is never used // I use __vtbl to distingush from MCG vtables that are used for CCWs internal struct __vtbl_IUnknown { // IUnknown methods internal IntPtr pfnQueryInterface; internal IntPtr pfnAddRef; internal IntPtr pfnRelease; } internal struct __vtbl_ISequentialStream { __vtbl_IUnknown parent; internal IntPtr pfnRead; internal IntPtr pfnWrite; } internal unsafe struct __IStream { internal __vtbl_IStream* vtbl; } internal struct __vtbl_IStream { __vtbl_ISequentialStream parent; internal IntPtr pfnSeek; internal IntPtr pfnSetSize; internal IntPtr pfnCopyTo; internal IntPtr pfnCommit; internal IntPtr pfnRevert; internal IntPtr pfnLockRegion; internal IntPtr pfnUnlockRegion; internal IntPtr pfnStat; internal IntPtr pfnClone; } internal unsafe struct __IMarshal { internal __vtbl_IMarshal* vtbl; } internal struct __vtbl_IMarshal { __vtbl_IUnknown parent; internal IntPtr pfnGetUnmarshalClass; internal IntPtr pfnGetMarshalSizeMax; internal IntPtr pfnMarshalInterface; internal IntPtr pfnUnmarshalInterface; internal IntPtr pfnReleaseMarshalData; internal IntPtr pfnDisconnectObject; } internal unsafe struct __IContextCallback { internal __vtbl_IContextCallback* vtbl; } internal struct __vtbl_IContextCallback { __vtbl_IUnknown parent; internal IntPtr pfnContextCallback; } internal struct ComCallData { internal uint dwDispid; internal uint dwReserved; internal IntPtr pUserDefined; } #pragma warning restore 649, 169 } }
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; /* * dk.brics.automaton * * Copyright (c) 2001-2009 Anders Moeller * 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ namespace Lucene.Net.Util.Automaton { /// <summary> /// <see cref="Automaton"/> transition. /// <para/> /// A transition, which belongs to a source state, consists of a Unicode /// codepoint interval and a destination state. /// <para/> /// @lucene.experimental /// </summary> public class Transition #if FEATURE_CLONEABLE : System.ICloneable #endif { /* * CLASS INVARIANT: min<=max */ internal readonly int min; internal readonly int max; internal readonly State to; /// <summary> /// Constructs a new singleton interval transition. /// </summary> /// <param name="c"> Transition codepoint. </param> /// <param name="to"> Destination state. </param> public Transition(int c, State to) { Debug.Assert(c >= 0); min = max = c; this.to = to; } /// <summary> /// Constructs a new transition. Both end points are included in the interval. /// </summary> /// <param name="min"> Transition interval minimum. </param> /// <param name="max"> Transition interval maximum. </param> /// <param name="to"> Destination state. </param> public Transition(int min, int max, State to) { Debug.Assert(min >= 0); Debug.Assert(max >= 0); if (max < min) { int t = max; max = min; min = t; } this.min = min; this.max = max; this.to = to; } /// <summary> /// Returns minimum of this transition interval. </summary> public virtual int Min { get { return min; } } /// <summary> /// Returns maximum of this transition interval. </summary> public virtual int Max { get { return max; } } /// <summary> /// Returns destination of this transition. </summary> public virtual State Dest { get { return to; } } /// <summary> /// Checks for equality. /// </summary> /// <param name="obj"> Object to compare with. </param> /// <returns> <c>true</c> if <paramref name="obj"/> is a transition with same character interval /// and destination state as this transition. </returns> public override bool Equals(object obj) { if (obj is Transition) { Transition t = (Transition)obj; return t.min == min && t.max == max && t.to == to; } else { return false; } } /// <summary> /// Returns hash code. The hash code is based on the character interval (not /// the destination state). /// </summary> /// <returns> Hash code. </returns> public override int GetHashCode() { return min * 2 + max * 3; } /// <summary> /// Clones this transition. /// </summary> /// <returns> Clone with same character interval and destination state. </returns> public virtual object Clone() { return (Transition)base.MemberwiseClone(); } internal static void AppendCharString(int c, StringBuilder b) { if (c >= 0x21 && c <= 0x7e && c != '\\' && c != '"') { b.AppendCodePoint(c); } else { b.Append("\\\\U"); string s = c.ToString("x"); if (c < 0x10) { b.Append("0000000").Append(s); } else if (c < 0x100) { b.Append("000000").Append(s); } else if (c < 0x1000) { b.Append("00000").Append(s); } else if (c < 0x10000) { b.Append("0000").Append(s); } else if (c < 0x100000) { b.Append("000").Append(s); } else if (c < 0x1000000) { b.Append("00").Append(s); } else if (c < 0x10000000) { b.Append("0").Append(s); } else { b.Append(s); } } } /// <summary> /// Returns a string describing this state. Normally invoked via /// <seealso cref="Automaton.ToString()"/>. /// </summary> public override string ToString() { StringBuilder b = new StringBuilder(); AppendCharString(min, b); if (min != max) { b.Append("-"); AppendCharString(max, b); } b.Append(" -> ").Append(to.number); return b.ToString(); } internal virtual void AppendDot(StringBuilder b) { b.Append(" -> ").Append(to.number).Append(" [label=\""); AppendCharString(min, b); if (min != max) { b.Append("-"); AppendCharString(max, b); } b.Append("\"]\n"); } private sealed class CompareByDestThenMinMaxSingle : IComparer<Transition> { public int Compare(Transition t1, Transition t2) { //if (t1.to != t2.to) if (!ReferenceEquals(t1.to, t2.to)) { if (t1.to.number < t2.to.number) { return -1; } else if (t1.to.number > t2.to.number) { return 1; } } if (t1.min < t2.min) { return -1; } if (t1.min > t2.min) { return 1; } if (t1.max > t2.max) { return -1; } if (t1.max < t2.max) { return 1; } return 0; } } // LUCENENET NOTE: Renamed to follow convention of static fields/constants public static readonly IComparer<Transition> COMPARE_BY_DEST_THEN_MIN_MAX = new CompareByDestThenMinMaxSingle(); private sealed class CompareByMinMaxThenDestSingle : IComparer<Transition> { public int Compare(Transition t1, Transition t2) { if (t1.min < t2.min) { return -1; } if (t1.min > t2.min) { return 1; } if (t1.max > t2.max) { return -1; } if (t1.max < t2.max) { return 1; } //if (t1.to != t2.to) if (!ReferenceEquals(t1.to, t2.to)) { if (t1.to.number < t2.to.number) { return -1; } if (t1.to.number > t2.to.number) { return 1; } } return 0; } } // LUCENENET NOTE: Renamed to follow convention of static fields/constants public static readonly IComparer<Transition> COMPARE_BY_MIN_MAX_THEN_DEST = new CompareByMinMaxThenDestSingle(); } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace CronNET { public interface ICronSchedule { bool isValid(string expression); bool isTime(DateTime date_time); } public class CronSchedule : ICronSchedule { #region Readonly Class Members readonly static Regex divided_regex = new Regex(@"(\*/\d+)"); readonly static Regex range_regex = new Regex(@"(\d+\-\d+)\/?(\d+)?"); readonly static Regex wild_regex = new Regex(@"(\*)"); readonly static Regex list_regex = new Regex(@"(((\d+,)*\d+)+)"); readonly static Regex validation_regex = new Regex(divided_regex + "|" + range_regex + "|" + wild_regex + "|" + list_regex); #endregion #region Private Instance Members private readonly string _expression; public List<int> minutes; public List<int> hours; public List<int> days_of_month; public List<int> months; public List<int> days_of_week; #endregion #region Public Constructors public CronSchedule() { } public CronSchedule(string expressions) { this._expression = expressions; generate(); } #endregion #region Public Methods private bool isValid() { return isValid(this._expression); } public bool isValid(string expression) { MatchCollection matches = validation_regex.Matches(expression); return matches.Count > 0;//== 5; } public bool isTime(DateTime date_time) { return minutes.Contains(date_time.Minute) && hours.Contains(date_time.Hour) && days_of_month.Contains(date_time.Day) && months.Contains(date_time.Month) && days_of_week.Contains((int)date_time.DayOfWeek); } private void generate() { if (!isValid()) return; MatchCollection matches = validation_regex.Matches(this._expression); generate_minutes(matches[0].ToString()); if (matches.Count > 1) generate_hours(matches[1].ToString()); else generate_hours("*"); if (matches.Count > 2) generate_days_of_month(matches[2].ToString()); else generate_days_of_month("*"); if (matches.Count > 3) generate_months(matches[3].ToString()); else generate_months("*"); if (matches.Count > 4) generate_days_of_weeks(matches[4].ToString()); else generate_days_of_weeks("*"); } private void generate_minutes(string match) { this.minutes = generate_values(match, 0, 60); } private void generate_hours(string match) { this.hours = generate_values(match, 0, 24); } private void generate_days_of_month(string match) { this.days_of_month = generate_values(match, 1, 32); } private void generate_months(string match) { this.months = generate_values(match, 1, 13); } private void generate_days_of_weeks(string match) { this.days_of_week = generate_values(match, 0, 7); } private List<int> generate_values(string configuration, int start, int max) { if (divided_regex.IsMatch(configuration)) return divided_array(configuration, start, max); if (range_regex.IsMatch(configuration)) return range_array(configuration); if (wild_regex.IsMatch(configuration)) return wild_array(configuration, start, max); if (list_regex.IsMatch(configuration)) return list_array(configuration); return new List<int>(); } private List<int> divided_array(string configuration, int start, int max) { if (!divided_regex.IsMatch(configuration)) return new List<int>(); List<int> ret = new List<int>(); string[] split = configuration.Split("/".ToCharArray()); int divisor = int.Parse(split[1]); for (int i = start; i < max; ++i) if (i % divisor == 0) ret.Add(i); return ret; } private List<int> range_array(string configuration) { if (!range_regex.IsMatch(configuration)) return new List<int>(); List<int> ret = new List<int>(); string[] split = configuration.Split("-".ToCharArray()); int start = int.Parse(split[0]); int end = 0; if (split[1].Contains("/")) { split = split[1].Split("/".ToCharArray()); end = int.Parse(split[0]); int divisor = int.Parse(split[1]); for (int i = start; i < end; ++i) if (i % divisor == 0) ret.Add(i); return ret; } else end = int.Parse(split[1]); for (int i = start; i <= end; ++i) ret.Add(i); return ret; } private List<int> wild_array(string configuration, int start, int max) { if (!wild_regex.IsMatch(configuration)) return new List<int>(); List<int> ret = new List<int>(); for (int i = start; i < max; ++i) ret.Add(i); return ret; } private List<int> list_array(string configuration) { if (!list_regex.IsMatch(configuration)) return new List<int>(); List<int> ret = new List<int>(); string[] split = configuration.Split(",".ToCharArray()); foreach (string s in split) ret.Add(int.Parse(s)); return ret; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Implements the algorithm for distributing loop indices to parallel loop workers // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Threading; using System.Diagnostics.Contracts; #pragma warning disable 0420 namespace System.Threading.Tasks { /// <summary> /// Represents an index range /// </summary> internal struct IndexRange { // the From and To values for this range. These do not change. internal long m_nFromInclusive; internal long m_nToExclusive; // The shared index, stored as the offset from nFromInclusive. Using an offset rather than the actual // value saves us from overflows that can happen due to multiple workers racing to increment this. // All updates to this field need to be interlocked. internal volatile Shared<long> m_nSharedCurrentIndexOffset; // to be set to 1 by the worker that finishes this range. It's OK to do a non-interlocked write here. internal int m_bRangeFinished; } /// <summary> /// The RangeWorker struct wraps the state needed by a task that services the parallel loop /// </summary> internal struct RangeWorker { // reference to the IndexRange array allocated by the range manager internal readonly IndexRange[] m_indexRanges; // index of the current index range that this worker is grabbing chunks from internal int m_nCurrentIndexRange; // the step for this loop. Duplicated here for quick access (rather than jumping to rangemanager) internal long m_nStep; // increment value is the current amount that this worker will use // to increment the shared index of the range it's working on internal long m_nIncrementValue; // the increment value is doubled each time this worker finds work, and is capped at this value internal readonly long m_nMaxIncrementValue; /// <summary> /// Initializes a RangeWorker struct /// </summary> internal RangeWorker(IndexRange[] ranges, int nInitialRange, long nStep) { m_indexRanges = ranges; m_nCurrentIndexRange = nInitialRange; m_nStep = nStep; m_nIncrementValue = nStep; m_nMaxIncrementValue = Parallel.DEFAULT_LOOP_STRIDE * nStep; } /// <summary> /// Implements the core work search algorithm that will be used for this range worker. /// </summary> /// /// Usage pattern is: /// 1) the thread associated with this rangeworker calls FindNewWork /// 2) if we return true, the worker uses the nFromInclusiveLocal and nToExclusiveLocal values /// to execute the sequential loop /// 3) if we return false it means there is no more work left. It's time to quit. /// internal bool FindNewWork(out long nFromInclusiveLocal, out long nToExclusiveLocal) { // since we iterate over index ranges circularly, we will use the // count of visited ranges as our exit condition int numIndexRangesToVisit = m_indexRanges.Length; do { // local snap to save array access bounds checks in places where we only read fields IndexRange currentRange = m_indexRanges[m_nCurrentIndexRange]; if (currentRange.m_bRangeFinished == 0) { if (m_indexRanges[m_nCurrentIndexRange].m_nSharedCurrentIndexOffset == null) { Interlocked.CompareExchange(ref m_indexRanges[m_nCurrentIndexRange].m_nSharedCurrentIndexOffset, new Shared<long>(0), null); } // this access needs to be on the array slot long nMyOffset = Interlocked.Add(ref m_indexRanges[m_nCurrentIndexRange].m_nSharedCurrentIndexOffset.Value, m_nIncrementValue) - m_nIncrementValue; if (currentRange.m_nToExclusive - currentRange.m_nFromInclusive > nMyOffset) { // we found work nFromInclusiveLocal = currentRange.m_nFromInclusive + nMyOffset; nToExclusiveLocal = nFromInclusiveLocal + m_nIncrementValue; // Check for going past end of range, or wrapping if ( (nToExclusiveLocal > currentRange.m_nToExclusive) || (nToExclusiveLocal < currentRange.m_nFromInclusive) ) { nToExclusiveLocal = currentRange.m_nToExclusive; } // We will double our unit of increment until it reaches the maximum. if (m_nIncrementValue < m_nMaxIncrementValue) { m_nIncrementValue *= 2; if (m_nIncrementValue > m_nMaxIncrementValue) { m_nIncrementValue = m_nMaxIncrementValue; } } return true; } else { // this index range is completed, mark it so that others can skip it quickly Interlocked.Exchange(ref m_indexRanges[m_nCurrentIndexRange].m_bRangeFinished, 1); } } // move on to the next index range, in circular order. m_nCurrentIndexRange = (m_nCurrentIndexRange + 1) % m_indexRanges.Length; numIndexRangesToVisit--; } while (numIndexRangesToVisit > 0); // we've visited all index ranges possible => there's no work remaining nFromInclusiveLocal = 0; nToExclusiveLocal = 0; return false; } /// <summary> /// 32 bit integer version of FindNewWork. Assumes the ranges were initialized with 32 bit values. /// </summary> internal bool FindNewWork32(out int nFromInclusiveLocal32, out int nToExclusiveLocal32) { long nFromInclusiveLocal; long nToExclusiveLocal; bool bRetVal = FindNewWork(out nFromInclusiveLocal, out nToExclusiveLocal); Contract.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) && (nToExclusiveLocal <= Int32.MaxValue) && (nToExclusiveLocal >= Int32.MinValue)); // convert to 32 bit before returning nFromInclusiveLocal32 = (int)nFromInclusiveLocal; nToExclusiveLocal32 = (int)nToExclusiveLocal; return bRetVal; } } /// <summary> /// Represents the entire loop operation, keeping track of workers and ranges. /// </summary> /// /// The usage pattern is: /// 1) The Parallel loop entry function (ForWorker) creates an instance of this class /// 2) Every thread joining to service the parallel loop calls RegisterWorker to grab a /// RangeWorker struct to wrap the state it will need to find and execute work, /// and they keep interacting with that struct until the end of the loop internal class RangeManager { internal readonly IndexRange[] m_indexRanges; internal int m_nCurrentIndexRangeToAssign; internal long m_nStep; /// <summary> /// Initializes a RangeManager with the given loop parameters, and the desired number of outer ranges /// </summary> internal RangeManager(long nFromInclusive, long nToExclusive, long nStep, int nNumExpectedWorkers) { m_nCurrentIndexRangeToAssign = 0; m_nStep = nStep; // Our signed math breaks down w/ nNumExpectedWorkers == 1. So change it to 2. if (nNumExpectedWorkers == 1) nNumExpectedWorkers = 2; // // calculate the size of each index range // ulong uSpan = (ulong)(nToExclusive - nFromInclusive); ulong uRangeSize = uSpan / (ulong) nNumExpectedWorkers; // rough estimate first uRangeSize -= uRangeSize % (ulong) nStep; // snap to multiples of nStep // otherwise index range transitions will derail us from nStep if (uRangeSize == 0) { uRangeSize = (ulong) nStep; } // // find the actual number of index ranges we will need // Contract.Assert((uSpan / uRangeSize) < Int32.MaxValue); int nNumRanges = (int)(uSpan / uRangeSize); if (uSpan % uRangeSize != 0) { nNumRanges++; } // Convert to signed so the rest of the logic works. // Should be fine so long as uRangeSize < Int64.MaxValue, which we guaranteed by setting #workers >= 2. long nRangeSize = (long)uRangeSize; // allocate the array of index ranges m_indexRanges = new IndexRange[nNumRanges]; long nCurrentIndex = nFromInclusive; for (int i = 0; i < nNumRanges; i++) { // the fromInclusive of the new index range is always on nCurrentIndex m_indexRanges[i].m_nFromInclusive = nCurrentIndex; m_indexRanges[i].m_nSharedCurrentIndexOffset = null; m_indexRanges[i].m_bRangeFinished = 0; // now increment it to find the toExclusive value for our range nCurrentIndex += nRangeSize; // detect integer overflow or range overage and snap to nToExclusive if (nCurrentIndex < nCurrentIndex - nRangeSize || nCurrentIndex > nToExclusive) { // this should only happen at the last index Contract.Assert(i == nNumRanges - 1); nCurrentIndex = nToExclusive; } // now that the end point of the new range is calculated, assign it. m_indexRanges[i].m_nToExclusive = nCurrentIndex; } } /// <summary> /// The function that needs to be called by each new worker thread servicing the parallel loop /// in order to get a RangeWorker struct that wraps the state for finding and executing indices /// </summary> internal RangeWorker RegisterNewWorker() { Contract.Assert(m_indexRanges != null && m_indexRanges.Length != 0); int nInitialRange = (Interlocked.Increment(ref m_nCurrentIndexRangeToAssign) - 1) % m_indexRanges.Length; return new RangeWorker(m_indexRanges, nInitialRange, m_nStep); } } } #pragma warning restore 0420
// 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.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; using Xunit.Sdk; namespace System.Diagnostics { /// <summary>Base class used for all tests that need to spawn a remote process.</summary> public abstract partial class RemoteExecutorTestBase : FileCleanupTestBase { /// <summary>A timeout (milliseconds) after which a wait on a remote operation should be considered a failure.</summary> public const int FailWaitTimeoutMilliseconds = 60 * 1000; /// <summary>The exit code returned when the test process exits successfully.</summary> public const int SuccessExitCode = 42; /// <summary>The name of the test console app.</summary> protected static readonly string TestConsoleApp = "RemoteExecutorConsoleApp.exe"; /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Action method, RemoteInvokeOptions options = null) { // There's no exit code to check options = options ?? new RemoteInvokeOptions(); options.CheckExitCode = false; return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<int> method, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<Task<int>> method, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, Task<int>> method, string arg, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, int> method, string arg, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, int> method, string arg1, string arg2, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, int> method, string arg1, string arg2, string arg3, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="arg4">The fourth argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, string, int> method, string arg1, string arg2, string arg3, string arg4, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="arg4">The fourth argument to pass to the method.</param> /// <param name="arg5">The fifth argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, string, string, int> method, string arg1, string arg2, string arg3, string arg4, string arg5, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4, arg5 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments without performing any modifications to the arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="args">The arguments to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvokeRaw(Delegate method, string unparsedArg, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { unparsedArg }, options, pasteArguments: false); } private static MethodInfo GetMethodInfo(Delegate d) { // RemoteInvoke doesn't support marshaling state on classes associated with // the delegate supplied (often a display class of a lambda). If such fields // are used, odd errors result, e.g. NullReferenceExceptions during the remote // execution. Try to ward off the common cases by proactively failing early // if it looks like such fields are needed. if (d.Target != null) { // The only fields on the type should be compiler-defined (any fields of the compiler's own // making generally include '<' and '>', as those are invalid in C# source). Note that this logic // may need to be revised in the future as the compiler changes, as this relies on the specifics of // actually how the compiler handles lifted fields for lambdas. Type targetType = d.Target.GetType(); Assert.All( targetType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), fi => Assert.True(fi.Name.IndexOf('<') != -1, $"Field marshaling is not supported by {nameof(RemoteInvoke)}: {fi.Name}")); } return d.GetMethodInfo(); } /// <summary>A cleanup handle to the Process created for the remote invocation.</summary> public sealed class RemoteInvokeHandle : IDisposable { public RemoteInvokeHandle(Process process, RemoteInvokeOptions options) { Process = process; Options = options; } public Process Process { get; private set; } public RemoteInvokeOptions Options { get; private set; } public void Dispose() { if (Process != null) { // A bit unorthodox to do throwing operations in a Dispose, but by doing it here we avoid // needing to do this in every derived test and keep each test much simpler. try { Assert.True(Process.WaitForExit(Options.TimeOut), $"Timed out after {Options.TimeOut}ms waiting for remote process {Process.Id}"); if (File.Exists(Options.ExceptionFile)) { throw new RemoteExecutionException(File.ReadAllText(Options.ExceptionFile)); } if (Options.CheckExitCode) { int expected = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Options.ExpectedExitCode : unchecked((sbyte)Options.ExpectedExitCode); int actual = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Process.ExitCode : unchecked((sbyte)Process.ExitCode); Assert.True(expected == actual, $"Exit code was {Process.ExitCode} but it should have been {Options.ExpectedExitCode}"); } } finally { if (File.Exists(Options.ExceptionFile)) { File.Delete(Options.ExceptionFile); } // Cleanup try { Process.Kill(); } catch { } // ignore all cleanup errors Process.Dispose(); Process = null; } } } private sealed class RemoteExecutionException : XunitException { internal RemoteExecutionException(string stackTrace) : base("Remote process failed with an unhandled exception.", stackTrace) { } } } } /// <summary>Options used with RemoteInvoke.</summary> public sealed class RemoteInvokeOptions { public bool Start { get; set; } = true; public ProcessStartInfo StartInfo { get; set; } = new ProcessStartInfo(); public bool EnableProfiling { get; set; } = true; public bool CheckExitCode { get; set; } = true; public int TimeOut {get; set; } = RemoteExecutorTestBase.FailWaitTimeoutMilliseconds; public int ExpectedExitCode { get; set; } = RemoteExecutorTestBase.SuccessExitCode; public string ExceptionFile { get; } = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); } }
using System; using System.Collections.Generic; using GLTF.Extensions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace GLTF.Schema { public class GLTFProperty { private static Dictionary<string, ExtensionFactory> _extensionRegistry = new Dictionary<string, ExtensionFactory>() { { ExtTextureTransformExtensionFactory.EXTENSION_NAME, new ExtTextureTransformExtensionFactory() }, { KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME, new KHR_materials_pbrSpecularGlossinessExtensionFactory() }, { MSFT_LODExtensionFactory.EXTENSION_NAME, new MSFT_LODExtensionFactory() } }; private static DefaultExtensionFactory _defaultExtensionFactory = new DefaultExtensionFactory(); public static bool IsExtensionRegistered(string extensionName) { lock (_extensionRegistry) { return _extensionRegistry.ContainsKey(extensionName); } } public static void RegisterExtension(ExtensionFactory extensionFactory) { lock (_extensionRegistry) { _extensionRegistry[extensionFactory.ExtensionName] = extensionFactory; } } public static ExtensionFactory TryGetExtension(string extensionName) { lock (_extensionRegistry) { ExtensionFactory result; if (_extensionRegistry.TryGetValue(extensionName, out result)) { return result; } return null; } } public static bool TryRegisterExtension(ExtensionFactory extensionFactory) { lock (_extensionRegistry) { if (_extensionRegistry.ContainsKey(extensionFactory.ExtensionName)) { return false; } _extensionRegistry.Add(extensionFactory.ExtensionName, extensionFactory); return true; } } public Dictionary<string, IExtension> Extensions; public JToken Extras; public GLTFProperty() { } public GLTFProperty(GLTFProperty property, GLTFRoot gltfRoot = null) { if (property == null) return; if (property.Extensions != null) { Extensions = new Dictionary<string, IExtension>(property.Extensions.Count); foreach (KeyValuePair<string, IExtension> extensionKeyValuePair in property.Extensions) { Extensions.Add(extensionKeyValuePair.Key, extensionKeyValuePair.Value.Clone(gltfRoot)); } } if (property.Extras != null) { Extras = property.Extras.DeepClone(); } } public void DefaultPropertyDeserializer(GLTFRoot root, JsonReader reader) { switch (reader.Value.ToString()) { case "extensions": Extensions = DeserializeExtensions(root, reader); break; case "extras": // advance to property value reader.Read(); if (reader.TokenType != JsonToken.StartObject) throw new Exception(string.Format("extras must be an object at: {0}", reader.Path)); Extras = JToken.ReadFrom(reader); break; default: SkipValue(reader); break; } } private void SkipValue(JsonReader reader) { if (!reader.Read()) { throw new Exception("No value found."); } if (reader.TokenType == JsonToken.StartObject) { SkipObject(reader); } else if (reader.TokenType == JsonToken.StartArray) { SkipArray(reader); } } private void SkipObject(JsonReader reader) { while (reader.Read() && reader.TokenType != JsonToken.EndObject) { if (reader.TokenType == JsonToken.StartArray) { SkipArray(reader); } else if (reader.TokenType == JsonToken.StartObject) { SkipObject(reader); } } } private void SkipArray(JsonReader reader) { while (reader.Read() && reader.TokenType != JsonToken.EndArray) { if (reader.TokenType == JsonToken.StartArray) { SkipArray(reader); } else if (reader.TokenType == JsonToken.StartObject) { SkipObject(reader); } } } private Dictionary<string, IExtension> DeserializeExtensions(GLTFRoot root, JsonReader reader) { if (reader.Read() && reader.TokenType != JsonToken.StartObject) { throw new GLTFParseException("GLTF extensions must be an object"); } JObject extensions = (JObject)JToken.ReadFrom(reader); var extensionsCollection = new Dictionary<string, IExtension>(); foreach (JToken child in extensions.Children()) { if (child.Type != JTokenType.Property) { throw new GLTFParseException("Children token of extensions should be properties"); } JProperty childAsJProperty = (JProperty)child; string extensionName = childAsJProperty.Name; ExtensionFactory extensionFactory; lock (_extensionRegistry) { if (!_extensionRegistry.TryGetValue(extensionName, out extensionFactory)) { extensionFactory = _defaultExtensionFactory; } } extensionsCollection.Add(extensionName, extensionFactory.Deserialize(root, childAsJProperty)); } return extensionsCollection; } public virtual void Serialize(JsonWriter writer) { if (Extensions != null && Extensions.Count > 0) { writer.WritePropertyName("extensions"); writer.WriteStartObject(); foreach (var extension in Extensions) { JToken extensionToken = extension.Value.Serialize(); extensionToken.WriteTo(writer); } writer.WriteEndObject(); } if (Extras != null) { writer.WritePropertyName("extras"); Extras.WriteTo(writer); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private SyntaxToken _methodName; public static async Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult); return await codeGenerator.GenerateAsync(cancellationToken).ConfigureAwait(false); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult); } return Contract.FailWithReturn<CSharpCodeGenerator>("Unknown selection"); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) : base(insertionPoint, selectionResult, analyzerResult) { Contract.ThrowIfFalse(this.SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(this.MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)this.SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = this.InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(CancellationToken cancellationToken) { var result = CreateMethodBody(cancellationToken); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: SpecializedCollections.EmptyList<AttributeData>(), accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: this.AnalyzerResult.ReturnType, explicitInterfaceSymbol: null, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(cancellationToken), parameters: CreateMethodParameters(), statements: result.Data); return result.With( this.MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = this.GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( this.AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<IEnumerable<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = this.GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(this.CallSiteAnnotation, cancellationToken).ConfigureAwait(false); return SpecializedCollections.SingletonEnumerable(statement); } // regular case var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = SpecializedCollections.EmptyEnumerable<StatementSyntax>(); statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(statements, cancellationToken); statements = postProcessor.MergeDeclarationStatements(statements); statements = AddAssignmentStatementToCallSite(statements, cancellationToken); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements, cancellationToken); return statements; } private bool IsExpressionBodiedMember(SyntaxNode node) { return node is MemberDeclarationSyntax && ((MemberDeclarationSyntax)node).GetExpressionBody() != null; } private SimpleNameSyntax CreateMethodNameForInvocation() { return this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in this.AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(this.SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = this.CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = this.CSharpSelectionResult.ShouldPutAsyncModifier(); return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: !this.AnalyzerResult.UseInstanceMember); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private OperationStatus<List<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToList<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = this.CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } var block = statements.Single() as BlockSyntax; if (block != null) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private IEnumerable<StatementSyntax> CleanupCode(IEnumerable<StatementSyntax> statements) { var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); statements = postProcessor.RemoveRedundantBlock(statements); statements = postProcessor.RemoveDeclarationAssignmentPattern(statements); statements = postProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { var returnStatement = statements.Single() as ReturnStatementSyntax; if (returnStatement != null && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { var declStatement = statement as LocalDeclarationStatementSyntax; if (declStatement == null) { // found one return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private IEnumerable<StatementSyntax> MoveDeclarationOutFromMethodDefinition( IEnumerable<StatementSyntax> statements, CancellationToken cancellationToken) { var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( this.AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); foreach (var statement in statements) { var declarationStatement = statement as LocalDeclarationStatementSyntax; if (declarationStatement == null || declarationStatement.Declaration.IsDeconstructionDeclaration) { // if given statement is not decl statement, or if it is a deconstruction-declaration, do nothing. yield return statement; continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { SyntaxToken identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token yield return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { yield return SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, declarationStatement.RefKeyword, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); } // return any expression statement if there was any foreach (var expressionStatement in expressionStatements) { yield return expressionStatement; } } } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private static SyntaxToken GetIdentifierTokenAndTrivia(SyntaxToken identifier, TypeSyntax typeSyntax) { if (typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); var identifierTrailingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } if (typeSyntax.HasTrailingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetTrailingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifierTrailingTrivia = identifierTrailingTrivia.AddRange(identifier.TrailingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia) .WithTrailingTrivia(identifierTrailingTrivia); } return identifier; } private IEnumerable<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( IEnumerable<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = this.GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) { return SyntaxFactory.Identifier(name); } protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); foreach (var argument in this.AnalyzerResult.MethodParameters) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default(SyntaxToken) : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = this.CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); } protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, CancellationToken cancellationToken, ExpressionSyntax initialValue = null) { var type = variable.GetVariableType(this.SemanticDocument); var typeNode = type.GenerateTypeSyntax(); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<MethodDeclarationSyntax>(this.MethodDefinitionAnnotation).First(); var newMethodDefinition = methodDefinition.ReplaceToken( methodDefinition.Body.OpenBraceToken, methodDefinition.Body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.CarriageReturnLineFeed))); newDocument = await newDocument.WithSyntaxRootAsync(root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (this.AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(this.AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// Request for a linear evaluation of a list of targets in a project /// </summary> [DebuggerDisplay("BuildRequest (Project={ProjectFileName}, Targets={System.String.Join(\";\", TargetNames)}, NodeIndex={NodeIndex}, HandleId={HandleId})")] internal class BuildRequest { #region Constructors internal BuildRequest() { // used for serialization } /// <summary> /// Called by the Engine /// </summary> internal BuildRequest ( int handleId, string projectFileName, string[] targetNames, BuildPropertyGroup globalProperties, string toolsetVersion, int requestId, bool useResultsCache, bool unloadProjectsOnCompletion ) : this ( handleId, projectFileName, targetNames, (IDictionary)null, toolsetVersion, requestId, useResultsCache, unloadProjectsOnCompletion ) { // Create a hashtable out of the BuildPropertyGroup passed in. // This constructor is called only through the object model. if (globalProperties != null) { Hashtable globalPropertiesTable = new Hashtable(globalProperties.Count); foreach (BuildProperty property in globalProperties) { globalPropertiesTable.Add(property.Name, property.FinalValue); } this.globalPropertiesPassedByTask = globalPropertiesTable; this.globalProperties = globalProperties; } } /// <summary> /// Called by the TEM ("generated" request) /// </summary> internal BuildRequest ( int handleId, string projectFileName, string[] targetNames, IDictionary globalProperties, string toolsetVersion, int requestId, bool useResultsCache, bool unloadProjectsOnCompletion ) { this.handleId = handleId; this.nodeIndex = EngineCallback.invalidNode; this.projectFileName = projectFileName; this.targetNames = targetNames; this.parentEngine = null; this.outputsByTarget = null; this.resultByTarget = new Hashtable(StringComparer.OrdinalIgnoreCase); this.globalPropertiesPassedByTask = null; this.globalProperties = null; this.buildSucceeded = false; this.buildSettings = BuildSettings.None; this.projectToBuild = null; this.fireProjectStartedFinishedEvents = false; this.requestId = requestId; this.useResultsCache = useResultsCache; this.unloadProjectsOnCompletion = unloadProjectsOnCompletion; this.restoredFromCache = false; this.toolsetVersion = toolsetVersion; this.isExternalRequest = false; this.parentHandleId = EngineCallback.invalidEngineHandle; this.projectId = 0; this.startTime = 0; this.processingTotalTime = 0; this.taskTime = 0; this.toolsVersionPeekedFromProjectFile = false; if (globalProperties is Hashtable) { this.globalPropertiesPassedByTask = (Hashtable)globalProperties; } else if (globalProperties != null) { // We were passed an IDictionary that was not a Hashtable. It may // not be serializable, so convert it into a Hashtable, which is. this.globalPropertiesPassedByTask = new Hashtable(globalProperties.Count); foreach (DictionaryEntry newGlobalProperty in globalProperties) { this.globalPropertiesPassedByTask.Add(newGlobalProperty.Key, newGlobalProperty.Value); } } } #endregion #region Properties /// <summary> /// The engine is set inside the proxy prior to enqueing the request /// </summary> internal Engine ParentEngine { get { return this.parentEngine; } set { this.parentEngine = value; } } /// <summary> /// The outputs of the build request /// </summary> internal IDictionary OutputsByTarget { get { return this.outputsByTarget; } set { this.outputsByTarget = value; } } /// <summary> /// Build result per target /// </summary> internal Hashtable ResultByTarget { get { return this.resultByTarget; } } /// <summary> /// The result of the build request /// </summary> internal bool BuildSucceeded { get { return this.buildSucceeded; } set { this.buildSucceeded = value; } } /// <summary> /// The list of targets that need to be evaluated /// </summary> internal string[] TargetNames { get { return this.targetNames; } } /// <summary> /// The build settings /// </summary> internal BuildSettings BuildSettings { get { return this.buildSettings; } set { this.buildSettings = value; } } /// <summary> /// The project to be evaluated /// </summary> internal Project ProjectToBuild { get { return this.projectToBuild; } set { this.projectToBuild = value; } } internal bool FireProjectStartedFinishedEvents { get { return this.fireProjectStartedFinishedEvents; } set { this.fireProjectStartedFinishedEvents = value; } } internal int NodeIndex { get { return this.nodeIndex; } set { this.nodeIndex = value; } } /// <summary> /// Maps the BuildRequest to the TaskExecutionContext. /// If BuildRequest originated in the Engine itself in CreateLocalBuildRequest, HandleId is EngineCallback.invalidEngineHandle. /// </summary> internal int HandleId { get { return this.handleId; } set { this.handleId = value; } } internal int ParentHandleId { get { return parentHandleId; } set { parentHandleId = value; } } internal int ProjectId { get { return this.projectId; } set { this.projectId = value; } } internal int ParentRequestId { get { return this.parentRequestId; } set { this.parentRequestId = value; } } internal string ProjectFileName { get { return this.projectFileName; } set { this.projectFileName = value; } } internal BuildPropertyGroup GlobalProperties { get { return this.globalProperties; } set { this.globalProperties = value; } } internal IDictionary GlobalPropertiesPassedByTask { get { return this.globalPropertiesPassedByTask; } } internal bool BuildCompleted { get { return this.buildCompleted; } set { this.buildCompleted = value; } } internal int RequestId { get { return this.requestId; } set { this.requestId = value; } } /// <summary> /// Returns true if this BuildRequest came from a task, rather than /// the Host Engine itself. /// </summary> internal bool IsGeneratedRequest { get { return (handleId != EngineCallback.invalidEngineHandle); } } /// <summary> /// This is set to true if the build request was sent from the parent process /// </summary> internal bool IsExternalRequest { get { return isExternalRequest; } set { isExternalRequest = value; } } internal bool UnloadProjectsOnCompletion { get { return this.unloadProjectsOnCompletion; } } internal bool UseResultsCache { get { return this.useResultsCache; } set { this.useResultsCache = value; } } internal string DefaultTargets { get { return this.defaultTargets; } set { this.defaultTargets = value; } } internal string InitialTargets { get { return this.initialTargets; } set { this.initialTargets = value; } } internal BuildEventContext ParentBuildEventContext { get { return buildEventContext; } set { buildEventContext = value; } } internal string ToolsetVersion { get { return toolsetVersion; } set { this.toolsetVersion = value; } } internal InvalidProjectFileException BuildException { get { return buildException; } set { buildException = value; } } internal bool ToolsVersionPeekedFromProjectFile { get { return toolsVersionPeekedFromProjectFile; } set { toolsVersionPeekedFromProjectFile = value; } } /// <summary> /// True if the build results in this requests have been restored from the cache /// (in which case there's no point in caching them again) /// </summary> internal bool RestoredFromCache { get { return this.restoredFromCache; } } // Temp timing data properties internal long StartTime { get { return startTime; } set { startTime = value; } } internal long ProcessingStartTime { get { return processingStartTime; } set { processingStartTime = value; } } internal long ProcessingTotalTime { get { return processingTotalTime; } set { processingTotalTime = value; } } #endregion #region Methods /// <summary> /// Restore the default values which do not travel over the wire /// </summary> internal void RestoreNonSerializedDefaults() { this.outputsByTarget = new Hashtable(); this.resultByTarget = new Hashtable(StringComparer.OrdinalIgnoreCase); this.projectToBuild = null; this.buildSettings = BuildSettings.None; this.fireProjectStartedFinishedEvents = true; this.nodeIndex = EngineCallback.invalidNode; this.buildCompleted = false; this.buildSucceeded = false; this.defaultTargets = null; this.initialTargets = null; this.restoredFromCache = false; this.isExternalRequest = false; this.parentHandleId = EngineCallback.invalidEngineHandle; this.projectId = 0; this.startTime = 0; this.taskTime = 0; this.processingTotalTime = 0; } /// <summary> /// Initialize this build request with a cached build result /// </summary> /// <param name="cachedResult"></param> internal void InitializeFromCachedResult(BuildResult cachedResult) { this.OutputsByTarget = cachedResult.OutputsByTarget; this.BuildSucceeded = cachedResult.EvaluationResult; this.BuildCompleted = true; this.DefaultTargets = cachedResult.DefaultTargets; this.InitialTargets = cachedResult.InitialTargets; this.projectId = cachedResult.ProjectId; this.restoredFromCache = true; } internal BuildResult GetBuildResult() { // Calculate the time spent on this build request int totalTime = 0; int engineTime = 0; int taskTimeMs = 0; if ( startTime != 0 ) { TimeSpan totalTimeSpan = new TimeSpan(DateTime.Now.Ticks - startTime ); totalTime = (int)totalTimeSpan.TotalMilliseconds; } if (processingTotalTime != 0) { TimeSpan processingTimeSpan = new TimeSpan(processingTotalTime); engineTime = (int)processingTimeSpan.TotalMilliseconds; } if (taskTime != 0) { TimeSpan taskTimeSpan = new TimeSpan(taskTime); taskTimeMs = (int)taskTimeSpan.TotalMilliseconds; } return new BuildResult(outputsByTarget, resultByTarget, buildSucceeded, handleId, requestId, projectId, useResultsCache, defaultTargets, initialTargets, totalTime, engineTime, taskTimeMs); } /// <summary> /// Provides unique identifers for the caching system so we can retrieve this set of targets /// at a later time. This list should be either a null array or a list of strings which are not null. /// </summary> /// <returns></returns> internal string GetTargetNamesList() { string list = null; if (targetNames != null) { if (targetNames.Length == 1) { list = targetNames[0]; } else { StringBuilder targetsBuilder = new StringBuilder(); foreach (string target in targetNames) { //We are making sure that null targets are not concatonated because they do not count as a valid target ErrorUtilities.VerifyThrowArgumentNull(target, "target should not be null"); targetsBuilder.Append(target); targetsBuilder.Append(';'); } list = targetsBuilder.ToString(); } } return list; } /// <summary> /// This method is called after a task finishes execution in order to add the time spent executing /// the task to the total used by the build request /// </summary> /// <param name="executionTime">execution time of the last task</param> internal void AddTaskExecutionTime(long executionTime) { taskTime += executionTime; } #endregion #region Member data private int requestId; private int handleId; private string projectFileName; private string[] targetNames; private BuildPropertyGroup globalProperties; private string toolsetVersion; private bool unloadProjectsOnCompletion; private bool useResultsCache; // This is the event context of the task / host which made the buildRequest // the buildEventContext is used to determine who the parent project is private BuildEventContext buildEventContext; #region CustomSerializationToStream internal void WriteToStream(BinaryWriter writer) { writer.Write((Int32)requestId); writer.Write((Int32)handleId); #region ProjectFileName if (projectFileName == null) { writer.Write((byte)0); } else { writer.Write((byte)1); writer.Write(projectFileName); } #endregion #region TargetNames //Write Number of HashItems if (targetNames == null) { writer.Write((byte)0); } else { writer.Write((byte)1); writer.Write((Int32)targetNames.Length); foreach (string targetName in targetNames) { if (targetName == null) { writer.Write((byte)0); } else { writer.Write((byte)1); writer.Write(targetName); } } } #endregion #region GlobalProperties // Write the global properties if (globalProperties == null) { writer.Write((byte)0); } else { writer.Write((byte)1); globalProperties.WriteToStream(writer); } #endregion #region ToolsetVersion if (toolsetVersion == null) { writer.Write((byte)0); } else { writer.Write((byte)1); writer.Write(toolsetVersion); } #endregion writer.Write(unloadProjectsOnCompletion); writer.Write(useResultsCache); #region BuildEventContext if (buildEventContext == null) { writer.Write((byte)0); } else { writer.Write((byte)1); writer.Write((Int32)buildEventContext.NodeId); writer.Write((Int32)buildEventContext.ProjectContextId); writer.Write((Int32)buildEventContext.TargetId); writer.Write((Int32)buildEventContext.TaskId); } #endregion #region ToolsVersionPeekedFromProjectFile // We need to pass this over shared memory because where ever this project is being built needs to know // if the tools version was an override or was retreived from the project file if (!this.toolsVersionPeekedFromProjectFile) { writer.Write((byte)0); } else { writer.Write((byte)1); } #endregion } internal static BuildRequest CreateFromStream(BinaryReader reader) { BuildRequest request = new BuildRequest(); request.requestId = reader.ReadInt32(); request.handleId = reader.ReadInt32(); #region ProjectFileName if (reader.ReadByte() == 0) { request.projectFileName = null; } else { request.projectFileName = reader.ReadString(); } #endregion #region TargetNames if (reader.ReadByte() == 0) { request.targetNames = null; } else { int numberOfTargetNames = reader.ReadInt32(); request.targetNames = new string[numberOfTargetNames]; for (int i = 0; i < numberOfTargetNames; i++) { if (reader.ReadByte() == 0) { request.targetNames[i] = null; } else { request.targetNames[i] = reader.ReadString(); } } } #endregion #region GlobalProperties if (reader.ReadByte() == 0) { request.globalProperties = null; } else { request.globalProperties = new BuildPropertyGroup(); request.globalProperties.CreateFromStream(reader); } #endregion #region ToolsetVersion if (reader.ReadByte() == 0) { request.toolsetVersion = null; } else { request.toolsetVersion = reader.ReadString(); } #endregion request.unloadProjectsOnCompletion = reader.ReadBoolean(); request.useResultsCache = reader.ReadBoolean(); #region BuildEventContext if (reader.ReadByte() == 0) { request.buildEventContext = null; } else { // Re create event context int nodeId = reader.ReadInt32(); int projectContextId = reader.ReadInt32(); int targetId = reader.ReadInt32(); int taskId = reader.ReadInt32(); request.buildEventContext = new BuildEventContext(nodeId, targetId, projectContextId, taskId); } #endregion #region ToolsVersionPeekedFromProjectFile // We need to pass this over shared memory because where ever this project is being built needs to know // if the tools version was an override or was retreived from the project file if (reader.ReadByte() == 0) { request.toolsVersionPeekedFromProjectFile = false; } else { request.toolsVersionPeekedFromProjectFile = true; } #endregion return request; } #endregion private InvalidProjectFileException buildException; private string defaultTargets; private string initialTargets; private IDictionary outputsByTarget; private Hashtable resultByTarget; private bool buildCompleted; private bool buildSucceeded; private Hashtable globalPropertiesPassedByTask; private int nodeIndex; private Engine parentEngine; private Project projectToBuild; private bool fireProjectStartedFinishedEvents; private BuildSettings buildSettings; private bool restoredFromCache; private bool isExternalRequest; private int parentHandleId; private int parentRequestId; private int projectId; // Timing data - used to profile the build private long startTime; private long processingStartTime; private long processingTotalTime; private long taskTime; // We peeked at the tools version from the project file because the tools version was null private bool toolsVersionPeekedFromProjectFile; #endregion } }
namespace NEventStore { using System; using System.Collections.Generic; using System.Linq; using NEventStore.Logging; using NEventStore.Persistence; /// <summary> /// Tracks the heads of streams to reduce latency by avoiding roundtrips to storage. /// </summary> public class OptimisticPipelineHook : PipelineHookBase { private const int MaxStreamsToTrack = 100; private static readonly ILog Logger = LogFactory.BuildLogger(typeof (OptimisticPipelineHook)); private readonly Dictionary<HeadKey, ICommit> _heads = new Dictionary<HeadKey, ICommit>(); //TODO use concurrent collections private readonly LinkedList<HeadKey> _maxItemsToTrack = new LinkedList<HeadKey>(); private readonly int _maxStreamsToTrack; public OptimisticPipelineHook() : this(MaxStreamsToTrack) {} public OptimisticPipelineHook(int maxStreamsToTrack) { Logger.Debug(Resources.TrackingStreams, maxStreamsToTrack); _maxStreamsToTrack = maxStreamsToTrack; } public override void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public override ICommit Select(ICommit committed) { Track(committed); return committed; } public override bool PreCommit(CommitAttempt attempt) { Logger.Debug(Resources.OptimisticConcurrencyCheck, attempt.StreamId); ICommit head = GetStreamHead(GetHeadKey(attempt)); if (head == null) { return true; } if (head.CommitSequence >= attempt.CommitSequence) { throw new ConcurrencyException(); } if (head.StreamRevision >= attempt.StreamRevision) { throw new ConcurrencyException(); } if (head.CommitSequence < attempt.CommitSequence - 1) { throw new StorageException(); // beyond the end of the stream } if (head.StreamRevision < attempt.StreamRevision - attempt.Events.Count) { throw new StorageException(); // beyond the end of the stream } Logger.Debug(Resources.NoConflicts, attempt.StreamId); return true; } public override void PostCommit(ICommit committed) { Track(committed); } public override void OnPurge(string bucketId) { lock (_maxItemsToTrack) { if (bucketId == null) { _heads.Clear(); _maxItemsToTrack.Clear(); return; } HeadKey[] headsInBucket = _heads.Keys.Where(k => k.BucketId == bucketId).ToArray(); foreach (var head in headsInBucket) { RemoveHead(head); } } } public override void OnDeleteStream(string bucketId, string streamId) { lock (_maxItemsToTrack) { RemoveHead(new HeadKey(bucketId, streamId)); } } public override void OnDeleteStreams(string bucketId, List<string> streamIds) { lock (_maxItemsToTrack) { foreach (var streamId in streamIds) { RemoveHead(new HeadKey(bucketId, streamId)); } } } protected virtual void Dispose(bool disposing) { _heads.Clear(); _maxItemsToTrack.Clear(); } public virtual void Track(ICommit committed) { if (committed == null) { return; } lock (_maxItemsToTrack) { UpdateStreamHead(committed); TrackUpToCapacity(committed); } } private void UpdateStreamHead(ICommit committed) { HeadKey headKey = GetHeadKey(committed); ICommit head = GetStreamHead(headKey); if (AlreadyTracked(head)) { _maxItemsToTrack.Remove(headKey); } head = head ?? committed; head = head.StreamRevision > committed.StreamRevision ? head : committed; _heads[headKey] = head; } private void RemoveHead(HeadKey head) { _heads.Remove(head); LinkedListNode<HeadKey> node = _maxItemsToTrack.Find(head); // There should only be ever one or none if (node != null) { _maxItemsToTrack.Remove(node); } } private static bool AlreadyTracked(ICommit head) { return head != null; } private void TrackUpToCapacity(ICommit committed) { Logger.Verbose(Resources.TrackingCommit, committed.CommitSequence, committed.StreamId); _maxItemsToTrack.AddFirst(GetHeadKey(committed)); if (_maxItemsToTrack.Count <= _maxStreamsToTrack) { return; } HeadKey expired = _maxItemsToTrack.Last.Value; Logger.Verbose(Resources.NoLongerTrackingStream, expired); _heads.Remove(expired); _maxItemsToTrack.RemoveLast(); } public virtual bool Contains(ICommit attempt) { return GetStreamHead(GetHeadKey(attempt)) != null; } private ICommit GetStreamHead(HeadKey headKey) { lock (_maxItemsToTrack) { ICommit head; _heads.TryGetValue(headKey, out head); return head; } } private static HeadKey GetHeadKey(ICommit commit) { return new HeadKey(commit.BucketId, commit.StreamId); } private static HeadKey GetHeadKey(CommitAttempt commitAttempt) { return new HeadKey(commitAttempt.BucketId, commitAttempt.StreamId); } private sealed class HeadKey : IEquatable<HeadKey> { private readonly string _bucketId; private readonly string _streamId; public HeadKey(string bucketId, string streamId) { _bucketId = bucketId; _streamId = streamId; } public string BucketId { get { return _bucketId; } } public string StreamId { get { return _streamId; } } public bool Equals(HeadKey other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return String.Equals(_bucketId, other._bucketId) && String.Equals(_streamId, other._streamId); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj is HeadKey && Equals((HeadKey) obj); } public override int GetHashCode() { unchecked { return (_bucketId.GetHashCode()*397) ^ _streamId.GetHashCode(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetFusion.Bootstrap.Catalog; using NetFusion.Bootstrap.Exceptions; using NetFusion.Bootstrap.Logging; using NetFusion.Bootstrap.Plugins; using NetFusion.Common.Extensions.Collections; using NetFusion.Common.Extensions.Reflection; namespace NetFusion.Bootstrap.Container { /// <summary> /// Responsible for registering the ICompositeApp instance built from /// a set of plugins specified by the application host. /// </summary> internal class CompositeAppBuilder : ICompositeAppBuilder { // .NET Core Service Abstractions: public IServiceCollection ServiceCollection { get; } public IConfiguration Configuration { get; } // Plugins filtered by type: public IPlugin HostPlugin { get; private set; } public IPlugin[] AppPlugins { get; private set; } public IPlugin[] CorePlugins { get; private set; } public IPlugin[] AllPlugins { get; private set; } = Array.Empty<IPlugin>(); public IPluginModule[] AllModules => AllPlugins.SelectMany(p => p.Modules).ToArray(); // Logging Properties: public CompositeAppLogger CompositeLog { get; private set; } public CompositeAppBuilder(IServiceCollection serviceCollection, IConfiguration configuration) { ServiceCollection = serviceCollection ?? throw new ArgumentNullException(nameof(serviceCollection)); Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); } // =========================== [Plug Composition] ========================== // Provided a list of plugins, initializes all plugin module dependencies. internal void ComposePlugins(ITypeResolver typeResolver, IPlugin[] plugins) { if (typeResolver == null) throw new ArgumentNullException(nameof(typeResolver)); if (plugins == null) throw new ArgumentNullException(nameof(plugins)); InitializePlugins(plugins, typeResolver); SetServiceDependencies(); ComposePlugins(typeResolver); ConfigurePlugins(); } /// <summary> /// Returns types associated with a specific category of plugin. /// </summary> /// <param name="pluginTypes">The category of plugins to limit the return types.</param> /// <returns>List of limited plugin types or all plugin types if no category is specified.</returns> public IEnumerable<Type> GetPluginTypes(params PluginTypes[] pluginTypes) { if (pluginTypes == null) throw new ArgumentNullException(nameof(pluginTypes), "List of Plugin types cannot be null."); return pluginTypes.Length == 0 ? AllPlugins.SelectMany(p => p.Types) : AllPlugins.Where(p => pluginTypes.Contains(p.PluginType)).SelectMany(p => p.Types); } // --------------------------- Initialization ------------------------------- private void InitializePlugins(IPlugin[] plugins, ITypeResolver typeResolver) { SetPluginAssemblyInfo(plugins, typeResolver); // Before composing the plugin modules, verify the plugins from which // the composite application is being build. var validator = new CompositeAppValidation(plugins); validator.Validate(); CategorizePlugins(plugins); } // Delegates to the type resolver to populate information and the types associated with each plugin. // This decouples the container from runtime information and makes it easier to test. private static void SetPluginAssemblyInfo(IPlugin[] plugins, ITypeResolver typeResolver) { foreach (IPlugin plugin in plugins) { typeResolver.SetPluginMeta(plugin); } } private void CategorizePlugins(IEnumerable<IPlugin> plugins) { AllPlugins = plugins.ToArray(); HostPlugin = AllPlugins.FirstOrDefault(p => p.PluginType == PluginTypes.HostPlugin); AppPlugins = AllPlugins.Where(p => p.PluginType == PluginTypes.AppPlugin).ToArray(); CorePlugins = AllPlugins.Where(p => p.PluginType == PluginTypes.CorePlugin).ToArray(); } // --------------------------- Service Dependencies ------------------------------- private void SetServiceDependencies() { SetServiceDependencies(CorePlugins, PluginTypes.CorePlugin); SetServiceDependencies(AppPlugins, PluginTypes.AppPlugin, PluginTypes.CorePlugin); SetServiceDependencies(new []{ HostPlugin }, PluginTypes.HostPlugin, PluginTypes.AppPlugin, PluginTypes.CorePlugin); } // A plugin module can reference another module by having a property deriving from IPluginModuleService // Finds all IPluginModuleService derived properties of the referencing module and sets them to the // corresponding referenced module instance. private void SetServiceDependencies(IPlugin[] plugins, params PluginTypes[] pluginTypes) { foreach (IPlugin plugin in plugins) { foreach (IPluginModule module in plugin.Modules) { module.DependentServiceModules = GetDependentServiceProperties(module); foreach (PropertyInfo serviceProp in module.DependentServiceModules) { IPluginModuleService dependentService = GetModuleSupportingService(module, serviceProp.PropertyType, pluginTypes); serviceProp.SetValue(module, dependentService); } } } } private static PropertyInfo[] GetDependentServiceProperties(IPluginModule module) { const BindingFlags bindings = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; return module.GetType().GetProperties(bindings) .Where(p => p.PropertyType.IsDerivedFrom(typeof(IPluginModuleService)) && p.CanWrite) .ToArray(); } /// <summary> /// Given a IPluginModuleService type referenced by a module's property, searches for the module /// providing the implementation within all plugin types specified. /// /// For example, a core plugin should only be dependent on other core plugin modules. It would /// not make sense for a lower level core plugin to be dependent on a higher-level application /// specific plugin module. /// /// On the other hand, an application specific plugin module can be dependent on both core and /// other application plugin modules. This can be the case since application plugin modules /// can build on top of services provided by core plugins. /// </summary> /// <param name="serviceType">The dependent service module type referenced by a module</param> /// <param name="pluginTypes">The types of plugins (Core, App, Host) to search for the dependent module.</param> /// <returns>Reference to the dependent module.</returns> private IPluginModuleService GetModuleSupportingService(IPluginModule module, Type serviceType, PluginTypes[] pluginTypes) { var foundModules = AllPlugins.Where(p=> pluginTypes.Contains(p.PluginType)) .SelectMany(p => p.Modules) .Where(m => m.GetType().IsDerivedFrom(serviceType)).ToArray(); if (! foundModules.Any()) { throw new ContainerException( $"Plugin module implementing service type: {serviceType} not found for module: {module.GetType()}."); } if (foundModules.Length > 1) { throw new ContainerException( $"Multiple plugin modules implementing service type: {serviceType} found for module: {module.GetType()}."); } return (IPluginModuleService)foundModules.First(); } // --------------------------- Plugin Composition ------------------------------- // Allow each plug-in module to compose itself from concrete types, defined by other plugins, // based on abstract types defined by the plugin being composed. Think of this as a simplified // implementation of Microsoft's MEF. private void ComposePlugins(ITypeResolver typeResolver) { ComposeCorePlugins(typeResolver); ComposeAppPlugins(typeResolver); ComposeHostPlugin(typeResolver); } // Core plugins are composed from all other plugin types since they implement // reusable cross-cutting concerns. private void ComposeCorePlugins(ITypeResolver typeResolver) { var allPluginTypes = GetPluginTypes().ToArray(); foreach (var plugin in CorePlugins) { typeResolver.ComposePlugin(plugin, allPluginTypes); } } // Application plugins contain a specific application's implementations // and are composed only from other application specific plugins. private void ComposeAppPlugins(ITypeResolver typeResolver) { var allAppPluginTypes = GetPluginTypes( PluginTypes.AppPlugin, PluginTypes.HostPlugin).ToArray(); foreach (var plugin in AppPlugins) { typeResolver.ComposePlugin(plugin, allAppPluginTypes); } } private void ComposeHostPlugin(ITypeResolver typeResolver) { var hostPluginTypes = GetPluginTypes(PluginTypes.HostPlugin).ToArray(); typeResolver.ComposePlugin(HostPlugin, hostPluginTypes); } // --------------------------- Module Initialization / Configuration ------------------------------- // Before services are registered by modules, a two phase initialization is completed. // First all modules have the Initialize() method called. The Initialize() method is // where plugins should cache information that can be accessed by other modules. // After all modules are initialized, each module has the Configure() method called. // Code contained within a module's Configure() method can reference information // initialized by a dependent module. private void ConfigurePlugins() { CorePlugins.ForEach(InitializeModules); AppPlugins.ForEach(InitializeModules); InitializeModules(HostPlugin); CorePlugins.ForEach(ConfigureModules); AppPlugins.ForEach(ConfigureModules); ConfigureModules(HostPlugin); } private void InitializeModules(IPlugin plugin) { foreach (IPluginModule module in plugin.Modules) { module.Context = new ModuleContext(this, plugin); module.Initialize(); } } private void ConfigureModules(IPlugin plugin) { foreach (IPluginModule module in plugin.Modules) { module.Configure(); } } // =========================== [Module Service Registrations] ========================= // Allows each module to register services that can be injected into // other components. These services expose functionality implemented // by a plugin that can be injected into other components. internal void RegisterPluginServices(IServiceCollection services) { if (services == null) throw new ArgumentNullException(nameof(services)); // Plugin Service Registrations: RegisterCorePluginServices(services); RegisterAppPluginServices(services); RegisterHostPluginServices(services); // Additional Registrations: RegisterPluginModulesAsService(services); RegisterCompositeApplication(services); CreateCompositeLogger(services); } private void RegisterCorePluginServices(IServiceCollection services) { var allPluginTypes = GetPluginTypes().ToArray(); RegisterDefaultPluginServices(services, CorePlugins); ScanForServices(services, CorePlugins, allPluginTypes); RegisterPluginServices(services, CorePlugins); } private void RegisterAppPluginServices(IServiceCollection services) { var allAppPluginTypes = GetPluginTypes( PluginTypes.AppPlugin, PluginTypes.HostPlugin).ToArray(); RegisterDefaultPluginServices(services, AppPlugins); ScanForServices(services, AppPlugins, allAppPluginTypes); RegisterPluginServices(services, AppPlugins); } private void RegisterHostPluginServices(IServiceCollection services) { var hostPluginTypes = GetPluginTypes(PluginTypes.HostPlugin).ToArray(); RegisterDefaultPluginServices(services, new []{ HostPlugin }); ScanForServices(services, new []{ HostPlugin }, hostPluginTypes); RegisterPluginServices(services, new []{ HostPlugin }); } private static void RegisterDefaultPluginServices(IServiceCollection services, IPlugin[] plugins) { foreach (IPluginModule module in plugins.SelectMany(p => p.Modules)) { module.RegisterDefaultServices(services); } } private static void ScanForServices(IServiceCollection services, IPlugin[] plugins, Type[] pluginTypes) { var catalog = services.CreateCatalog(pluginTypes); foreach (var module in plugins.SelectMany(p => p.Modules)) { module.ScanForServices(catalog); } } private static void RegisterPluginServices(IServiceCollection services, IPlugin[] plugins) { foreach (IPluginModule module in plugins.SelectMany(p => p.Modules)) { module.RegisterServices(services); } } // Registers all modules as a service that implements one or more // interfaces deriving from IPluginModuleService. private void RegisterPluginModulesAsService(IServiceCollection services) { var modulesWithServices = AllModules.OfType<IPluginModuleService>(); foreach (IPluginModuleService moduleService in modulesWithServices) { var moduleServiceType = moduleService.GetType(); var moduleServiceInterfaces = moduleServiceType.GetInterfacesDerivedFrom<IPluginModuleService>(); services.AddSingleton(moduleServiceInterfaces, moduleService); } } // Registers the ICompositeApp component in the container representing the // application built from a set of plugins. private void RegisterCompositeApplication(IServiceCollection services) { services.AddSingleton<ICompositeAppBuilder>(this); services.AddSingleton<ICompositeApp, CompositeApp>(); } private void CreateCompositeLogger(IServiceCollection serviceCollection) { CompositeLog = new CompositeAppLogger(this, serviceCollection); } } }
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2016 Colin Green ([email protected]) * * SharpNEAT is free software; you can redistribute it and/or modify * it under the terms of The MIT License (MIT). * * You should have received a copy of the MIT License * along with SharpNEAT; if not, see https://opensource.org/licenses/MIT. */ using System; using SharpNeat.Core; using SharpNeat.Phenomes; namespace SharpNeat.Domains.BoxesVisualDiscrimination { /// <summary> /// Boxes Visual Discrimination Task. /// </summary> public class BoxesVisualDiscriminationEvaluator : IPhenomeEvaluator<IBlackBox> { /// <summary> /// Width and length of the visual field in the 'real' coordinate system that /// substrate nodes are located within (and therefore sensor and output pixels). /// </summary> public const double VisualFieldEdgeLength = 2.0; /// <summary> /// The root mean square distance (rmsd) between two random points in the unit square. /// An agent that attempts this problem domain by selecting random points will produce this value as a score /// when the size of the visual field is 1x1 (the unit square). For other visual field sizes we can obtain the /// random agent's score by simply multiplying this value by the edge length of the visual field (the score scales /// linearly with the edge length). /// /// This value can be derived starting with the function for the mean length of a line between two random points /// in the unit square, as given in: http://mathworld.wolfram.com/SquareLinePicking.html /// /// Alternatively the value can be experimentally determined/approximated. The value here was found computationally. /// </summary> const double MeanLineInSquareRootMeanSquareLength = 0.5773; /// <summary> /// Maximum fitness for this evaluator. Problem domain is considered perfectly 'solved' if this score is achieved. /// </summary> const double MaxFitness = 110.0; /// <summary> /// The resolution of the visual and output fields. /// </summary> readonly int _visualFieldResolution; /// <summary> /// The width and height of a visual field pixel in the real coordinate system. /// </summary> readonly double _visualPixelSize; /// <summary> /// The X and Y position of the visual field's origin pixel in the real coordinate system (the center position of the origin pixel). /// </summary> readonly double _visualOriginPixelXY; /// <summary> /// Number of evaluations. /// </summary> ulong _evalCount; /// <summary> /// Indicates if some stop condition has been achieved. /// </summary> bool _stopConditionSatisfied; #region Public Static Methods /// <summary> /// Apply the provided test case to the provided black box's inputs (visual input field). /// </summary> public static void ApplyVisualFieldToBlackBox(TestCaseField testCaseField, IBlackBox box, int visualFieldResolution, double visualOriginPixelXY, double visualPixelSize) { int inputIdx = 0; double yReal = visualOriginPixelXY; for(int y=0; y<visualFieldResolution; y++, yReal += visualPixelSize) { double xReal = visualOriginPixelXY; for(int x=0; x<visualFieldResolution; x++, xReal += visualPixelSize, inputIdx++) { box.InputSignalArray[inputIdx] = testCaseField.GetPixel(xReal, yReal); } } } /// <summary> /// Determine the coordinate of the pixel with the highest activation. /// </summary> public static IntPoint FindMaxActivationOutput(IBlackBox box, int visualFieldResolution, out double minActivation, out double maxActivation) { minActivation = maxActivation = box.OutputSignalArray[0]; int maxOutputIdx = 0; int len = box.OutputSignalArray.Length; for(int i=1; i<len; i++) { double val = box.OutputSignalArray[i]; if(val > maxActivation) { maxActivation = val; maxOutputIdx = i; } else if(val < minActivation) { minActivation = val; } } int y = maxOutputIdx / visualFieldResolution; int x = maxOutputIdx - (y * visualFieldResolution); return new IntPoint(x, y); } #endregion #region Constructor /// <summary> /// Construct with the specified sensor and output pixel array resolution. /// </summary> /// <param name="visualFieldResolution"></param> public BoxesVisualDiscriminationEvaluator(int visualFieldResolution) { _visualFieldResolution = visualFieldResolution; _visualPixelSize = VisualFieldEdgeLength / _visualFieldResolution; _visualOriginPixelXY = -1.0 + (_visualPixelSize/2.0); } #endregion #region IPhenomeEvaluator<IBlackBox> Members /// <summary> /// Gets the total number of evaluations that have been performed. /// </summary> public ulong EvaluationCount { get { return _evalCount; } } /// <summary> /// Gets a value indicating whether some goal fitness has been achieved and that /// the evolutionary algorithm/search should stop. This property's value can remain false /// to allow the algorithm to run indefinitely. /// </summary> public bool StopConditionSatisfied { get { return _stopConditionSatisfied; } } /// <summary> /// Evaluate the provided IBlackBox against the XOR problem domain and return its fitness score. /// /// Fitness value explanation. /// 1) Max distance from target position in each trial is sqrt(2)*VisualFieldEdgeLength (target in one corner and selected target in /// opposite corner). /// /// 2) An agents is scored by squaring the distance of its selected target from the actual target, squaring the value, /// taking the average over all test cases and then taking the square root. This is referred to as the root mean squared distance (RMSD) /// and is effectively an implementation of least squares (least squared error). The square root term converts values back into units /// of distance (rather than squared distance) /// /// 3) An agent selecting points at random will score VisualFieldEdgeLength * MeanLineInSquareRootMeanSquareLength. Any agent scoring /// this amount or less is assigned a fitness of zero. All other scores are scaled and translated into the range 0-100 where 0 is no better /// or worse than a random agent, and 100 is perfectly selecting the correct target for all test cases (distance of zero between target and /// selected target). /// /// 4) In addition to this the range of output values is scaled to 0-10 and added to the final score, this encourages solutions with a wide /// output range between the highest activation (the selected pixel) and the lowest activation (this encourages prominent/clear selection). /// /// An alternative scheme is fitness = 1/RMSD (separately handling the special case where RMSD==0). /// However, this gives a non-linear increase in fitness as RMSD decreases linearly, which in turns produces a 'spikier' fitness landscape /// which is more likely to cause genomes and species to get caught in a local maximum. /// </summary> public FitnessInfo Evaluate(IBlackBox box) { _evalCount++; // Accumulate square distance from each test case. double acc = 0.0; double activationRangeAcc = 0.0; TestCaseField testCaseField = new TestCaseField(); for(int i=0; i<3; i++) { for(int j=0; j<25; j++) { double activationRange; acc += RunTrial(box, testCaseField, i, out activationRange); activationRangeAcc += activationRange; } } // Calc root mean squared distance (RMSD) and calculate fitness based comparison to the random agent. const double threshold = VisualFieldEdgeLength * 0.5772; double rmsd = Math.Sqrt(acc / 75.0); double fitness; if(rmsd > threshold) { fitness = 0.0; } else { fitness = (((threshold-rmsd) * 100.0) / threshold) + (activationRangeAcc / 7.5); } // Set stop flag when max fitness is attained. if(!_stopConditionSatisfied && fitness == MaxFitness) { _stopConditionSatisfied = true; } return new FitnessInfo(fitness, rmsd); } /// <summary> /// Reset the internal state of the evaluation scheme if any exists. /// Note. The XOR problem domain has no internal state. This method does nothing. /// </summary> public void Reset() { } #endregion #region Private Methods /// <summary> /// Run a single trial /// 1) Generate random test case with the box orientation specified by largeBoxRelativePos. /// 2) Apply test case visual field to black box inputs. /// 3) Activate black box. /// 4) Determine black box output with highest output, this is the selected pixel. /// /// Returns square of distance between target pixel (center of large box) and pixel selected by the black box. /// </summary> private double RunTrial(IBlackBox box, TestCaseField testCaseField, int largeBoxRelativePos, out double activationRange) { // Generate random test case. Also gets the center position of the large box. IntPoint targetPos = testCaseField.InitTestCase(0); // Apply test case visual field to black box inputs. ApplyVisualFieldToBlackBox(testCaseField, box, _visualFieldResolution, _visualOriginPixelXY, _visualPixelSize); // Clear any pre-existing state and activate. box.ResetState(); box.Activate(); if(!box.IsStateValid) { // Any black box that gets itself into an invalid state is unlikely to be // any good, so lets just bail out here. activationRange = 0.0; return 0.0; } // Find output pixel with highest activation. double minActivation, maxActivation; IntPoint highestActivationPoint = FindMaxActivationOutput(box, _visualFieldResolution, out minActivation, out maxActivation); activationRange = Math.Max(0.0, maxActivation - minActivation); // Get the distance between the target and activated pixels, in the real coordinate space. // We actually want squared distance (not distance) thus we can skip taking the square root (expensive CPU operation). return CalcRealDistanceSquared(targetPos, highestActivationPoint); } private double CalcRealDistanceSquared(IntPoint a, IntPoint b) { // We can skip calculating abs(val) because we square the values. double xdelta = (a._x - b._x) * _visualPixelSize; double ydelta = (a._y - b._y) * _visualPixelSize; return xdelta*xdelta + ydelta*ydelta; } #endregion } }
using System.Diagnostics; using System; class PolynomialF { public static void Main(string[] args) { /* Size of the array of elements to compute the polynomial on */ const int arraySize = 1024*1024*8; /* Allocate arrays of inputs and outputs */ float[] x = new float[arraySize]; float[] pYeppp = new float[arraySize]; float[] pNaive = new float[arraySize]; /* Populate the array of inputs with random data */ Random rng = new Random(); for (int i = 0; i < x.Length; i++) { x[i] = unchecked((float)rng.NextDouble()); } /* Zero-initialize the output arrays */ Array.Clear(pYeppp, 0, pYeppp.Length); Array.Clear(pNaive, 0, pYeppp.Length); /* Retrieve the number of timer ticks per second */ ulong frequency = Yeppp.Library.GetTimerFrequency(); /* Retrieve the number of timer ticks before calling the C version of polynomial evaluation */ ulong startTimeNaive = Yeppp.Library.GetTimerTicks(); /* Evaluate polynomial using C# implementation */ EvaluatePolynomialNaive(x, pNaive); /* Retrieve the number of timer ticks after calling the C version of polynomial evaluation */ ulong endTimeNaive = Yeppp.Library.GetTimerTicks(); /* Retrieve the number of timer ticks before calling Yeppp! polynomial evaluation */ ulong startTimeYeppp = Yeppp.Library.GetTimerTicks(); /* Evaluate polynomial using Yeppp! */ Yeppp.Math.EvaluatePolynomial_V32fV32f_V32f(coefs, 0, x, 0, pYeppp, 0, coefs.Length, x.Length); /* Retrieve the number of timer ticks after calling Yeppp! polynomial evaluation */ ulong endTimeYeppp = Yeppp.Library.GetTimerTicks(); /* Compute time in seconds and performance in FLOPS */ double secsNaive = ((double)(endTimeNaive - startTimeNaive)) / ((double)(frequency)); double secsYeppp = ((double)(endTimeYeppp - startTimeYeppp)) / ((double)(frequency)); double flopsNaive = (double)(arraySize * (coefs.Length - 1) * 2) / secsNaive; double flopsYeppp = (double)(arraySize * (coefs.Length - 1) * 2) / secsYeppp; /* Report the timing and performance results */ Console.WriteLine("Naive implementation:"); Console.WriteLine("\tTime = {0:F2} secs", secsNaive); Console.WriteLine("\tPerformance = {0:F2} GFLOPS", flopsNaive * 1.0e-9); Console.WriteLine("Yeppp! implementation:"); Console.WriteLine("\tTime = {0:F2} secs", secsYeppp); Console.WriteLine("\tPerformance = {0:F2} GFLOPS", flopsYeppp * 1.0e-9); /* Make sure the result is correct. */ Console.WriteLine("Max difference: {0:F3}%", ComputeMaxDifference(pNaive, pYeppp) * 100.0f); } /* C# implementation with hard-coded coefficients. */ private static void EvaluatePolynomialNaive(float[] xArray, float[] yArray) { Debug.Assert(xArray.Length == yArray.Length); for (int index = 0; index < xArray.Length; index++) { float x = xArray[index]; float y = c0 + x * (c1 + x * (c2 + x * (c3 + x * (c4 + x * (c5 + x * (c6 + x * (c7 + x * (c8 + x * (c9 + x * (c10 + x * (c11 + x * (c12 + x * (c13 + x * (c14 + x * (c15 + x * (c16 + x * (c17 + x * (c18 + x * (c19 + x * (c20 + x * (c21 + x * (c22 + x * (c23 + x * (c24 + x * (c25 + x * (c26 + x * (c27 + x * (c28 + x * (c29 + x * (c30 + x * (c31 + x * (c32 + x * (c33 + x * (c34 + x * (c35 + x * (c36 + x * (c37 + x * (c38 + x * (c39 + x * (c40 + x * (c41 + x * (c42 + x * (c43 + x * (c44 + x * (c45 + x * (c46 + x * (c47 + x * (c48 + x * (c49 + x * (c50 + x * (c51 + x * (c52 + x * (c53 + x * (c54 + x * (c55 + x * (c56 + x * (c57 + x * (c58 + x * (c59 + x * (c60 + x * (c61 + x * (c62 + x * (c63 + x * (c64 + x * (c65 + x * (c66 + x * (c67 + x * (c68 + x * (c69 + x * (c70 + x * (c71 + x * (c72 + x * (c73 + x * (c74 + x * (c75 + x * (c76 + x * (c77 + x * (c78 + x * (c79 + x * (c80 + x * (c81 + x * (c82 + x * (c83 + x * (c84 + x * (c85 + x * (c86 + x * (c87 + x * (c88 + x * (c89 + x * (c90 + x * (c91 + x * (c92 + x * (c93 + x * (c94 + x * (c95 + x * (c96 + x * (c97 + x * (c98 + x * (c99 + x * c100) )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))); yArray[index] = y; } } /* This function computes the maximum relative error between two vectors. */ private static float ComputeMaxDifference(float[] xArray, float[] yArray) { Debug.Assert(xArray.Length == yArray.Length); float maxDiff = 0.0f; for (int index = 0; index < xArray.Length; index++) { if (xArray[index] == 0.0f) continue; float diff = Math.Abs(xArray[index] - yArray[index]) / Math.Abs(xArray[index]); maxDiff = Math.Max(maxDiff, diff); } return maxDiff; } /* Polynomial Coefficients 101 */ private const float c0 = 1.53270461724076346f; private const float c1 = 1.45339856462100293f; private const float c2 = 1.21078763026010761f; private const float c3 = 1.46952786401453397f; private const float c4 = 1.34249847863665017f; private const float c5 = 0.75093174077762164f; private const float c6 = 1.90239336671587562f; private const float c7 = 1.62162053962810579f; private const float c8 = 0.53312230473555923f; private const float c9 = 1.76588453111778762f; private const float c10 = 1.31215699612484679f; private const float c11 = 1.49636144227257237f; private const float c12 = 1.52170011054112963f; private const float c13 = 0.83637497322280110f; private const float c14 = 1.12764540941736043f; private const float c15 = 0.65513628703807597f; private const float c16 = 1.15879020877781906f; private const float c17 = 1.98262901973751791f; private const float c18 = 1.09134643523639479f; private const float c19 = 1.92898634047221235f; private const float c20 = 1.01233347751449659f; private const float c21 = 1.89462732589369078f; private const float c22 = 1.28216239080886344f; private const float c23 = 1.78448898277094016f; private const float c24 = 1.22382217182612910f; private const float c25 = 1.23434674193555734f; private const float c26 = 1.13914782832335501f; private const float c27 = 0.73506235075797319f; private const float c28 = 0.55461432517332724f; private const float c29 = 1.51704871121967963f; private const float c30 = 1.22430234239661516f; private const float c31 = 1.55001237689160722f; private const float c32 = 0.84197209952298114f; private const float c33 = 1.59396169927319749f; private const float c34 = 0.97067044414760438f; private const float c35 = 0.99001960195021281f; private const float c36 = 1.17887814292622884f; private const float c37 = 0.58955609453835851f; private const float c38 = 0.58145654861350322f; private const float c39 = 1.32447212043555583f; private const float c40 = 1.24673632882394241f; private const float c41 = 1.24571828921765111f; private const float c42 = 1.21901343493503215f; private const float c43 = 1.89453941213996638f; private const float c44 = 1.85561626872427416f; private const float c45 = 1.13302165522004133f; private const float c46 = 1.79145993815510725f; private const float c47 = 1.59227069037095317f; private const float c48 = 1.89104468672467114f; private const float c49 = 1.78733894997070918f; private const float c50 = 1.32648559107345081f; private const float c51 = 1.68531055586072865f; private const float c52 = 1.08980909640581993f; private const float c53 = 1.34308207822154847f; private const float c54 = 1.81689492849547059f; private const float c55 = 1.38582137073988747f; private const float c56 = 1.04974901183570510f; private const float c57 = 1.14348742300966456f; private const float c58 = 1.87597730040483323f; private const float c59 = 0.62131555899466420f; private const float c60 = 0.64710935668225787f; private const float c61 = 1.49846610600978751f; private const float c62 = 1.07834176789680957f; private const float c63 = 1.69130785175832059f; private const float c64 = 1.64547687732258793f; private const float c65 = 1.02441150427208083f; private const float c66 = 1.86129006037146541f; private const float c67 = 0.98309038830424073f; private const float c68 = 1.75444578237500969f; private const float c69 = 1.08698336765112349f; private const float c70 = 1.89455010772036759f; private const float c71 = 0.65812118412299539f; private const float c72 = 0.62102711487851459f; private const float c73 = 1.69991208083436747f; private const float c74 = 1.65467704495635767f; private const float c75 = 1.69599459626992174f; private const float c76 = 0.82365682103308750f; private const float c77 = 1.71353437063595036f; private const float c78 = 0.54992984722831769f; private const float c79 = 0.54717367088443119f; private const float c80 = 0.79915543248858154f; private const float c81 = 1.70160318364006257f; private const float c82 = 1.34441280175456970f; private const float c83 = 0.79789486341474966f; private const float c84 = 0.61517383020710754f; private const float c85 = 0.55177400048576055f; private const float c86 = 1.43229889543908696f; private const float c87 = 1.60658663666266949f; private const float c88 = 1.78861146369896090f; private const float c89 = 1.05843250742401821f; private const float c90 = 1.58481799048208832f; private const float c91 = 1.70954313374718085f; private const float c92 = 0.52590070195022226f; private const float c93 = 0.92705074709607885f; private const float c94 = 0.71442651832362455f; private const float c95 = 1.14752795948077643f; private const float c96 = 0.89860175106926404f; private const float c97 = 0.76771198245570573f; private const float c98 = 0.67059202034800746f; private const float c99 = 0.53785922275590729f; private const float c100 = 0.82098327929734880f; /* The same coefficients as an array. This array is used for a Yeppp! function call. */ private static readonly float[] coefs = { c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, c31, c32, c33, c34, c35, c36, c37, c38, c39, c40, c41, c42, c43, c44, c45, c46, c47, c48, c49, c50, c51, c52, c53, c54, c55, c56, c57, c58, c59, c60, c61, c62, c63, c64, c65, c66, c67, c68, c69, c70, c71, c72, c73, c74, c75, c76, c77, c78, c79, c80, c81, c82, c83, c84, c85, c86, c87, c88, c89, c90, c91, c92, c93, c94, c95, c96, c97, c98, c99, c100 }; }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace Mono.Cecil.Pdb { [ComImport, InterfaceType (ComInterfaceType.InterfaceIsIUnknown), Guid ("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")] interface IMetaDataEmit { void SetModuleProps (string szName); void Save (string szFile, uint dwSaveFlags); void SaveToStream (IntPtr pIStream, uint dwSaveFlags); uint GetSaveSize (uint fSave); uint DefineTypeDef (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements); uint DefineNestedType (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser); void SetHandler ([MarshalAs (UnmanagedType.IUnknown), In]object pUnk); uint DefineMethod (uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags); void DefineMethodImpl (uint td, uint tkBody, uint tkDecl); uint DefineTypeRefByName (uint tkResolutionScope, IntPtr szName); uint DefineImportType (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit); uint DefineMemberRef (uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob); uint DefineImportMember (IntPtr pAssemImport, IntPtr /* void* */ pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent); uint DefineEvent (uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr /* uint* */ rmdOtherMethods); void SetClassLayout (uint td, uint dwPackSize, IntPtr /*COR_FIELD_OFFSET**/ rFieldOffsets, uint ulClassSize); void DeleteClassLayout (uint td); void SetFieldMarshal (uint tk, IntPtr /* byte* */ pvNativeType, uint cbNativeType); void DeleteFieldMarshal (uint tk); uint DefinePermissionSet (uint tk, uint dwAction, IntPtr /* void* */ pvPermission, uint cbPermission); void SetRVA (uint md, uint ulRVA); uint GetTokenFromSig (IntPtr /* byte* */ pvSig, uint cbSig); uint DefineModuleRef (string szName); void SetParent (uint mr, uint tk); uint GetTokenFromTypeSpec (IntPtr /* byte* */ pvSig, uint cbSig); void SaveToMemory (IntPtr /* void* */ pbData, uint cbData); uint DefineUserString (string szString, uint cchString); void DeleteToken (uint tkObj); void SetMethodProps (uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags); void SetTypeDefProps (uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr /* uint* */ rtkImplements); void SetEventProps (uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr /* uint* */ rmdOtherMethods); uint SetPermissionSetProps (uint tk, uint dwAction, IntPtr /* void* */ pvPermission, uint cbPermission); void DefinePinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL); void SetPinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL); void DeletePinvokeMap (uint tk); uint DefineCustomAttribute (uint tkObj, uint tkType, IntPtr /* void* */ pCustomAttribute, uint cbCustomAttribute); void SetCustomAttributeValue (uint pcv, IntPtr /* void* */ pCustomAttribute, uint cbCustomAttribute); uint DefineField (uint td, string szName, uint dwFieldFlags, IntPtr /* byte* */ pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue); uint DefineProperty (uint td, string szProperty, uint dwPropFlags, IntPtr /* byte* */ pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr /* uint* */ rmdOtherMethods); uint DefineParam (uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue); void SetFieldProps (uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue); void SetPropertyProps (uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr /* uint* */ rmdOtherMethods); void SetParamProps (uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue); uint DefineSecurityAttributeSet (uint tkObj, IntPtr rSecAttrs, uint cSecAttrs); void ApplyEditAndContinue ([MarshalAs (UnmanagedType.IUnknown)]object pImport); uint TranslateSigWithScope (IntPtr pAssemImport, IntPtr /* void* */ pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr /* byte* */ pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr /* byte* */ pvTranslatedSig, uint cbTranslatedSigMax); void SetMethodImplFlags (uint md, uint dwImplFlags); void SetFieldRVA (uint fd, uint ulRVA); void Merge (IMetaDataImport pImport, IntPtr pHostMapToken, [MarshalAs (UnmanagedType.IUnknown)]object pHandler); void MergeEnd (); } [ComImport, InterfaceType (ComInterfaceType.InterfaceIsIUnknown), Guid ("7DAC8207-D3AE-4c75-9B67-92801A497D44")] interface IMetaDataImport { [PreserveSig] void CloseEnum (uint hEnum); uint CountEnum (uint hEnum); void ResetEnum (uint hEnum, uint ulPos); uint EnumTypeDefs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rTypeDefs, uint cMax); uint EnumInterfaceImpls (ref uint phEnum, uint td, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rImpls, uint cMax); uint EnumTypeRefs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rTypeRefs, uint cMax); uint FindTypeDefByName (string szTypeDef, uint tkEnclosingClass); Guid GetScopeProps (StringBuilder szName, uint cchName, out uint pchName); uint GetModuleFromScope (); uint GetTypeDefProps (uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags); uint GetInterfaceImplProps (uint iiImpl, out uint pClass); uint GetTypeRefProps (uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName); uint ResolveTypeRef (uint tr, [In] ref Guid riid, [MarshalAs (UnmanagedType.Interface)] out object ppIScope); uint EnumMembers (ref uint phEnum, uint cl, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rMembers, uint cMax); uint EnumMembersWithName (ref uint phEnum, uint cl, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMembers, uint cMax); uint EnumMethods (ref uint phEnum, uint cl, IntPtr /* uint* */ rMethods, uint cMax); uint EnumMethodsWithName (ref uint phEnum, uint cl, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMethods, uint cMax); uint EnumFields (ref uint phEnum, uint cl, IntPtr /* uint* */ rFields, uint cMax); uint EnumFieldsWithName (ref uint phEnum, uint cl, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rFields, uint cMax); uint EnumParams (ref uint phEnum, uint mb, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rParams, uint cMax); uint EnumMemberRefs (ref uint phEnum, uint tkParent, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rMemberRefs, uint cMax); uint EnumMethodImpls (ref uint phEnum, uint td, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMethodBody, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMethodDecl, uint cMax); uint EnumPermissionSets (ref uint phEnum, uint tk, uint dwActions, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rPermission, uint cMax); uint FindMember (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob); uint FindMethod (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob); uint FindField (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob); uint FindMemberRef (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob); uint GetMethodProps (uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA); uint GetMemberRefProps (uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr /* byte* */ ppvSigBlob); uint EnumProperties (ref uint phEnum, uint td, IntPtr /* uint* */ rProperties, uint cMax); uint EnumEvents (ref uint phEnum, uint td, IntPtr /* uint* */ rEvents, uint cMax); uint GetEventProps (uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 11)] uint [] rmdOtherMethod, uint cMax); uint EnumMethodSemantics (ref uint phEnum, uint mb, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rEventProp, uint cMax); uint GetMethodSemantics (uint mb, uint tkEventProp); uint GetClassLayout (uint td, out uint pdwPackSize, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] IntPtr /*COR_FIELD_OFFSET **/ rFieldOffset, uint cMax, out uint pcFieldOffset); uint GetFieldMarshal (uint tk, out IntPtr /* byte* */ ppvNativeType); uint GetRVA (uint tk, out uint pulCodeRVA); uint GetPermissionSetProps (uint pm, out uint pdwAction, out IntPtr /* void* */ ppvPermission); uint GetSigFromToken (uint mdSig, out IntPtr /* byte* */ ppvSig); uint GetModuleRefProps (uint mur, StringBuilder szName, uint cchName); uint EnumModuleRefs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rModuleRefs, uint cmax); uint GetTypeSpecFromToken (uint typespec, out IntPtr /* byte* */ ppvSig); uint GetNameFromToken (uint tk); uint EnumUnresolvedMethods (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rMethods, uint cMax); uint GetUserString (uint stk, StringBuilder szString, uint cchString); uint GetPinvokeMap (uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName); uint EnumSignatures (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rSignatures, uint cmax); uint EnumTypeSpecs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rTypeSpecs, uint cmax); uint EnumUserStrings (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rStrings, uint cmax); [PreserveSig] int GetParamForMethodIndex (uint md, uint ulParamSeq, out uint pParam); uint EnumCustomAttributes (ref uint phEnum, uint tk, uint tkType, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rCustomAttributes, uint cMax); uint GetCustomAttributeProps (uint cv, out uint ptkObj, out uint ptkType, out IntPtr /* void* */ ppBlob); uint FindTypeRef (uint tkResolutionScope, string szName); uint GetMemberProps (uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr /* byte* */ ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppValue); uint GetFieldProps (uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr /* byte* */ ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppValue); uint GetPropertyProps (uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr /* byte* */ ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 14)] uint [] rmdOtherMethod, uint cMax); uint GetParamProps (uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppValue); uint GetCustomAttributeByName (uint tkObj, string szName, out IntPtr /* void* */ ppData); [PreserveSig] [return: MarshalAs (UnmanagedType.Bool)] bool IsValidToken (uint tk); uint GetNestedClassProps (uint tdNestedClass); uint GetNativeCallConvFromSig (IntPtr /* void* */ pvSig, uint cbSig); int IsGlobal (uint pd); } class ModuleMetadata : IMetaDataEmit, IMetaDataImport { readonly ModuleDefinition module; Dictionary<uint, TypeDefinition> types; Dictionary<uint, MethodDefinition> methods; public ModuleMetadata (ModuleDefinition module) { this.module = module; } bool TryGetType (uint token, out TypeDefinition type) { if (types == null) InitializeMetadata (module); return types.TryGetValue (token, out type); } bool TryGetMethod (uint token, out MethodDefinition method) { if (methods == null) InitializeMetadata (module); return methods.TryGetValue (token, out method); } void InitializeMetadata (ModuleDefinition module) { types = new Dictionary<uint, TypeDefinition> (); methods = new Dictionary<uint, MethodDefinition> (); foreach (var type in module.GetTypes ()) { types.Add (type.MetadataToken.ToUInt32 (), type); InitializeMethods (type); } } void InitializeMethods (TypeDefinition type) { foreach (var method in type.Methods) methods.Add (method.MetadataToken.ToUInt32 (), method); } public void SetModuleProps (string szName) { throw new NotImplementedException (); } public void Save (string szFile, uint dwSaveFlags) { throw new NotImplementedException (); } public void SaveToStream (IntPtr pIStream, uint dwSaveFlags) { throw new NotImplementedException (); } public uint GetSaveSize (uint fSave) { throw new NotImplementedException (); } public uint DefineTypeDef (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements) { throw new NotImplementedException (); } public uint DefineNestedType (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser) { throw new NotImplementedException (); } public void SetHandler (object pUnk) { throw new NotImplementedException (); } public uint DefineMethod (uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags) { throw new NotImplementedException (); } public void DefineMethodImpl (uint td, uint tkBody, uint tkDecl) { throw new NotImplementedException (); } public uint DefineTypeRefByName (uint tkResolutionScope, IntPtr szName) { throw new NotImplementedException (); } public uint DefineImportType (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit) { throw new NotImplementedException (); } public uint DefineMemberRef (uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob) { throw new NotImplementedException (); } public uint DefineImportMember (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent) { throw new NotImplementedException (); } public uint DefineEvent (uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods) { throw new NotImplementedException (); } public void SetClassLayout (uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize) { throw new NotImplementedException (); } public void DeleteClassLayout (uint td) { throw new NotImplementedException (); } public void SetFieldMarshal (uint tk, IntPtr pvNativeType, uint cbNativeType) { throw new NotImplementedException (); } public void DeleteFieldMarshal (uint tk) { throw new NotImplementedException (); } public uint DefinePermissionSet (uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission) { throw new NotImplementedException (); } public void SetRVA (uint md, uint ulRVA) { throw new NotImplementedException (); } public uint GetTokenFromSig (IntPtr pvSig, uint cbSig) { throw new NotImplementedException (); } public uint DefineModuleRef (string szName) { throw new NotImplementedException (); } public void SetParent (uint mr, uint tk) { throw new NotImplementedException (); } public uint GetTokenFromTypeSpec (IntPtr pvSig, uint cbSig) { throw new NotImplementedException (); } public void SaveToMemory (IntPtr pbData, uint cbData) { throw new NotImplementedException (); } public uint DefineUserString (string szString, uint cchString) { throw new NotImplementedException (); } public void DeleteToken (uint tkObj) { throw new NotImplementedException (); } public void SetMethodProps (uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags) { throw new NotImplementedException (); } public void SetTypeDefProps (uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements) { throw new NotImplementedException (); } public void SetEventProps (uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods) { throw new NotImplementedException (); } public uint SetPermissionSetProps (uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission) { throw new NotImplementedException (); } public void DefinePinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL) { throw new NotImplementedException (); } public void SetPinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL) { throw new NotImplementedException (); } public void DeletePinvokeMap (uint tk) { throw new NotImplementedException (); } public uint DefineCustomAttribute (uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute) { throw new NotImplementedException (); } public void SetCustomAttributeValue (uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute) { throw new NotImplementedException (); } public uint DefineField (uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException (); } public uint DefineProperty (uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods) { throw new NotImplementedException (); } public uint DefineParam (uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException (); } public void SetFieldProps (uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException (); } public void SetPropertyProps (uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods) { throw new NotImplementedException (); } public void SetParamProps (uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException (); } public uint DefineSecurityAttributeSet (uint tkObj, IntPtr rSecAttrs, uint cSecAttrs) { throw new NotImplementedException (); } public void ApplyEditAndContinue (object pImport) { throw new NotImplementedException (); } public uint TranslateSigWithScope (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax) { throw new NotImplementedException (); } public void SetMethodImplFlags (uint md, uint dwImplFlags) { throw new NotImplementedException (); } public void SetFieldRVA (uint fd, uint ulRVA) { throw new NotImplementedException (); } public void Merge (IMetaDataImport pImport, IntPtr pHostMapToken, object pHandler) { throw new NotImplementedException (); } public void MergeEnd () { throw new NotImplementedException (); } public void CloseEnum (uint hEnum) { throw new NotImplementedException (); } public uint CountEnum (uint hEnum) { throw new NotImplementedException (); } public void ResetEnum (uint hEnum, uint ulPos) { throw new NotImplementedException (); } public uint EnumTypeDefs (ref uint phEnum, uint[] rTypeDefs, uint cMax) { throw new NotImplementedException (); } public uint EnumInterfaceImpls (ref uint phEnum, uint td, uint[] rImpls, uint cMax) { throw new NotImplementedException (); } public uint EnumTypeRefs (ref uint phEnum, uint[] rTypeRefs, uint cMax) { throw new NotImplementedException (); } public uint FindTypeDefByName (string szTypeDef, uint tkEnclosingClass) { throw new NotImplementedException (); } public Guid GetScopeProps (StringBuilder szName, uint cchName, out uint pchName) { throw new NotImplementedException (); } public uint GetModuleFromScope () { throw new NotImplementedException (); } public uint GetTypeDefProps (uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags) { TypeDefinition type; if (!TryGetType (td, out type)) { Marshal.WriteInt16 (szTypeDef, 0); pchTypeDef = 1; return 0; } WriteString (type.IsNested ? type.Name : type.FullName, szTypeDef, cchTypeDef, out pchTypeDef); WriteIntPtr (pdwTypeDefFlags, (uint) type.Attributes); return type.BaseType != null ? type.BaseType.MetadataToken.ToUInt32 () : 0; } static void WriteIntPtr (IntPtr ptr, uint value) { if (ptr == IntPtr.Zero) return; Marshal.WriteInt32 (ptr, (int) value); } static void WriteString (string str, IntPtr buffer, uint bufferSize, out uint chars) { var length = str.Length + 1 >= bufferSize ? bufferSize - 1 : (uint) str.Length; chars = length + 1; var offset = 0; for (int i = 0; i < length; i++) { Marshal.WriteInt16 (buffer, offset, str [i]); offset += 2; } Marshal.WriteInt16 (buffer, offset, 0); } public uint GetInterfaceImplProps (uint iiImpl, out uint pClass) { throw new NotImplementedException (); } public uint GetTypeRefProps (uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName) { throw new NotImplementedException (); } public uint ResolveTypeRef (uint tr, ref Guid riid, out object ppIScope) { throw new NotImplementedException (); } public uint EnumMembers (ref uint phEnum, uint cl, uint[] rMembers, uint cMax) { throw new NotImplementedException (); } public uint EnumMembersWithName (ref uint phEnum, uint cl, string szName, uint[] rMembers, uint cMax) { throw new NotImplementedException (); } public uint EnumMethods (ref uint phEnum, uint cl, IntPtr rMethods, uint cMax) { throw new NotImplementedException (); } public uint EnumMethodsWithName (ref uint phEnum, uint cl, string szName, uint[] rMethods, uint cMax) { throw new NotImplementedException (); } public uint EnumFields (ref uint phEnum, uint cl, IntPtr rFields, uint cMax) { throw new NotImplementedException (); } public uint EnumFieldsWithName (ref uint phEnum, uint cl, string szName, uint[] rFields, uint cMax) { throw new NotImplementedException (); } public uint EnumParams (ref uint phEnum, uint mb, uint[] rParams, uint cMax) { throw new NotImplementedException (); } public uint EnumMemberRefs (ref uint phEnum, uint tkParent, uint[] rMemberRefs, uint cMax) { throw new NotImplementedException (); } public uint EnumMethodImpls (ref uint phEnum, uint td, uint[] rMethodBody, uint[] rMethodDecl, uint cMax) { throw new NotImplementedException (); } public uint EnumPermissionSets (ref uint phEnum, uint tk, uint dwActions, uint[] rPermission, uint cMax) { throw new NotImplementedException (); } public uint FindMember (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException (); } public uint FindMethod (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException (); } public uint FindField (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException (); } public uint FindMemberRef (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException (); } public uint GetMethodProps (uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA) { MethodDefinition method; if (!TryGetMethod (mb, out method)) { Marshal.WriteInt16 (szMethod, 0); pchMethod = 1; pClass = 0; return 0; } pClass = method.DeclaringType.MetadataToken.ToUInt32 (); WriteString (method.Name, szMethod, cchMethod, out pchMethod); WriteIntPtr (pdwAttr, (uint) method.Attributes); WriteIntPtr (pulCodeRVA, (uint) method.RVA); return (uint) method.ImplAttributes; } public uint GetMemberRefProps (uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob) { throw new NotImplementedException (); } public uint EnumProperties (ref uint phEnum, uint td, IntPtr rProperties, uint cMax) { throw new NotImplementedException (); } public uint EnumEvents (ref uint phEnum, uint td, IntPtr rEvents, uint cMax) { throw new NotImplementedException (); } public uint GetEventProps (uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, uint[] rmdOtherMethod, uint cMax) { throw new NotImplementedException (); } public uint EnumMethodSemantics (ref uint phEnum, uint mb, uint[] rEventProp, uint cMax) { throw new NotImplementedException (); } public uint GetMethodSemantics (uint mb, uint tkEventProp) { throw new NotImplementedException (); } public uint GetClassLayout (uint td, out uint pdwPackSize, IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset) { throw new NotImplementedException (); } public uint GetFieldMarshal (uint tk, out IntPtr ppvNativeType) { throw new NotImplementedException (); } public uint GetRVA (uint tk, out uint pulCodeRVA) { throw new NotImplementedException (); } public uint GetPermissionSetProps (uint pm, out uint pdwAction, out IntPtr ppvPermission) { throw new NotImplementedException (); } public uint GetSigFromToken (uint mdSig, out IntPtr ppvSig) { throw new NotImplementedException (); } public uint GetModuleRefProps (uint mur, StringBuilder szName, uint cchName) { throw new NotImplementedException (); } public uint EnumModuleRefs (ref uint phEnum, uint[] rModuleRefs, uint cmax) { throw new NotImplementedException (); } public uint GetTypeSpecFromToken (uint typespec, out IntPtr ppvSig) { throw new NotImplementedException (); } public uint GetNameFromToken (uint tk) { throw new NotImplementedException (); } public uint EnumUnresolvedMethods (ref uint phEnum, uint[] rMethods, uint cMax) { throw new NotImplementedException (); } public uint GetUserString (uint stk, StringBuilder szString, uint cchString) { throw new NotImplementedException (); } public uint GetPinvokeMap (uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName) { throw new NotImplementedException (); } public uint EnumSignatures (ref uint phEnum, uint[] rSignatures, uint cmax) { throw new NotImplementedException (); } public uint EnumTypeSpecs (ref uint phEnum, uint[] rTypeSpecs, uint cmax) { throw new NotImplementedException (); } public uint EnumUserStrings (ref uint phEnum, uint[] rStrings, uint cmax) { throw new NotImplementedException (); } public int GetParamForMethodIndex (uint md, uint ulParamSeq, out uint pParam) { throw new NotImplementedException (); } public uint EnumCustomAttributes (ref uint phEnum, uint tk, uint tkType, uint[] rCustomAttributes, uint cMax) { throw new NotImplementedException (); } public uint GetCustomAttributeProps (uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob) { throw new NotImplementedException (); } public uint FindTypeRef (uint tkResolutionScope, string szName) { throw new NotImplementedException (); } public uint GetMemberProps (uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException (); } public uint GetFieldProps (uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException (); } public uint GetPropertyProps (uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, uint[] rmdOtherMethod, uint cMax) { throw new NotImplementedException (); } public uint GetParamProps (uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException (); } public uint GetCustomAttributeByName (uint tkObj, string szName, out IntPtr ppData) { throw new NotImplementedException (); } public bool IsValidToken (uint tk) { throw new NotImplementedException (); } public uint GetNestedClassProps (uint tdNestedClass) { TypeDefinition type; if (!TryGetType (tdNestedClass, out type)) return 0; return type.IsNested ? type.DeclaringType.MetadataToken.ToUInt32 () : 0; } public uint GetNativeCallConvFromSig (IntPtr pvSig, uint cbSig) { throw new NotImplementedException (); } public int IsGlobal (uint pd) { throw new NotImplementedException (); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Search; using Lucene.Net.Search.Function; using Lucene.Net.Spatial.Queries; using Lucene.Net.Spatial.Util; using Spatial4n.Core.Context; using Spatial4n.Core.Shapes; namespace Lucene.Net.Spatial.BBox { public class BBoxStrategy : SpatialStrategy { public static String SUFFIX_MINX = "__minX"; public static String SUFFIX_MAXX = "__maxX"; public static String SUFFIX_MINY = "__minY"; public static String SUFFIX_MAXY = "__maxY"; public static String SUFFIX_XDL = "__xdl"; /* * The Bounding Box gets stored as four fields for x/y min/max and a flag * that says if the box crosses the dateline (xdl). */ public readonly String field_bbox; public readonly String field_minX; public readonly String field_minY; public readonly String field_maxX; public readonly String field_maxY; public readonly String field_xdl; // crosses dateline public readonly double queryPower = 1.0; public readonly double targetPower = 1.0f; public int precisionStep = 8; // same as solr default public BBoxStrategy(SpatialContext ctx, String fieldNamePrefix) : base(ctx, fieldNamePrefix) { field_bbox = fieldNamePrefix; field_minX = fieldNamePrefix + SUFFIX_MINX; field_maxX = fieldNamePrefix + SUFFIX_MAXX; field_minY = fieldNamePrefix + SUFFIX_MINY; field_maxY = fieldNamePrefix + SUFFIX_MAXY; field_xdl = fieldNamePrefix + SUFFIX_XDL; } public void SetPrecisionStep(int p) { precisionStep = p; if (precisionStep <= 0 || precisionStep >= 64) precisionStep = int.MaxValue; } //--------------------------------- // Indexing //--------------------------------- public override AbstractField[] CreateIndexableFields(Shape shape) { var rect = shape as Rectangle; if (rect != null) return CreateIndexableFields(rect); throw new InvalidOperationException("Can only index Rectangle, not " + shape); } public AbstractField[] CreateIndexableFields(Rectangle bbox) { var fields = new AbstractField[5]; fields[0] = DoubleField(field_minX, bbox.GetMinX()); fields[1] = DoubleField(field_maxX, bbox.GetMaxX()); fields[2] = DoubleField(field_minY, bbox.GetMinY()); fields[3] = DoubleField(field_maxY, bbox.GetMaxY()); fields[4] = new Field(field_xdl, bbox.GetCrossesDateLine() ? "T" : "F", Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS) {OmitNorms = true, OmitTermFreqAndPositions = true}; return fields; } private AbstractField DoubleField(string field, double value) { var f = new NumericField(field, precisionStep, Field.Store.NO, true) {OmitNorms = true, OmitTermFreqAndPositions = true}; f.SetDoubleValue(value); return f; } public override ValueSource MakeDistanceValueSource(Point queryPoint) { return new BBoxSimilarityValueSource(this, new DistanceSimilarity(this.GetSpatialContext(), queryPoint)); } public ValueSource MakeBBoxAreaSimilarityValueSource(Rectangle queryBox) { return new BBoxSimilarityValueSource( this, new AreaSimilarity(queryBox, queryPower, targetPower)); } public override ConstantScoreQuery MakeQuery(SpatialArgs args) { return new ConstantScoreQuery(new QueryWrapperFilter(MakeSpatialQuery(args))); } public Query MakeQueryWithValueSource(SpatialArgs args, ValueSource valueSource) { var bq = new BooleanQuery(); var spatial = MakeFilter(args); bq.Add(new ConstantScoreQuery(spatial), Occur.MUST); // This part does the scoring Query spatialRankingQuery = new FunctionQuery(valueSource); bq.Add(spatialRankingQuery, Occur.MUST); return bq; } public override Filter MakeFilter(SpatialArgs args) { return new QueryWrapperFilter(MakeSpatialQuery(args)); } private Query MakeSpatialQuery(SpatialArgs args) { var bbox = args.Shape as Rectangle; if (bbox == null) throw new InvalidOperationException("Can only query by Rectangle, not " + args.Shape); Query spatial = null; // Useful for understanding Relations: // http://edndoc.esri.com/arcsde/9.1/general_topics/understand_spatial_relations.htm SpatialOperation op = args.Operation; if (op == SpatialOperation.BBoxIntersects) spatial = MakeIntersects(bbox); else if (op == SpatialOperation.BBoxWithin) spatial = MakeWithin(bbox); else if (op == SpatialOperation.Contains) spatial = MakeContains(bbox); else if (op == SpatialOperation.Intersects) spatial = MakeIntersects(bbox); else if (op == SpatialOperation.IsEqualTo) spatial = MakeEquals(bbox); else if (op == SpatialOperation.IsDisjointTo) spatial = MakeDisjoint(bbox); else if (op == SpatialOperation.IsWithin) spatial = MakeWithin(bbox); else if (op == SpatialOperation.Overlaps) spatial = MakeIntersects(bbox); else { throw new UnsupportedSpatialOperation(op); } return spatial; } //------------------------------------------------------------------------------- // //------------------------------------------------------------------------------- /// <summary> /// Constructs a query to retrieve documents that fully contain the input envelope. /// </summary> /// <param name="bbox"></param> /// <returns>The spatial query</returns> protected Query MakeContains(Rectangle bbox) { // general case // docMinX <= queryExtent.GetMinX() AND docMinY <= queryExtent.GetMinY() AND docMaxX >= queryExtent.GetMaxX() AND docMaxY >= queryExtent.GetMaxY() // Y conditions // docMinY <= queryExtent.GetMinY() AND docMaxY >= queryExtent.GetMaxY() Query qMinY = NumericRangeQuery.NewDoubleRange(field_minY, precisionStep, null, bbox.GetMinY(), false, true); Query qMaxY = NumericRangeQuery.NewDoubleRange(field_maxY, precisionStep, bbox.GetMaxY(), null, true, false); Query yConditions = this.MakeQuery(new Query[] { qMinY, qMaxY }, Occur.MUST); // X conditions Query xConditions = null; // queries that do not cross the date line if (!bbox.GetCrossesDateLine()) { // X Conditions for documents that do not cross the date line, // documents that contain the min X and max X of the query envelope, // docMinX <= queryExtent.GetMinX() AND docMaxX >= queryExtent.GetMaxX() Query qMinX = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, null, bbox.GetMinX(), false, true); Query qMaxX = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, bbox.GetMaxX(), null, true, false); Query qMinMax = this.MakeQuery(new Query[] { qMinX, qMaxX }, Occur.MUST); Query qNonXDL = this.MakeXDL(false, qMinMax); // X Conditions for documents that cross the date line, // the left portion of the document contains the min X of the query // OR the right portion of the document contains the max X of the query, // docMinXLeft <= queryExtent.GetMinX() OR docMaxXRight >= queryExtent.GetMaxX() Query qXDLLeft = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, null, bbox.GetMinX(), false, true); Query qXDLRight = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, bbox.GetMaxX(), null, true, false); Query qXDLLeftRight = this.MakeQuery(new Query[] { qXDLLeft, qXDLRight }, Occur.SHOULD); Query qXDL = this.MakeXDL(true, qXDLLeftRight); // apply the non-XDL and XDL conditions xConditions = this.MakeQuery(new Query[] { qNonXDL, qXDL }, Occur.SHOULD); // queries that cross the date line } else { // No need to search for documents that do not cross the date line // X Conditions for documents that cross the date line, // the left portion of the document contains the min X of the query // AND the right portion of the document contains the max X of the query, // docMinXLeft <= queryExtent.GetMinX() AND docMaxXRight >= queryExtent.GetMaxX() Query qXDLLeft = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, null, bbox.GetMinX(), false, true); Query qXDLRight = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, bbox.GetMaxX(), null, true, false); Query qXDLLeftRight = this.MakeQuery(new Query[] { qXDLLeft, qXDLRight }, Occur.MUST); xConditions = this.MakeXDL(true, qXDLLeftRight); } // both X and Y conditions must occur return this.MakeQuery(new Query[] { xConditions, yConditions }, Occur.MUST); } /// <summary> /// Constructs a query to retrieve documents that are disjoint to the input envelope. /// </summary> /// <param name="bbox"></param> /// <returns>the spatial query</returns> Query MakeDisjoint(Rectangle bbox) { // general case // docMinX > queryExtent.GetMaxX() OR docMaxX < queryExtent.GetMinX() OR docMinY > queryExtent.GetMaxY() OR docMaxY < queryExtent.GetMinY() // Y conditions // docMinY > queryExtent.GetMaxY() OR docMaxY < queryExtent.GetMinY() Query qMinY = NumericRangeQuery.NewDoubleRange(field_minY, precisionStep, bbox.GetMaxY(), null, false, false); Query qMaxY = NumericRangeQuery.NewDoubleRange(field_maxY, precisionStep, null, bbox.GetMinY(), false, false); Query yConditions = this.MakeQuery(new Query[] { qMinY, qMaxY }, Occur.SHOULD); // X conditions Query xConditions = null; // queries that do not cross the date line if (!bbox.GetCrossesDateLine()) { // X Conditions for documents that do not cross the date line, // docMinX > queryExtent.GetMaxX() OR docMaxX < queryExtent.GetMinX() Query qMinX = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, bbox.GetMaxX(), null, false, false); Query qMaxX = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, null, bbox.GetMinX(), false, false); Query qMinMax = this.MakeQuery(new Query[] { qMinX, qMaxX }, Occur.SHOULD); Query qNonXDL = this.MakeXDL(false, qMinMax); // X Conditions for documents that cross the date line, // both the left and right portions of the document must be disjoint to the query // (docMinXLeft > queryExtent.GetMaxX() OR docMaxXLeft < queryExtent.GetMinX()) AND // (docMinXRight > queryExtent.GetMaxX() OR docMaxXRight < queryExtent.GetMinX()) // where: docMaxXLeft = 180.0, docMinXRight = -180.0 // (docMaxXLeft < queryExtent.GetMinX()) equates to (180.0 < queryExtent.GetMinX()) and is ignored // (docMinXRight > queryExtent.GetMaxX()) equates to (-180.0 > queryExtent.GetMaxX()) and is ignored Query qMinXLeft = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, bbox.GetMaxX(), null, false, false); Query qMaxXRight = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, null, bbox.GetMinX(), false, false); Query qLeftRight = this.MakeQuery(new Query[] { qMinXLeft, qMaxXRight }, Occur.MUST); Query qXDL = this.MakeXDL(true, qLeftRight); // apply the non-XDL and XDL conditions xConditions = this.MakeQuery(new Query[] { qNonXDL, qXDL }, Occur.SHOULD); // queries that cross the date line } else { // X Conditions for documents that do not cross the date line, // the document must be disjoint to both the left and right query portions // (docMinX > queryExtent.GetMaxX()Left OR docMaxX < queryExtent.GetMinX()) AND (docMinX > queryExtent.GetMaxX() OR docMaxX < queryExtent.GetMinX()Left) // where: queryExtent.GetMaxX()Left = 180.0, queryExtent.GetMinX()Left = -180.0 Query qMinXLeft = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, 180.0, null, false, false); Query qMaxXLeft = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, null, bbox.GetMinX(), false, false); Query qMinXRight = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, bbox.GetMaxX(), null, false, false); Query qMaxXRight = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, null, -180.0, false, false); Query qLeft = this.MakeQuery(new Query[] { qMinXLeft, qMaxXLeft }, Occur.SHOULD); Query qRight = this.MakeQuery(new Query[] { qMinXRight, qMaxXRight }, Occur.SHOULD); Query qLeftRight = this.MakeQuery(new Query[] { qLeft, qRight }, Occur.MUST); // No need to search for documents that do not cross the date line xConditions = this.MakeXDL(false, qLeftRight); } // either X or Y conditions should occur return this.MakeQuery(new Query[] { xConditions, yConditions }, Occur.SHOULD); } /* * Constructs a query to retrieve documents that equal the input envelope. * * @return the spatial query */ public Query MakeEquals(Rectangle bbox) { // docMinX = queryExtent.GetMinX() AND docMinY = queryExtent.GetMinY() AND docMaxX = queryExtent.GetMaxX() AND docMaxY = queryExtent.GetMaxY() Query qMinX = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, bbox.GetMinX(), bbox.GetMinX(), true, true); Query qMinY = NumericRangeQuery.NewDoubleRange(field_minY, precisionStep, bbox.GetMinY(), bbox.GetMinY(), true, true); Query qMaxX = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, bbox.GetMaxX(), bbox.GetMaxX(), true, true); Query qMaxY = NumericRangeQuery.NewDoubleRange(field_maxY, precisionStep, bbox.GetMaxY(), bbox.GetMaxY(), true, true); var bq = new BooleanQuery { {qMinX, Occur.MUST}, {qMinY, Occur.MUST}, {qMaxX, Occur.MUST}, {qMaxY, Occur.MUST} }; return bq; } /// <summary> /// Constructs a query to retrieve documents that intersect the input envelope. /// </summary> /// <param name="bbox"></param> /// <returns>the spatial query</returns> Query MakeIntersects(Rectangle bbox) { // the original intersects query does not work for envelopes that cross the date line, // switch to a NOT Disjoint query // MUST_NOT causes a problem when it's the only clause type within a BooleanQuery, // to get round it we add all documents as a SHOULD // there must be an envelope, it must not be disjoint Query qDisjoint = MakeDisjoint(bbox); Query qIsNonXDL = this.MakeXDL(false); Query qIsXDL = this.MakeXDL(true); Query qHasEnv = this.MakeQuery(new Query[] { qIsNonXDL, qIsXDL }, Occur.SHOULD); var qNotDisjoint = new BooleanQuery {{qHasEnv, Occur.MUST}, {qDisjoint, Occur.MUST_NOT}}; //Query qDisjoint = makeDisjoint(); //BooleanQuery qNotDisjoint = new BooleanQuery(); //qNotDisjoint.add(new MatchAllDocsQuery(),BooleanClause.Occur.SHOULD); //qNotDisjoint.add(qDisjoint,BooleanClause.Occur.MUST_NOT); return qNotDisjoint; } /* * Makes a boolean query based upon a collection of queries and a logical operator. * * @param queries the query collection * @param occur the logical operator * @return the query */ BooleanQuery MakeQuery(Query[] queries, Occur occur) { var bq = new BooleanQuery(); foreach (Query query in queries) { bq.Add(query, occur); } return bq; } /* * Constructs a query to retrieve documents are fully within the input envelope. * * @return the spatial query */ Query MakeWithin(Rectangle bbox) { // general case // docMinX >= queryExtent.GetMinX() AND docMinY >= queryExtent.GetMinY() AND docMaxX <= queryExtent.GetMaxX() AND docMaxY <= queryExtent.GetMaxY() // Y conditions // docMinY >= queryExtent.GetMinY() AND docMaxY <= queryExtent.GetMaxY() Query qMinY = NumericRangeQuery.NewDoubleRange(field_minY, precisionStep, bbox.GetMinY(), null, true, false); Query qMaxY = NumericRangeQuery.NewDoubleRange(field_maxY, precisionStep, null, bbox.GetMaxY(), false, true); Query yConditions = this.MakeQuery(new Query[] { qMinY, qMaxY }, Occur.MUST); // X conditions Query xConditions = null; // X Conditions for documents that cross the date line, // the left portion of the document must be within the left portion of the query, // AND the right portion of the document must be within the right portion of the query // docMinXLeft >= queryExtent.GetMinX() AND docMaxXLeft <= 180.0 // AND docMinXRight >= -180.0 AND docMaxXRight <= queryExtent.GetMaxX() Query qXDLLeft = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, bbox.GetMinX(), null, true, false); Query qXDLRight = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, null, bbox.GetMaxX(), false, true); Query qXDLLeftRight = this.MakeQuery(new Query[] { qXDLLeft, qXDLRight }, Occur.MUST); Query qXDL = this.MakeXDL(true, qXDLLeftRight); // queries that do not cross the date line if (!bbox.GetCrossesDateLine()) { // X Conditions for documents that do not cross the date line, // docMinX >= queryExtent.GetMinX() AND docMaxX <= queryExtent.GetMaxX() Query qMinX = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, bbox.GetMinX(), null, true, false); Query qMaxX = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, null, bbox.GetMaxX(), false, true); Query qMinMax = this.MakeQuery(new Query[] { qMinX, qMaxX }, Occur.MUST); Query qNonXDL = this.MakeXDL(false, qMinMax); // apply the non-XDL or XDL X conditions if ((bbox.GetMinX() <= -180.0) && bbox.GetMaxX() >= 180.0) { xConditions = this.MakeQuery(new Query[] { qNonXDL, qXDL }, Occur.SHOULD); } else { xConditions = qNonXDL; } // queries that cross the date line } else { // X Conditions for documents that do not cross the date line // the document should be within the left portion of the query // docMinX >= queryExtent.GetMinX() AND docMaxX <= 180.0 Query qMinXLeft = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, bbox.GetMinX(), null, true, false); Query qMaxXLeft = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, null, 180.0, false, true); Query qLeft = this.MakeQuery(new Query[] { qMinXLeft, qMaxXLeft }, Occur.MUST); // the document should be within the right portion of the query // docMinX >= -180.0 AND docMaxX <= queryExtent.GetMaxX() Query qMinXRight = NumericRangeQuery.NewDoubleRange(field_minX, precisionStep, -180.0, null, true, false); Query qMaxXRight = NumericRangeQuery.NewDoubleRange(field_maxX, precisionStep, null, bbox.GetMaxX(), false, true); Query qRight = this.MakeQuery(new Query[] { qMinXRight, qMaxXRight }, Occur.MUST); // either left or right conditions should occur, // apply the left and right conditions to documents that do not cross the date line Query qLeftRight = this.MakeQuery(new Query[] { qLeft, qRight }, Occur.SHOULD); Query qNonXDL = this.MakeXDL(false, qLeftRight); // apply the non-XDL and XDL conditions xConditions = this.MakeQuery(new Query[] { qNonXDL, qXDL }, Occur.SHOULD); } // both X and Y conditions must occur return this.MakeQuery(new Query[] { xConditions, yConditions }, Occur.MUST); } /* * Constructs a query to retrieve documents that do or do not cross the date line. * * * @param crossedDateLine <code>true</true> for documents that cross the date line * @return the query */ public Query MakeXDL(bool crossedDateLine) { // The 'T' and 'F' values match solr fields return new TermQuery(new Term(field_xdl, crossedDateLine ? "T" : "F")); } /* * Constructs a query to retrieve documents that do or do not cross the date line * and match the supplied spatial query. * * @param crossedDateLine <code>true</true> for documents that cross the date line * @param query the spatial query * @return the query */ public Query MakeXDL(bool crossedDateLine, Query query) { var bq = new BooleanQuery {{this.MakeXDL(crossedDateLine), Occur.MUST}, {query, Occur.MUST}}; return bq; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; namespace Avalonia.Collections { /// <summary> /// A notifying dictionary. /// </summary> /// <typeparam name="TKey">The type of the dictionary key.</typeparam> /// <typeparam name="TValue">The type of the dictionary value.</typeparam> public class AvaloniaDictionary<TKey, TValue> : IDictionary<TKey, TValue>, INotifyCollectionChanged, INotifyPropertyChanged { private Dictionary<TKey, TValue> _inner; /// <summary> /// Initializes a new instance of the <see cref="AvaloniaDictionary{TKey, TValue}"/> class. /// </summary> public AvaloniaDictionary() { _inner = new Dictionary<TKey, TValue>(); } /// <summary> /// Occurs when the collection changes. /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged; /// <summary> /// Raised when a property on the collection changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <inheritdoc/> public int Count => _inner.Count; /// <inheritdoc/> public bool IsReadOnly => false; /// <inheritdoc/> public ICollection<TKey> Keys => _inner.Keys; /// <inheritdoc/> public ICollection<TValue> Values => _inner.Values; /// <summary> /// Gets or sets the named resource. /// </summary> /// <param name="key">The resource key.</param> /// <returns>The resource, or null if not found.</returns> public TValue this[TKey key] { get { return _inner[key]; } set { TValue old; bool replace = _inner.TryGetValue(key, out old); _inner[key] = value; if (replace) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs($"Item[{key}]")); if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, new KeyValuePair<TKey, TValue>(key, value), new KeyValuePair<TKey, TValue>(key, old)); CollectionChanged(this, e); } } else { NotifyAdd(key, value); } } } /// <inheritdoc/> public void Add(TKey key, TValue value) { _inner.Add(key, value); NotifyAdd(key, value); } /// <inheritdoc/> public void Clear() { var old = _inner; _inner = new Dictionary<TKey, TValue>(); if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Count")); PropertyChanged(this, new PropertyChangedEventArgs($"Item[]")); } if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, old.ToList(), -1); CollectionChanged(this, e); } } /// <inheritdoc/> public bool ContainsKey(TKey key) { return _inner.ContainsKey(key); } /// <inheritdoc/> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { ((IDictionary<TKey, TValue>)_inner).CopyTo(array, arrayIndex); } /// <inheritdoc/> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _inner.GetEnumerator(); } /// <inheritdoc/> public bool Remove(TKey key) { TValue value; if (_inner.TryGetValue(key, out value)) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Count")); PropertyChanged(this, new PropertyChangedEventArgs($"Item[{key}]")); } if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, new[] { new KeyValuePair<TKey, TValue>(key, value) }, -1); CollectionChanged(this, e); } return true; } else { return false; } } /// <inheritdoc/> public bool TryGetValue(TKey key, out TValue value) { return _inner.TryGetValue(key, out value); } /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() { return _inner.GetEnumerator(); } /// <inheritdoc/> void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } /// <inheritdoc/> bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return _inner.Contains(item); } /// <inheritdoc/> bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { return Remove(item.Key); } private void NotifyAdd(TKey key, TValue value) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Count")); PropertyChanged(this, new PropertyChangedEventArgs($"Item[{key}]")); } if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, new[] { new KeyValuePair<TKey, TValue>(key, value) }, -1); CollectionChanged(this, e); } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- using Microsoft.Azure.DocumentDBStudio.Helpers; using Microsoft.Azure.DocumentDBStudio.Providers; namespace Microsoft.Azure.DocumentDBStudio { using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Drawing; using System.Globalization; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading; using System.Windows.Forms; using Properties; using Documents; using Documents.Client; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public partial class MainForm : Form { private int defaultFontPoint = 9; private int fontScale = 100; private string loadingGifPath; private string prettyJSONTemplate; private string currentJson; private string currentText; private string homepage; Action<object, RequestOptions> currentOperationCallback; private RequestOptions requestOptions; CheckBox cbEnableScan; CheckBox cbEnableCrossPartitionQuery; private DocumentCollection newDocumentCollection; private OperationType operationType; private ResourceType resourceType; private OfferType offerType; public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(arg => CheckCurrentRelease()); Height = Screen.GetWorkingArea(this).Height * 3 / 4; Width = Screen.GetWorkingArea(this).Width / 2; Top = 0; Text = Constants.ApplicationName; homepage = EmbeddedResourceProvider.ReadEmbeddedResource("Microsoft.Azure.DocumentDBStudio.Resources.home.html"); homepage = homepage.Replace("&VERSION&", Constants.ProductVersion); var t = File.GetLastWriteTime(Assembly.GetExecutingAssembly().Location); homepage = homepage.Replace("&BUILDTIME&", t.ToString("f", CultureInfo.CurrentCulture)); cbUrl.Items.Add("about:home"); cbUrl.SelectedIndex = 0; cbUrl.KeyDown += cbUrl_KeyDown; btnBack.Enabled = false; splitContainerOuter.Panel1Collapsed = false; splitContainerInner.Panel1Collapsed = true; ButtomSplitContainer.Panel1Collapsed = true; KeyPreview = true; PreviewKeyDown += MainForm_PreviewKeyDown; webBrowserResponse.PreviewKeyDown += webBrowserResponse_PreviewKeyDown; webBrowserResponse.StatusTextChanged += webBrowserResponse_StatusTextChanged; webBrowserResponse.ScriptErrorsSuppressed = true; tabControl.SelectedTab = tabCrudContext; tabControl.TabPages.Remove(tabRequest); tabControl.TabPages.Remove(tabDocumentCollection); tabControl.TabPages.Remove(tabOffer); var imageList = BuildImageList(); treeView1.ImageList = imageList; InitTreeView(); btnHome_Click(null, null); splitContainerIntabPage.Panel1Collapsed = true; toolStripBtnExecute.Enabled = false; btnExecuteNext.Enabled = false; UnpackEmbeddedResources(); btnHeaders.Checked = false; cbRequestOptionsApply_CheckedChanged(null, null); cbIndexingPolicyDefault_CheckedChanged(null, null); cbEnableScan = new CheckBox { Text = "EnableScanInQuery", CheckState = CheckState.Indeterminate }; ToolStripControlHost host1 = new ToolStripControlHost(cbEnableScan); feedToolStrip.Items.Insert(3, host1); cbEnableCrossPartitionQuery = new CheckBox { Text = "EnableCrossPartitionQuery", CheckState = CheckState.Indeterminate }; ToolStripControlHost host2 = new ToolStripControlHost(cbEnableCrossPartitionQuery); feedToolStrip.Items.Insert(4, host2); lbIncludedPath.Items.Add(new IncludedPath() { Path = "/" }); offerType = OfferType.StandardSingle; tbThroughput.Text = "400"; tsbHideDocumentSystemProperties.Checked = Settings.Default.HideDocumentSystemProperties; SetDocumentSystemPropertiesTabText(); tsbViewType.Checked = Settings.Default.TextView; SetViewTypeTabText(); } private static ImageList BuildImageList() { var imageList = new ImageList(); imageList.Images.Add("Default", Resources.DocDBpng); imageList.Images.Add("Feed", Resources.Feedpng); imageList.Images.Add("Javascript", Resources.Javascriptpng); imageList.Images.Add("User", Resources.Userpng); imageList.Images.Add("Permission", Resources.Permissionpng); imageList.Images.Add("DatabaseAccount", Resources.DatabaseAccountpng); imageList.Images.Add("SystemFeed", Resources.SystemFeedpng); imageList.Images.Add("Attachment", Resources.Attachmentpng); imageList.Images.Add("Conflict", Resources.Conflictpng); imageList.Images.Add("Offer", Resources.Offerpng); return imageList; } private void UnpackEmbeddedResources() { if (!Directory.Exists(SystemInfoProvider.LocalApplicationDataPath)) { Directory.CreateDirectory(SystemInfoProvider.LocalApplicationDataPath); } loadingGifPath = CopyStreamToFile("loading.gif", "loading.gif"); CopyStreamToFile("prettyJSON.backbone-min.js", "backbone-min.js"); CopyStreamToFile("prettyJSON.jquery-1.11.1.min.js", "jquery-1.11.1.min.js"); CopyStreamToFile("prettyJSON.pretty-json.css", "pretty-json.css"); CopyStreamToFile("prettyJSON.pretty-json-min.js", "pretty-json-min.js"); CopyStreamToFile("prettyJSON.underscore-min.js", "underscore-min.js"); prettyJSONTemplate = EmbeddedResourceProvider.ReadEmbeddedResource("Microsoft.Azure.DocumentDBStudio.Resources.prettyJSON.PrettyPrintJSONTemplate.html"); } private string CopyStreamToFile(string resourceName, string fileName) { var fileLocation = Path.Combine(SystemInfoProvider.LocalApplicationDataPath, fileName); EmbeddedResourceProvider.CopyStreamToFile(resourceName, fileLocation); return fileLocation; } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); // ToolStrips don't appear to have a way to "spring" their items like status bars cbUrl.Width = tsAddress.Width - 40 - tsLabelUrl.Width - btnGo.Width; } void webBrowserResponse_StatusTextChanged(object sender, EventArgs e) { } void cbUrl_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { webBrowserResponse.Navigate(cbUrl.Text); e.Handled = true; } } void webBrowserResponse_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (webBrowserResponse.Focused) { HandlePreviewKeyDown(e.KeyCode, e.Modifiers); } } void MainForm_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (!webBrowserResponse.Focused && !cbUrl.Focused) { HandlePreviewKeyDown(e.KeyCode, e.Modifiers); } } bool HandlePreviewKeyDown(Keys key, Keys modifiers) { if (key == Keys.Back) { // Don't steal backspace from the URL combo box if (!cbUrl.Focused) { return true; } } else if (key == Keys.F5) { return true; } else if (key == Keys.Enter) { webBrowserResponse.Navigate(cbUrl.Text); return true; } else if (key == Keys.W && modifiers == Keys.Control) { // Exit the app on Ctrl + W like browser tabs Close(); return true; } else if (key == Keys.D && modifiers == Keys.Alt) { // Focus the URL in the address bar cbUrl.SelectAll(); cbUrl.Focus(); } return false; } private void tbCrudContext_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { switch (e.KeyCode) { case Keys.F5: { if (toolStripBtnExecute.Enabled) { toolStripBtnExecute_Click(null, null); } } break; case Keys.A: if (e.Control) { tbCrudContext.SelectAll(); } break; } } // private void DisplayResponseContent() { var workJson = DocumentHelper.RemoveInternalDocumentValues(currentJson); if (tsbViewType.Checked) { PrettyPrintJson(workJson, currentText, Settings.Default.ExpandPrettyPrintJson); } else { string htmlResponse = ""; if (!string.IsNullOrEmpty(workJson)) { htmlResponse = Helper.FormatTextAsHtml(workJson, false); } if (!string.IsNullOrEmpty(currentText)) { htmlResponse += "\r\n\r\n" + Helper.FormatTextAsHtml(currentText, false); } DisplayHtmlContentInScale(htmlResponse); } } void DisplayHtmlContentInScale(string htmlResponse) { if (fontScale != 100) { // current scaled font float fontPt = defaultFontPoint * (fontScale / 100.0f); // todo: make this a well defined class string style = "{ font-size: " + fontPt + "pt; }"; string s = htmlResponse.Replace("{ font-size: 9pt; }", style); webBrowserResponse.DocumentText = s; } else { webBrowserResponse.DocumentText = htmlResponse; } } private void tsButtonZoom_ButtonClick(object sender, EventArgs e) { switch (tsButtonZoom.Text) { case "100%": fontScale = 125; break; case "125%": fontScale = 150; break; case "150%": fontScale = 175; break; case "175%": fontScale = 100; break; } tsButtonZoom.Text = fontScale.ToString(CultureInfo.CurrentCulture) + "%"; tbRequest.Font = new Font(tbRequest.Font.FontFamily.Name, defaultFontPoint * (fontScale / 100.0f)); tbResponse.Font = new Font(tbResponse.Font.FontFamily.Name, defaultFontPoint * (fontScale / 100.0f)); Font = new Font(tbResponse.Font.FontFamily.Name, defaultFontPoint * (fontScale / 100.0f)); // we don't support pretty print for font scaling yet. if (!tsbViewType.Checked) { DisplayResponseContent(); } } private void btnHeaders_Click(object sender, EventArgs e) { if (splitContainerInner.Panel1Collapsed == true) { splitContainerInner.Panel1Collapsed = false; btnHeaders.Checked = true; btnHeaders.Text = "Hide Response Headers"; tabControl.SelectedTab = tabResponse; } else { splitContainerInner.Panel1Collapsed = true; btnHeaders.Checked = false; btnHeaders.Text = "Show Response Headers"; } } private void btnHome_Click(object sender, EventArgs e) { // DisplayHtmlContentInScale(homepage); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Close(); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show(this, Constants.ApplicationName + "\nVersion " + Constants.ProductVersion, "About", MessageBoxButtons.OK); } private void tsbViewType_Click(object sender, EventArgs e) { Settings.Default.TextView = tsbViewType.Checked; Settings.Default.Save(); SetViewTypeTabText(); if ((webBrowserResponse.Url.AbsoluteUri == "about:blank" && webBrowserResponse.DocumentTitle != "DataModelBrowserHome") || webBrowserResponse.Url.Scheme == "file") { DisplayResponseContent(); } } private void tsbHideDocumentSystemProperties_Click(object sender, EventArgs e) { Settings.Default.HideDocumentSystemProperties = tsbHideDocumentSystemProperties.Checked; Settings.Default.Save(); SetDocumentSystemPropertiesTabText(); if ((webBrowserResponse.Url.AbsoluteUri == "about:blank" && webBrowserResponse.DocumentTitle != "DataModelBrowserHome") || webBrowserResponse.Url.Scheme == "file") { DisplayResponseContent(); } } private void SetViewTypeTabText() { if (Settings.Default.TextView) tsbViewType.Text = "Pretty Json View"; else tsbViewType.Text = "Text View"; } private void settingsToolStripMenuItem_Click(object sender, EventArgs e) { // Bring up account settings dialog AccountSettingsForm dlg = new AccountSettingsForm(); DialogResult dr = dlg.ShowDialog(this); if (dr == DialogResult.OK) { AddAccountToSettings(dlg.AccountEndpoint, dlg.AccountSettings); } } public void ChangeAccountSettings(TreeNode thisNode, string accountEndpoint) { treeView1.SelectedNode = thisNode; for (int i = 0; i < Settings.Default.AccountSettingsList.Count; i = i + 2) { if (string.Compare(accountEndpoint, Settings.Default.AccountSettingsList[i], StringComparison.OrdinalIgnoreCase) == 0) { AccountSettings accountSettings = (AccountSettings)JsonConvert.DeserializeObject(Settings.Default.AccountSettingsList[i + 1], typeof(AccountSettings)); // Bring up account settings dialog AccountSettingsForm dlg = new AccountSettingsForm { AccountEndpoint = accountEndpoint, AccountSettings = accountSettings }; DialogResult dr = dlg.ShowDialog(this); if (dr == DialogResult.OK) { thisNode.Remove(); RemoveAccountFromSettings(dlg.AccountEndpoint); AddAccountToSettings(dlg.AccountEndpoint, dlg.AccountSettings); } break; } } } private void AddAccountToSettings(string accountEndpoint, AccountSettings accountSettings) { bool found = false; // if the account is not in tree view top level, add it! for (int i = 0; i < Settings.Default.AccountSettingsList.Count; i = i + 2) { if (string.Compare(accountEndpoint, Settings.Default.AccountSettingsList[i], StringComparison.OrdinalIgnoreCase) == 0) { found = true; break; } } if (!found) { if (accountSettings.IsPersistedLocally) { Settings.Default.AccountSettingsList.Add(accountEndpoint); Settings.Default.AccountSettingsList.Add(JsonConvert.SerializeObject(accountSettings)); Settings.Default.Save(); } AddConnectionTreeNode(accountEndpoint, accountSettings); } } public void RemoveAccountFromSettings(string accountEndpoint) { int index = -1; // if the account is not in tree view top level, add it! for (int i = 0; i < Settings.Default.AccountSettingsList.Count; i = i + 2) { if (string.Compare(accountEndpoint, Settings.Default.AccountSettingsList[i], StringComparison.OrdinalIgnoreCase) == 0) { index = i; break; } } if (index >= 0) { Settings.Default.AccountSettingsList.RemoveRange(index, 2); Settings.Default.Save(); } } public FeedOptions GetFeedOptions() { FeedOptions feedOptions = new FeedOptions(); try { feedOptions.MaxItemCount = Convert.ToInt32(toolStripTextMaxItemCount.Text, CultureInfo.InvariantCulture); } catch (Exception) { // Ignore the exception and use the defualt value } try { feedOptions.MaxDegreeOfParallelism = Convert.ToInt32(toolStripTextMaxDop.Text, CultureInfo.InvariantCulture); } catch (Exception) { // Ignore the exception and use the defualt value } try { feedOptions.MaxBufferedItemCount = Convert.ToInt32(toolStripTextMaxBuffItem.Text, CultureInfo.InvariantCulture); } catch (Exception) { // Ignore the exception and use the defualt value } if (cbEnableScan.CheckState == CheckState.Checked) { feedOptions.EnableScanInQuery = true; } else if (cbEnableScan.CheckState == CheckState.Unchecked) { feedOptions.EnableScanInQuery = false; } if (cbEnableCrossPartitionQuery.CheckState == CheckState.Checked) { feedOptions.EnableCrossPartitionQuery = true; } else if (cbEnableCrossPartitionQuery.CheckState == CheckState.Unchecked) { feedOptions.EnableCrossPartitionQuery = false; } return feedOptions; } public RequestOptions GetRequestOptions() { if (tbPostTrigger.Modified) { string postTrigger = tbPostTrigger.Text; if (!string.IsNullOrEmpty(postTrigger)) { // split by ; string[] segments = postTrigger.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); requestOptions.PostTriggerInclude = segments; } tbPostTrigger.Modified = false; } if (tbPreTrigger.Modified) { string preTrigger = tbPreTrigger.Text; if (!string.IsNullOrEmpty(preTrigger)) { // split by ; string[] segments = preTrigger.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); requestOptions.PreTriggerInclude = segments; } } if (tbAccessConditionText.Modified) { string condition = tbAccessConditionText.Text; if (!string.IsNullOrEmpty(condition)) { requestOptions.AccessCondition.Condition = condition; } } if (tbPartitionKeyForRequestOption.Modified) { string partitionKey = tbPartitionKeyForRequestOption.Text; if (!string.IsNullOrEmpty(partitionKey)) { requestOptions.PartitionKey = new PartitionKey(partitionKey); } } if ((resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Offer) && (operationType == OperationType.Create || operationType == OperationType.Replace)) { if (offerType == OfferType.StandardSingle || offerType == OfferType.StandardElastic) { requestOptions.OfferThroughput = int.Parse(tbThroughput.Text, CultureInfo.CurrentCulture); requestOptions.OfferType = null; } else { requestOptions.OfferType = offerType.ToString(); requestOptions.OfferThroughput = null; } } return requestOptions; } private delegate DialogResult MessageBoxDelegate(string msg, string title, MessageBoxButtons buttons, MessageBoxIcon icon); private DialogResult ShowMessage(string msg, string title, MessageBoxButtons buttons, MessageBoxIcon icon) { return MessageBox.Show(this, msg, title, buttons, icon); } public void CheckCurrentRelease() { Thread.Sleep(3000); Uri uri = new Uri("https://api.github.com/repos/mingaliu/documentdbstudio/releases"); using (HttpClient client = new HttpClient()) { try { HttpRequestMessage request = new HttpRequestMessage() { RequestUri = uri, Method = HttpMethod.Get, }; request.Headers.UserAgent.Add(new ProductInfoHeaderValue("DocumentDBStudio", Constants.ProductVersion.ToString())); HttpResponseMessage response = client.SendAsync(request).Result; if (response.StatusCode == HttpStatusCode.OK) { JArray releaseJson = JArray.Parse(response.Content.ReadAsStringAsync().Result); JToken latestRelease = releaseJson.First; JToken latestReleaseTag = latestRelease["tag_name"]; string latestReleaseString = latestReleaseTag.ToString(); if (string.Compare(Constants.ProductVersion.ToString(), latestReleaseString, StringComparison.OrdinalIgnoreCase) < 0) { Invoke(new MessageBoxDelegate(ShowMessage), string.Format(CultureInfo.InvariantCulture, "Please update the DocumentDB studio to the latest version {0} at https://github.com/mingaliu/DocumentDBStudio/releases", latestReleaseString), Constants.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception) { // ignore any exception here. } } } private void InitTreeView() { if (Settings.Default.AccountSettingsList == null) { Settings.Default.AccountSettingsList = new List<string>(); } // load the account settings from the List. for (int i = 0; i < Settings.Default.AccountSettingsList.Count; i = i + 2) { var accountSettings = (AccountSettings)JsonConvert.DeserializeObject(Settings.Default.AccountSettingsList[i + 1], typeof(AccountSettings)); AddConnectionTreeNode(Settings.Default.AccountSettingsList[i], accountSettings); } } private void AddConnectionTreeNode(string accountEndpoint, AccountSettings accountSettings) { try { var suffix = Constants.ApplicationName + "/" + Constants.ProductVersion; var client = new DocumentClient(new Uri(accountEndpoint), accountSettings.MasterKey, new ConnectionPolicy { ConnectionMode = accountSettings.ConnectionMode, ConnectionProtocol = accountSettings.Protocol, // enable after we support the automatic failover from client . EnableEndpointDiscovery = accountSettings.EnableEndpointDiscovery, UserAgentSuffix = suffix }); var dbaNode = new DatabaseAccountNode(accountEndpoint, client); treeView1.Nodes.Add(dbaNode); // Update the map. DocumentClientExtension.AddOrUpdate(client.ServiceEndpoint.Host, accountSettings.IsNameBased); dbaNode.ForeColor = accountSettings.IsNameBased ? Color.Green : Color.Blue; } catch (Exception e) { Program.GetMain().SetResultInBrowser(null, e.ToString(), true); } } private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e) { if (e.Node is FeedNode) { ((FeedNode)e.Node).Refresh(false); } } private void treeView1_NodeKeyDown(object sender, KeyEventArgs keyEventArgs) { if (treeView1.SelectedNode is FeedNode) { var node = (FeedNode)treeView1.SelectedNode; node.HandleNodeKeyDown(sender, keyEventArgs); } } private void treeView1_NodeKeyPress(object sender, KeyPressEventArgs keyPressEventArgs) { if (treeView1.SelectedNode is FeedNode) { var node = (FeedNode)treeView1.SelectedNode; if (keyPressEventArgs.KeyChar == 13) { // Enter HandleNodeSelected(node); } node.HandleNodeKeyPress(sender, keyPressEventArgs); } } private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { switch (e.Button) { case MouseButtons.Right: if (e.Node is FeedNode) { (e.Node as FeedNode).ShowContextMenu(e.Node.TreeView, e.Location); } break; case MouseButtons.Left: HandleNodeSelected(e.Node); break; } } private void HandleNodeSelected(TreeNode treeNode) { // render the JSON in the right panel. currentText = null; currentJson = null; if (treeNode is ResourceNode) { var node = treeNode as ResourceNode; var body = node.GetBody(); if (!string.IsNullOrEmpty(body)) { currentText = body; } } if (treeNode.Tag is string) { currentText = treeNode.Tag.ToString(); } else if (treeNode is DatabaseAccountNode) { currentJson = JsonConvert.SerializeObject(treeNode.Tag, Formatting.Indented); } else if (treeNode.Tag != null) { var tag = treeNode.Tag; currentJson = tag.ToString(); } if (currentJson == null && currentText == null) { currentText = treeNode.Text; } DisplayResponseContent(); } internal void SetCrudContext( TreeNode node, OperationType operation, ResourceType resourceType, string bodytext, Action<object, RequestOptions> func, CommandContext commandContext = null ) { if (commandContext == null) { commandContext = new CommandContext(); } treeView1.SelectedNode = node; operationType = operation; this.resourceType = resourceType; currentOperationCallback = func; tabCrudContext.Text = string.Format("{0} {1}", operation, resourceType); tbCrudContext.Text = bodytext; SetToolStripBtnExecuteTooltip(true); toolStripBtnExecute.Enabled = true; tbCrudContext.ReadOnly = commandContext.IsDelete; // the split panel at the right side, Panel1: tab Control, Panel2: ButtomSplitContainer (next page and browser) splitContainerInner.Panel1Collapsed = false; var showId = (resourceType == ResourceType.Trigger || resourceType == ResourceType.UserDefinedFunction || resourceType == ResourceType.StoredProcedure) && (operation == OperationType.Create || operation == OperationType.Replace); //the split panel inside Tab. Panel1: Id input box, Panel2: Edit CRUD resource. splitContainerIntabPage.Panel1Collapsed = !showId; tbResponse.Text = ""; //the split panel at right bottom. Panel1: NextPage, Panel2: Browser. if (commandContext.IsFeed) { ButtomSplitContainer.Panel1Collapsed = false; ButtomSplitContainer.Panel1.Controls.Clear(); ButtomSplitContainer.Panel1.Controls.Add(feedToolStrip); } else if (commandContext.IsCreateTrigger) { ButtomSplitContainer.Panel1Collapsed = false; ButtomSplitContainer.Panel1.Controls.Clear(); ButtomSplitContainer.Panel1.Controls.Add(triggerPanel); } else { ButtomSplitContainer.Panel1Collapsed = true; } SetNextPageVisibility(commandContext); // Prepare the tab pages tabControl.TabPages.Remove(tabDocumentCollection); tabControl.TabPages.Remove(tabOffer); tabControl.TabPages.Remove(tabCrudContext); if (this.resourceType == ResourceType.DocumentCollection && (operationType == OperationType.Create || operationType == OperationType.Replace)) { tabControl.TabPages.Insert(0, tabDocumentCollection); SetToolStripBtnExecuteTooltip(); if (operationType == OperationType.Create) { tbCollectionId.Enabled = true; tbCollectionId.Text = "DocumentCollection Id"; tabControl.TabPages.Insert(0, tabOffer); tabControl.SelectedTab = tabOffer; webBrowserResponse.Navigate(new Uri("https://azure.microsoft.com/en-us/documentation/articles/documentdb-performance-levels/")); } else { tbCollectionId.Enabled = false; tbCollectionId.Text = (node.Tag as Resource).Id; tabControl.SelectedTab = tabDocumentCollection; } } else { tabControl.TabPages.Insert(0, tabCrudContext); tabControl.SelectedTab = tabCrudContext; } } public void SetNextPageVisibility(CommandContext commandContext) { btnExecuteNext.Enabled = commandContext.HasContinuation || !commandContext.QueryStarted; } private bool ValidateInput() { if ((resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Offer) && (operationType == OperationType.Create || operationType == OperationType.Replace)) { // basic validation: if (offerType == OfferType.StandardElastic || offerType == OfferType.StandardSingle) { int throughput; if (!int.TryParse(tbThroughput.Text, NumberStyles.Integer, CultureInfo.CurrentCulture, out throughput)) { MessageBox.Show(this, "Offer throughput has to be integer", Constants.ApplicationName + "\nVersion " + Constants.ProductVersion, MessageBoxButtons.OK); return false; } if (throughput % 100 != 0) { MessageBox.Show(this, "Offer throughput has to be multiple of 100", Constants.ApplicationName + "\nVersion " + Constants.ProductVersion, MessageBoxButtons.OK); return false; } if (offerType == OfferType.StandardElastic) { // remove 250K from the internal version if (throughput < 10000) { MessageBox.Show(this, "Offer throughput has to be between 10K and 250K for partitioned collection", Constants.ApplicationName + "\nVersion " + Constants.ProductVersion, MessageBoxButtons.OK); return false; } // now verify partition key string partitionKey = tbPartitionKeyForCollectionCreate.Text; if (string.IsNullOrEmpty(partitionKey) || partitionKey[0] != '/' || partitionKey[partitionKey.Length - 1] == ' ') { MessageBox.Show(this, "PartitionKey is not in valid format", Constants.ApplicationName + "\nVersion " + Constants.ProductVersion, MessageBoxButtons.OK); return false; } } else { if (throughput < 400 || throughput > 10000) { MessageBox.Show(this, "Offer throughput has to be between 400 and 10000 for single partition collection", Constants.ApplicationName + "\nVersion " + Constants.ProductVersion, MessageBoxButtons.OK); return false; } } } } return true; } public void SetToolStripBtnExecuteTooltip(bool includeF5 = false) { toolStripBtnExecute.ToolTipText = includeF5 ? "Execute (F5)" : "Execute"; } private void toolStripBtnExecute_Click(object sender, EventArgs e) { if (!ValidateInput()) { return; } SetLoadingState(); var requestOptions = GetRequestOptions(); if (resourceType == ResourceType.DocumentCollection && (operationType == OperationType.Create || operationType == OperationType.Replace)) { newDocumentCollection.IndexingPolicy.IncludedPaths.Clear(); foreach (var item in lbIncludedPath.Items) { var includedPath = item as IncludedPath; newDocumentCollection.IndexingPolicy.IncludedPaths.Add(includedPath); } newDocumentCollection.IndexingPolicy.ExcludedPaths.Clear(); foreach (var item in lbExcludedPath.Items) { var excludedPath = item as string; newDocumentCollection.IndexingPolicy.ExcludedPaths.Add(new ExcludedPath() { Path = excludedPath }); } newDocumentCollection.Id = tbCollectionId.Text; if (operationType == OperationType.Create) { if (offerType == OfferType.StandardElastic) { newDocumentCollection.PartitionKey.Paths.Add(tbPartitionKeyForCollectionCreate.Text); } } currentOperationCallback(newDocumentCollection, requestOptions); } else if (resourceType == ResourceType.Offer && operationType == OperationType.Replace) { currentOperationCallback(newDocumentCollection, requestOptions); } else if (resourceType == ResourceType.Trigger && operationType == OperationType.Create) { var trigger = new Trigger { Body = tbCrudContext.Text, Id = textBoxforId.Text, TriggerOperation = TriggerOperation.All }; if (rbPreTrigger.Checked) trigger.TriggerType = TriggerType.Pre; else if (rbPostTrigger.Checked) trigger.TriggerType = TriggerType.Post; currentOperationCallback(trigger, requestOptions); } else if (resourceType == ResourceType.Trigger && operationType == OperationType.Replace) { var trigger = new Trigger { Body = tbCrudContext.Text, Id = textBoxforId.Text }; currentOperationCallback(trigger, requestOptions); } else if (resourceType == ResourceType.UserDefinedFunction && (operationType == OperationType.Create || operationType == OperationType.Replace)) { var udf = new UserDefinedFunction { Body = tbCrudContext.Text, Id = textBoxforId.Text }; currentOperationCallback(udf, requestOptions); } else if (resourceType == ResourceType.StoredProcedure && (operationType == OperationType.Create || operationType == OperationType.Replace)) { var storedProcedure = new StoredProcedure { Body = tbCrudContext.Text, Id = textBoxforId.Text }; currentOperationCallback(storedProcedure, requestOptions); } else { if (!string.IsNullOrEmpty(tbCrudContext.SelectedText)) { currentOperationCallback(tbCrudContext.SelectedText, requestOptions); } else { if (resourceType == ResourceType.StoredProcedure && operationType == OperationType.Execute && !tbCrudContext.Modified) { currentOperationCallback(null, requestOptions); } else { currentOperationCallback(tbCrudContext.Text, requestOptions); } } } } public void SetLoadingState() { // webBrowserResponse.Url = new Uri(loadingGifPath); } public void RenderFile(string fileName) { // webBrowserResponse.Url = new Uri(fileName); } public void SetResultInBrowser(string json, string text, bool executeButtonEnabled, NameValueCollection responseHeaders = null) { currentText = text; currentJson = json; DisplayResponseContent(); toolStripBtnExecute.Enabled = executeButtonEnabled; SetResponseHeaders(responseHeaders); } public void SetStatus(string status) { tsStatus.Text = status; } private void PrettyPrintJson(string json, string extraText, bool expandAllNodes) { if (string.IsNullOrEmpty(json)) { json = "\"\""; } string prettyPrint = prettyJSONTemplate.Replace("&JSONSTRINGREPLACE&", json); if (string.IsNullOrEmpty(extraText)) { extraText = ""; } prettyPrint = prettyPrint.Replace("&EXTRASTRINGREPLACE&", Helper.FormatTextAsHtml(extraText, false, false)); if (expandAllNodes) { prettyPrint = prettyPrint.Replace("&EXPANDALLNODES&", "node.expandAll();"); } else { prettyPrint = prettyPrint.Replace("&EXPANDALLNODES&", ""); } // save prettyePrint to file. string prettyPrintHtml = Path.Combine(SystemInfoProvider.LocalApplicationDataPath, "prettyPrint.Html"); using (StreamWriter outfile = new StreamWriter(prettyPrintHtml)) { outfile.Write(prettyPrint); } // now launch it in broswer! webBrowserResponse.Url = new Uri(prettyPrintHtml); } public void SetResponseHeaders(NameValueCollection responseHeaders) { List<NameValueCollection> responseHeadersList = null; // responseHeaders = null in case of an exception thrown if (responseHeaders != null) { responseHeadersList = new List<NameValueCollection> { responseHeaders }; } SetResponseHeaders(responseHeadersList); } public void SetResponseHeaders(List<NameValueCollection> responseHeaders) { if (responseHeaders != null) { string headers = ""; int? itemCountValue = null; decimal charge = 0; var hasContinuation = false; foreach (var nvc in responseHeaders) { if (nvc != null) { hasContinuation = false; foreach (string key in nvc.Keys) { headers += string.Format(CultureInfo.InvariantCulture, "{0}: {1}\r\n", key, nvc[key]); if (string.Compare("x-ms-request-charge", key, StringComparison.OrdinalIgnoreCase) == 0) { charge += decimal.Parse(nvc[key].Replace(".", ",")); } if (string.Compare("x-ms-item-count", key, StringComparison.OrdinalIgnoreCase) == 0) { if (itemCountValue == null) itemCountValue = 0; itemCountValue += Convert.ToInt32(nvc[key]); } if (string.Compare("x-ms-continuation", key, StringComparison.OrdinalIgnoreCase) == 0) { hasContinuation = true; } } } } tsStatus.Text = tsStatus.Text + ", Request Charge: " + charge; if (itemCountValue != null) { tsStatus.Text = tsStatus.Text + ", Count: " + itemCountValue; if (hasContinuation) { tsStatus.Text = tsStatus.Text + "+"; } } tbResponse.Text = headers; } } private void btnExecuteNext_Click(object sender, EventArgs e) { SetLoadingState(); if (!string.IsNullOrEmpty(tbCrudContext.SelectedText)) { currentOperationCallback(tbCrudContext.SelectedText, null); } else { currentOperationCallback(tbCrudContext.Text, null); } } private void cbRequestOptionsApply_CheckedChanged(object sender, EventArgs e) { CreateDefaultRequestOptions(); if (cbRequestOptionsApply.Checked) { rbIndexingDefault.Enabled = false; rbIndexingExclude.Enabled = false; rbIndexingInclude.Enabled = false; rbAccessConditionIfMatch.Enabled = false; rbAccessConditionIfNoneMatch.Enabled = false; tbAccessConditionText.Enabled = false; rbConsistencyBound.Enabled = false; rbConsistencyEventual.Enabled = false; rbConsistencySession.Enabled = false; rbConsistencyStrong.Enabled = false; tbPreTrigger.Enabled = false; tbPostTrigger.Enabled = false; tbPartitionKeyForRequestOption.Enabled = false; } else { rbIndexingDefault.Enabled = true; rbIndexingExclude.Enabled = true; rbIndexingInclude.Enabled = true; rbAccessConditionIfMatch.Enabled = true; rbAccessConditionIfNoneMatch.Enabled = true; tbAccessConditionText.Enabled = true; rbConsistencyEventual.Enabled = true; rbConsistencyBound.Enabled = true; rbConsistencySession.Enabled = true; rbConsistencyStrong.Enabled = true; tbPreTrigger.Enabled = true; tbPostTrigger.Enabled = true; tbPartitionKeyForRequestOption.Enabled = true; } } private void CreateDefaultRequestOptions() { requestOptions = new RequestOptions(); if (rbIndexingDefault.Checked) { requestOptions.IndexingDirective = IndexingDirective.Default; } else if (rbIndexingExclude.Checked) { requestOptions.IndexingDirective = IndexingDirective.Exclude; } else if (rbIndexingInclude.Checked) { requestOptions.IndexingDirective = IndexingDirective.Include; } requestOptions.AccessCondition = new AccessCondition(); if (rbAccessConditionIfMatch.Checked) { requestOptions.AccessCondition.Type = AccessConditionType.IfMatch; } else if (rbAccessConditionIfNoneMatch.Checked) { requestOptions.AccessCondition.Type = AccessConditionType.IfNoneMatch; } string condition = tbAccessConditionText.Text; if (!string.IsNullOrEmpty(condition)) { requestOptions.AccessCondition.Condition = condition; } if (rbConsistencyStrong.Checked) { requestOptions.ConsistencyLevel = ConsistencyLevel.Strong; } else if (rbConsistencyBound.Checked) { requestOptions.ConsistencyLevel = ConsistencyLevel.BoundedStaleness; } else if (rbConsistencySession.Checked) { requestOptions.ConsistencyLevel = ConsistencyLevel.Session; } else if (rbConsistencyEventual.Checked) { requestOptions.ConsistencyLevel = ConsistencyLevel.Eventual; } string preTrigger = tbPreTrigger.Text; if (!string.IsNullOrEmpty(preTrigger)) { // split by ; string[] segments = preTrigger.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); requestOptions.PreTriggerInclude = segments; } string postTrigger = tbPostTrigger.Text; if (!string.IsNullOrEmpty(postTrigger)) { // split by ; string[] segments = postTrigger.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); requestOptions.PostTriggerInclude = segments; } string partitionKey = tbPartitionKeyForRequestOption.Text; if (!string.IsNullOrEmpty(partitionKey)) { requestOptions.PartitionKey = new PartitionKey(partitionKey); } } private void rbIndexingDefault_CheckedChanged(object sender, EventArgs e) { requestOptions.IndexingDirective = IndexingDirective.Default; } private void rbIndexingInclude_CheckedChanged(object sender, EventArgs e) { requestOptions.IndexingDirective = IndexingDirective.Include; } private void rbIndexingExclude_CheckedChanged(object sender, EventArgs e) { requestOptions.IndexingDirective = IndexingDirective.Exclude; } private void rbAccessConditionIfMatch_CheckedChanged(object sender, EventArgs e) { requestOptions.AccessCondition.Type = AccessConditionType.IfMatch; } private void rbAccessConditionIfNoneMatch_CheckedChanged(object sender, EventArgs e) { requestOptions.AccessCondition.Type = AccessConditionType.IfNoneMatch; } private void rbConsistencyStrong_CheckedChanged(object sender, EventArgs e) { requestOptions.ConsistencyLevel = ConsistencyLevel.Strong; } private void rbConsistencyBound_CheckedChanged(object sender, EventArgs e) { requestOptions.ConsistencyLevel = ConsistencyLevel.BoundedStaleness; } private void rbConsistencySession_CheckedChanged(object sender, EventArgs e) { requestOptions.ConsistencyLevel = ConsistencyLevel.Session; } private void rbConsistencyEventual_CheckedChanged(object sender, EventArgs e) { requestOptions.ConsistencyLevel = ConsistencyLevel.Eventual; } private void btnAddIncludePath_Click(object sender, EventArgs e) { IncludedPathForm dlg = new IncludedPathForm(); dlg.StartPosition = FormStartPosition.CenterParent; DialogResult dr = dlg.ShowDialog(this); if (dr == DialogResult.OK) { lbIncludedPath.Items.Add(dlg.IncludedPath); } } private void btnRemovePath_Click(object sender, EventArgs e) { lbIncludedPath.Items.RemoveAt(lbIncludedPath.SelectedIndex); } private void lbIncludedPath_SelectedIndexChanged(object sender, EventArgs e) { if (lbIncludedPath.SelectedItem != null) { btnEdit.Enabled = true; btnRemovePath.Enabled = true; } else { btnEdit.Enabled = false; btnRemovePath.Enabled = false; } } private void btnEdit_Click(object sender, EventArgs e) { IncludedPath includedPath = lbIncludedPath.SelectedItem as IncludedPath; IncludedPathForm dlg = new IncludedPathForm(); dlg.StartPosition = FormStartPosition.CenterParent; dlg.SetIncludedPath(includedPath); DialogResult dr = dlg.ShowDialog(this); if (dr == DialogResult.OK) { lbIncludedPath.Items[lbIncludedPath.SelectedIndex] = dlg.IncludedPath; } } private void btnAddExcludedPath_Click(object sender, EventArgs e) { ExcludedPathForm dlg = new ExcludedPathForm(); DialogResult dr = dlg.ShowDialog(this); if (dr == DialogResult.OK) { lbExcludedPath.Items.Add(dlg.ExcludedPath); } } private void btnRemoveExcludedPath_Click(object sender, EventArgs e) { lbExcludedPath.Items.RemoveAt(lbExcludedPath.SelectedIndex); } private void lbExcludedPath_SelectedIndexChanged(object sender, EventArgs e) { if (lbExcludedPath.SelectedItem != null) { btnRemoveExcludedPath.Enabled = true; } else { btnRemoveExcludedPath.Enabled = false; } } private void cbIndexingPolicyDefault_CheckedChanged(object sender, EventArgs e) { if (cbIndexingPolicyDefault.Checked) { cbAutomatic.Enabled = false; rbConsistent.Enabled = false; rbLazy.Enabled = false; lbIncludedPath.Enabled = false; btnAddIncludePath.Enabled = false; btnRemovePath.Enabled = false; btnEdit.Enabled = false; lbExcludedPath.Enabled = false; btnAddExcludedPath.Enabled = false; btnRemoveExcludedPath.Enabled = false; tbPartitionKeyForCollectionCreate.Enabled = false; newDocumentCollection = new DocumentCollection(); } else { cbAutomatic.Enabled = true; rbConsistent.Enabled = true; rbLazy.Enabled = true; lbIncludedPath.Enabled = true; btnAddIncludePath.Enabled = true; btnRemovePath.Enabled = false; btnEdit.Enabled = false; lbExcludedPath.Enabled = true; btnAddExcludedPath.Enabled = true; btnRemoveExcludedPath.Enabled = false; tbPartitionKeyForCollectionCreate.Enabled = true; CreateDefaultIndexingPolicy(); } } private void CreateDefaultIndexingPolicy() { newDocumentCollection.IndexingPolicy.Automatic = cbAutomatic.Checked; if (rbConsistent.Checked) { newDocumentCollection.IndexingPolicy.IndexingMode = IndexingMode.Consistent; } else { newDocumentCollection.IndexingPolicy.IndexingMode = IndexingMode.Lazy; } } private void cbAutomatic_CheckedChanged(object sender, EventArgs e) { newDocumentCollection.IndexingPolicy.Automatic = cbAutomatic.Checked; } private void rbConsistent_CheckedChanged(object sender, EventArgs e) { if (rbConsistent.Checked) { newDocumentCollection.IndexingPolicy.IndexingMode = IndexingMode.Consistent; } else { newDocumentCollection.IndexingPolicy.IndexingMode = IndexingMode.Lazy; } } private void rbLazy_CheckedChanged(object sender, EventArgs e) { if (rbConsistent.Checked) { newDocumentCollection.IndexingPolicy.IndexingMode = IndexingMode.Consistent; } else { newDocumentCollection.IndexingPolicy.IndexingMode = IndexingMode.Lazy; } } private void rbOfferS1_CheckedChanged(object sender, EventArgs e) { if (rbOfferS1.Checked) { offerType = OfferType.S1; labelThroughput.Text = "Fixed 250 RU. 10GB Storage"; tbThroughput.Enabled = false; tbThroughput.Text = "250"; } } private void rbOfferS2_CheckedChanged(object sender, EventArgs e) { if (rbOfferS2.Checked) { offerType = OfferType.S2; labelThroughput.Text = "Fixed 1000 RU. 10GB Storage "; tbThroughput.Enabled = false; tbThroughput.Text = "1000"; } } private void rbOfferS3_CheckedChanged(object sender, EventArgs e) { if (rbOfferS3.Checked) { offerType = OfferType.S3; labelThroughput.Text = "Fixed 2500 RU. 10GB Storage "; tbThroughput.Enabled = false; tbThroughput.Text = "2500"; } } private void rbElasticCollection_CheckedChanged(object sender, EventArgs e) { if (rbElasticCollection.Checked) { offerType = OfferType.StandardElastic; tbPartitionKeyForCollectionCreate.Enabled = true; labelThroughput.Text = "Allowed values > 10k and <= 250k. 250GB Storage"; tbThroughput.Enabled = true; tbThroughput.Text = "20000"; } else tbPartitionKeyForCollectionCreate.Enabled = false; } private void cbShowLegacyOffer_CheckedChanged(object sender, EventArgs e) { rbOfferS1.Visible = cbShowLegacyOffer.Checked; rbOfferS2.Visible = cbShowLegacyOffer.Checked; rbOfferS3.Visible = cbShowLegacyOffer.Checked; if (!cbShowLegacyOffer.Checked) { rbSinglePartition.Checked = true; } } private void rbSinglePartition_CheckedChanged(object sender, EventArgs e) { if (rbSinglePartition.Checked) { offerType = OfferType.StandardSingle; labelThroughput.Text = "Allowed values between 400 - 10k. 10GB Storage"; tbThroughput.Enabled = true; tbThroughput.Text = "400"; } } private void feedToolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void SetDocumentSystemPropertiesTabText() { tsbHideDocumentSystemProperties.Text = Settings.Default.HideDocumentSystemProperties ? "Hide System resources" : "Show System resources"; } private void settingsToolStripMenuItem_Click_1(object sender, EventArgs e) { // Bring up account settings dialog var dlg = new AppSettingsForm(); DialogResult dr = dlg.ShowDialog(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Text; using Microsoft.Win32; using Xunit; namespace System { public static partial class PlatformDetection { // // Do not use the " { get; } = <expression> " pattern here. Having all the initialization happen in the type initializer // means that one exception anywhere means all tests using PlatformDetection fail. If you feel a value is worth latching, // do it in a way that failures don't cascade. // public static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); public static bool IsUap => IsInAppContainer; public static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase); public static bool HasWindowsShell => IsWindows && IsNotWindowsServerCore && IsNotWindowsNanoServer && IsNotWindowsIoTCore; public static bool IsWindows7 => IsWindows && GetWindowsVersion() == 6 && GetWindowsMinorVersion() == 1; public static bool IsWindows8x => IsWindows && GetWindowsVersion() == 6 && (GetWindowsMinorVersion() == 2 || GetWindowsMinorVersion() == 3); public static bool IsWindows8xOrLater => IsWindows && new Version((int)GetWindowsVersion(), (int)GetWindowsMinorVersion()) >= new Version(6, 2); public static bool IsWindowsNanoServer => IsWindows && (IsNotWindowsIoTCore && GetWindowsInstallationType().Equals("Nano Server", StringComparison.OrdinalIgnoreCase)); public static bool IsWindowsServerCore => IsWindows && GetWindowsInstallationType().Equals("Server Core", StringComparison.OrdinalIgnoreCase); public static int WindowsVersion => IsWindows ? (int)GetWindowsVersion() : -1; public static bool IsNotWindows7 => !IsWindows7; public static bool IsNotWindows8x => !IsWindows8x; public static bool IsNotWindowsNanoServer => !IsWindowsNanoServer; public static bool IsNotWindowsServerCore => !IsWindowsServerCore; public static bool IsNotWindowsIoTCore => !IsWindowsIoTCore; public static bool IsNotWindowsHomeEdition => !IsWindowsHomeEdition; public static bool IsNotInAppContainer => !IsInAppContainer; public static bool IsWinRTSupported => IsWindows && !IsWindows7; public static bool IsNotWinRTSupported => !IsWinRTSupported; public static bool IsSoundPlaySupported => IsWindows && IsNotWindowsNanoServer; // >= Windows 10 Anniversary Update public static bool IsWindows10Version1607OrGreater => IsWindows && GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393; // >= Windows 10 Creators Update public static bool IsWindows10Version1703OrGreater => IsWindows && GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 15063; // >= Windows 10 Fall Creators Update public static bool IsWindows10Version1709OrGreater => IsWindows && GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 16299; // >= Windows 10 April 2018 Update public static bool IsWindows10Version1803OrGreater => IsWindows && GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 17134; // >= Windows 10 May 2019 Update (19H1) public static bool IsWindows10Version1903OrGreater => IsWindows && GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 18362; // >= Windows 10 20H1 Update (As of Jan. 2020 yet to be released) // Per https://docs.microsoft.com/en-us/windows-insider/flight-hub/ the first 20H1 build is 18836. public static bool IsWindows10Version2004OrGreater => IsWindows && GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 18836; // Windows OneCoreUAP SKU doesn't have httpapi.dll public static bool IsNotOneCoreUAP => !IsWindows || File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "httpapi.dll")); public static bool IsWindowsIoTCore { get { if (!IsWindows) { return false; } int productType = GetWindowsProductType(); if ((productType == PRODUCT_IOTUAPCOMMERCIAL) || (productType == PRODUCT_IOTUAP)) { return true; } return false; } } public static bool IsWindowsHomeEdition { get { if (!IsWindows) { return false; } int productType = GetWindowsProductType(); switch (productType) { case PRODUCT_CORE: case PRODUCT_CORE_COUNTRYSPECIFIC: case PRODUCT_CORE_N: case PRODUCT_CORE_SINGLELANGUAGE: case PRODUCT_HOME_BASIC: case PRODUCT_HOME_BASIC_N: case PRODUCT_HOME_PREMIUM: case PRODUCT_HOME_PREMIUM_N: return true; default: return false; } } } public static bool IsWindowsSubsystemForLinux => m_isWindowsSubsystemForLinux.Value; public static bool IsNotWindowsSubsystemForLinux => !IsWindowsSubsystemForLinux; private static Lazy<bool> m_isWindowsSubsystemForLinux = new Lazy<bool>(GetIsWindowsSubsystemForLinux); private static bool GetIsWindowsSubsystemForLinux() { // https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364 if (IsLinux) { const string versionFile = "/proc/version"; if (File.Exists(versionFile)) { string s = File.ReadAllText(versionFile); if (s.Contains("Microsoft") || s.Contains("WSL")) { return true; } } } return false; } private static string GetWindowsInstallationType() { string key = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion"; string value = ""; try { value = (string)Registry.GetValue(key, "InstallationType", defaultValue: ""); } catch (Exception e) when (e is SecurityException || e is InvalidCastException || e is PlatformNotSupportedException /* UAP */) { } return value; } private static int GetWindowsProductType() { Assert.True(GetProductInfo(Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, 0, 0, out int productType)); return productType; } private const int PRODUCT_IOTUAP = 0x0000007B; private const int PRODUCT_IOTUAPCOMMERCIAL = 0x00000083; private const int PRODUCT_CORE = 0x00000065; private const int PRODUCT_CORE_COUNTRYSPECIFIC = 0x00000063; private const int PRODUCT_CORE_N = 0x00000062; private const int PRODUCT_CORE_SINGLELANGUAGE = 0x00000064; private const int PRODUCT_HOME_BASIC = 0x00000002; private const int PRODUCT_HOME_BASIC_N = 0x00000005; private const int PRODUCT_HOME_PREMIUM = 0x00000003; private const int PRODUCT_HOME_PREMIUM_N = 0x0000001A; [DllImport("kernel32.dll", SetLastError = false)] private static extern bool GetProductInfo( int dwOSMajorVersion, int dwOSMinorVersion, int dwSpMajorVersion, int dwSpMinorVersion, out int pdwReturnedProductType ); [DllImport("kernel32.dll", ExactSpelling = true)] private static extern int GetCurrentApplicationUserModelId(ref uint applicationUserModelIdLength, byte[] applicationUserModelId); internal static uint GetWindowsVersion() { Assert.Equal(0, Interop.NtDll.RtlGetVersionEx(out Interop.NtDll.RTL_OSVERSIONINFOEX osvi)); return osvi.dwMajorVersion; } internal static uint GetWindowsMinorVersion() { Assert.Equal(0, Interop.NtDll.RtlGetVersionEx(out Interop.NtDll.RTL_OSVERSIONINFOEX osvi)); return osvi.dwMinorVersion; } internal static uint GetWindowsBuildNumber() { Assert.Equal(0, Interop.NtDll.RtlGetVersionEx(out Interop.NtDll.RTL_OSVERSIONINFOEX osvi)); return osvi.dwBuildNumber; } private static int s_isInAppContainer = -1; public static bool IsInAppContainer { // This actually checks whether code is running in a modern app. // Currently this is the only situation where we run in app container. // If we want to distinguish the two cases in future, // EnvironmentHelpers.IsAppContainerProcess in desktop code shows how to check for the AC token. get { if (s_isInAppContainer != -1) return s_isInAppContainer == 1; if (!IsWindows || IsWindows7) { s_isInAppContainer = 0; return false; } byte[] buffer = Array.Empty<byte>(); uint bufferSize = 0; try { int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer); switch (result) { case 15703: // APPMODEL_ERROR_NO_APPLICATION case 120: // ERROR_CALL_NOT_IMPLEMENTED // This function is not supported on this system. // In example on Windows Nano Server s_isInAppContainer = 0; break; case 0: // ERROR_SUCCESS case 122: // ERROR_INSUFFICIENT_BUFFER // Success is actually insufficent buffer as we're really only looking for // not NO_APPLICATION and we're not actually giving a buffer here. The // API will always return NO_APPLICATION if we're not running under a // WinRT process, no matter what size the buffer is. s_isInAppContainer = 1; break; default: throw new InvalidOperationException($"Failed to get AppId, result was {result}."); } } catch (Exception e) { // We could catch this here, being friendly with older portable surface area should we // desire to use this method elsewhere. if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal)) { // API doesn't exist, likely pre Win8 s_isInAppContainer = 0; } else { throw; } } return s_isInAppContainer == 1; } } private static int s_isWindowsElevated = -1; public static bool IsWindowsAndElevated { get { if (s_isWindowsElevated != -1) return s_isWindowsElevated == 1; if (!IsWindows || IsInAppContainer) { s_isWindowsElevated = 0; return false; } s_isWindowsElevated = AdminHelpers.IsProcessElevated() ? 1 : 0; return s_isWindowsElevated == 1; } } } }
using System; using System.Collections.Generic; using GrandTheftMultiplayer.Server.API; using GrandTheftMultiplayer.Server.Constant; using GrandTheftMultiplayer.Server.Elements; using GrandTheftMultiplayer.Shared; using GrandTheftMultiplayer.Shared.Math; public class CopsNCrooks : Script { public CopsNCrooks() { Cops = new List<Client>(); Crooks = new List<Client>(); Vehicles = new List<NetHandle>(); API.onPlayerRespawn += onDeath; API.onPlayerConnected += OnPlayerConnected; API.onUpdate += onUpdate; API.onResourceStart += onResStart; API.onPlayerDisconnected += onPlayerDisconnected; } public List<Client> Cops; public List<Client> Crooks; public int CopTeam = 2; public int CrookTeam = 3; public List<NetHandle> Vehicles; private Vector3 _copRespawn = new Vector3(444.12f, -983.73f, 30.69f); private Vector3 _crookRespawn = new Vector3(617.16f, 608.95f, 128.91f); private Vector3 _targetPos = new Vector3(-1079.34f, -3001.1f, 13.96f); public Client CrookBoss; public NetHandle EscapeVehicle; public bool isRoundOngoing; private Random rngProvider = new Random(); private void SpawnCars() { Vehicles.Clear(); // Crooks Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(634.32f, 622.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(636.32f, 635.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(631.32f, 613.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(611.32f, 637.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(607.32f, 626.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Washington, new Vector3(593.32f, 618.54f, 128.44f), new Vector3(0, 0, 250.89f), 0, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Limo2, new Vector3(631.5f, 642.54f, 128.44f), new Vector3(0, 0, 327.15f), 0, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Maverick, new Vector3(644.09f, 599.09f, 129.01f), new Vector3(0, 0, 0.15f), 0, 0)); // Cops Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(407.37f, -979.13f, 28.88f), new Vector3(0, 0, 52.84f), 111, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(407.37f, -983.99f, 28.88f), new Vector3(0, 0, 52.84f), 111, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(407.37f, -988.8f, 28.88f), new Vector3(0, 0, 52.84f), 111, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(407.37f, -992.76f, 28.88f), new Vector3(0, 0, 52.84f), 111, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(407.37f, -997.72f, 28.88f), new Vector3(0, 0, 52.84f), 111, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Police2, new Vector3(393.51f, -981.3f, 28.96f), new Vector3(0, 0, 356.26f), 111, 0)); Vehicles.Add(API.createVehicle(VehicleHash.Insurgent, new Vector3(428.9f, -960.98f, 29.11f), new Vector3(0, 0, 90.12f), 111, 0)); } private void onResStart() { var blip = API.createBlip(_targetPos); API.setBlipColor(blip, 66); API.createMarker(28, _targetPos, new Vector3(), new Vector3(), new Vector3(20f, 20f, 20f), 80, 255, 255, 255); } public void onPlayerDisconnected(Client player, string reason) { if (Crooks.Contains(player)) Crooks.Remove(player); if (Cops.Contains(player)) Cops.Remove(player); if (CrookBoss == player) { API.sendNotificationToAll("The boss has left the game. Restarting the round."); isRoundOngoing = false; } if (Crooks.Count == 0 || Cops.Count == 0) { API.sendNotificationToAll("One of the teams is empty. Restarting..."); isRoundOngoing = false; } } private bool IsInRangeOf(Vector3 playerPos, Vector3 target, float range) { var direct = new Vector3(target.X - playerPos.X, target.Y - playerPos.Y, target.Z - playerPos.Z); var len = direct.X * direct.X + direct.Y * direct.Y + direct.Z * direct.Z; return range * range > len; } public void onUpdate() { if (!isRoundOngoing) { var players = API.getAllPlayers(); if (players.Count < 2) { return; } API.sendNotificationToAll("Starting new round in 5 seconds!"); API.sleep(5000); StartRound(); } else { if (IsInRangeOf(CrookBoss.position, _targetPos, 10f)) { API.sendNotificationToAll("The boss has arrived to the destination. The ~r~Crooks~w~ win!"); isRoundOngoing = false; } } } public void StartRound() { Cops.Clear(); Crooks.Clear(); API.triggerClientEventForAll("clearAllBlips"); isRoundOngoing = true; foreach (var car in Vehicles) { API.deleteEntity(car); } // spawn vehicles here SpawnCars(); var players = API.getAllPlayers(); players.Shuffle(); var firstHalfCount = players.Count / 2; var secondHalfCount = players.Count - players.Count / 2; Crooks = new List<Client>(players.GetRange(0, firstHalfCount)); Cops = new List<Client>(players.GetRange(firstHalfCount, secondHalfCount)); CrookBoss = Crooks[rngProvider.Next(Crooks.Count)]; foreach (var c in Cops) { Respawn(c); API.consoleOutput(c.name + " is a cop!"); } foreach (var c in Crooks) { if (c == CrookBoss) { API.setPlayerSkin(c, PedHash.MexBoss02GMM); // MexBoss02GMM API.sendNotificationToPlayer(c, "You are ~r~the boss~w~! Get to the ~y~extraction point~w~ alive!~"); } else { API.sendNotificationToPlayer(c, "Don't let the ~r~cops~w~ kill your boss!"); API.setPlayerSkin(c, PedHash.MexGoon03GMY); // MexGoon03GMY } CrookRespawn(c); API.setPlayerTeam(c, CrookTeam); } API.sendNotificationToAll("The crook boss is " + CrookBoss.name + "!"); } public void Respawn(Client player) { if (!isRoundOngoing) return; if (!Cops.Contains(player)) { Cops.Add(player); } API.setPlayerSkin(player, PedHash.Cop01SMY); // Cop01SMY API.givePlayerWeapon(player, WeaponHash.Nightstick, 1, true, true); API.givePlayerWeapon(player, WeaponHash.CombatPistol, 300, true, true); API.givePlayerWeapon(player, WeaponHash.PumpShotgun, 300, true, true); API.setPlayerHealth(player, 100); API.sendNotificationToPlayer(player, "Apprehend the ~r~crooks!"); API.setEntityPosition(player.handle, _copRespawn); API.setPlayerTeam(player, CopTeam); } public void CrookRespawn(Client player) { if (!isRoundOngoing) return; API.givePlayerWeapon(player, WeaponHash.Molotov, 20, true, true); API.givePlayerWeapon(player, WeaponHash.VintagePistol, 100, true, true); API.givePlayerWeapon(player, WeaponHash.Gusenberg, 700, true, true); API.setPlayerHealth(player, 100); API.setEntityPosition(player.handle, _crookRespawn); } public void onDeath(Client player) { if (player == CrookBoss) { API.sendNotificationToAll("The boss has died! ~b~Cops~w~ win!"); isRoundOngoing = false; return; } else if (Cops.Contains(player)) { Respawn(player); } else if (Crooks.Contains(player)) { CrookRespawn(player); } } public void OnPlayerConnected(Client player) { Respawn(player); } } public static class Extensions { public static Random rng = new Random(); public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; using Mono.Data.SqliteClient; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Monitoring; namespace OpenSim.Region.UserStatistics { public class ActiveConnectionsAJAX : IStatsController { private Vector3 DefaultNeighborPosition = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 70); #region IStatsController Members public string ReportName { get { return ""; } } public Hashtable ProcessModel(Hashtable pParams) { List<Scene> m_scene = (List<Scene>)pParams["Scenes"]; Hashtable nh = new Hashtable(); nh.Add("hdata", m_scene); return nh; } public string RenderView(Hashtable pModelResult) { List<Scene> all_scenes = (List<Scene>) pModelResult["hdata"]; StringBuilder output = new StringBuilder(); HTMLUtil.OL_O(ref output, ""); foreach (Scene scene in all_scenes) { HTMLUtil.LI_O(ref output, String.Empty); output.Append(scene.RegionInfo.RegionName); HTMLUtil.OL_O(ref output, String.Empty); scene.ForEachScenePresence(delegate(ScenePresence av) { Dictionary<string, string> queues = new Dictionary<string, string>(); if (av.ControllingClient is IStatsCollector) { IStatsCollector isClient = (IStatsCollector)av.ControllingClient; queues = decodeQueueReport(isClient.Report()); } HTMLUtil.LI_O(ref output, String.Empty); output.Append(av.Name); output.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); output.Append((av.IsChildAgent ? "Child" : "Root")); if (av.AbsolutePosition == DefaultNeighborPosition) { output.Append("<br />Position: ?"); } else { output.Append(string.Format("<br /><NOBR>Position: <{0},{1},{2}></NOBR>", (int)av.AbsolutePosition.X, (int)av.AbsolutePosition.Y, (int)av.AbsolutePosition.Z)); } Dictionary<string, int> throttles = DecodeClientThrottles(av.ControllingClient.GetThrottlesPacked(1)); HTMLUtil.UL_O(ref output, String.Empty); foreach (string throttlename in throttles.Keys) { HTMLUtil.LI_O(ref output, String.Empty); output.Append(throttlename); output.Append(":"); output.Append(throttles[throttlename].ToString()); if (queues.ContainsKey(throttlename)) { output.Append("/"); output.Append(queues[throttlename]); } HTMLUtil.LI_C(ref output); } if (queues.ContainsKey("Incoming") && queues.ContainsKey("Outgoing")) { HTMLUtil.LI_O(ref output, "red"); output.Append("SEND:"); output.Append(queues["Outgoing"]); output.Append("/"); output.Append(queues["Incoming"]); HTMLUtil.LI_C(ref output); } HTMLUtil.UL_C(ref output); HTMLUtil.LI_C(ref output); }); HTMLUtil.OL_C(ref output); } HTMLUtil.OL_C(ref output); return output.ToString(); } /// <summary> /// Convert active connections information to JSON string. Returns a structure: /// <pre> /// {"regionName": { /// "presenceName": { /// "name": "presenceName", /// "position": "<x,y,z>", /// "isRoot": "false", /// "throttle": { /// }, /// "queue": { /// } /// }, /// ... // multiple presences in the scene /// }, /// ... // multiple regions in the sim /// } /// /// </pre> /// </summary> /// <param name="pModelResult"></param> /// <returns></returns> public string RenderJson(Hashtable pModelResult) { List<Scene> all_scenes = (List<Scene>) pModelResult["hdata"]; OSDMap regionInfo = new OSDMap(); foreach (Scene scene in all_scenes) { OSDMap sceneInfo = new OpenMetaverse.StructuredData.OSDMap(); List<ScenePresence> avatarInScene = scene.GetScenePresences(); foreach (ScenePresence av in avatarInScene) { OSDMap presenceInfo = new OSDMap(); presenceInfo.Add("Name", new OSDString(av.Name)); Dictionary<string,string> queues = new Dictionary<string, string>(); if (av.ControllingClient is IStatsCollector) { IStatsCollector isClient = (IStatsCollector) av.ControllingClient; queues = decodeQueueReport(isClient.Report()); } OSDMap queueInfo = new OpenMetaverse.StructuredData.OSDMap(); foreach (KeyValuePair<string, string> kvp in queues) { queueInfo.Add(kvp.Key, new OSDString(kvp.Value)); } sceneInfo.Add("queues", queueInfo); if (av.IsChildAgent) presenceInfo.Add("isRoot", new OSDString("false")); else presenceInfo.Add("isRoot", new OSDString("true")); if (av.AbsolutePosition == DefaultNeighborPosition) { presenceInfo.Add("position", new OSDString("<0, 0, 0>")); } else { presenceInfo.Add("position", new OSDString(string.Format("<{0},{1},{2}>", (int)av.AbsolutePosition.X, (int) av.AbsolutePosition.Y, (int) av.AbsolutePosition.Z)) ); } Dictionary<string, int> throttles = DecodeClientThrottles(av.ControllingClient.GetThrottlesPacked(1)); OSDMap throttleInfo = new OpenMetaverse.StructuredData.OSDMap(); foreach (string throttlename in throttles.Keys) { throttleInfo.Add(throttlename, new OSDString(throttles[throttlename].ToString())); } presenceInfo.Add("throttle", throttleInfo); sceneInfo.Add(av.Name, presenceInfo); } regionInfo.Add(scene.RegionInfo.RegionName, sceneInfo); } return regionInfo.ToString(); } public Dictionary<string, int> DecodeClientThrottles(byte[] throttle) { Dictionary<string, int> returndict = new Dictionary<string, int>(); // From mantis http://opensimulator.org/mantis/view.php?id=1374 // it appears that sometimes we are receiving empty throttle byte arrays. // TODO: Investigate this behaviour if (throttle.Length == 0) { return new Dictionary<string, int>(); } int tResend = -1; int tLand = -1; int tWind = -1; int tCloud = -1; int tTask = -1; int tTexture = -1; int tAsset = -1; int tall = -1; const int singlefloat = 4; //Agent Throttle Block contains 7 single floatingpoint values. int j = 0; // Some Systems may be big endian... // it might be smart to do this check more often... if (!BitConverter.IsLittleEndian) for (int i = 0; i < 7; i++) Array.Reverse(throttle, j + i * singlefloat, singlefloat); // values gotten from OpenMetaverse.org/wiki/Throttle. Thanks MW_ // bytes // Convert to integer, since.. the full fp space isn't used. tResend = (int)BitConverter.ToSingle(throttle, j); returndict.Add("Resend", tResend); j += singlefloat; tLand = (int)BitConverter.ToSingle(throttle, j); returndict.Add("Land", tLand); j += singlefloat; tWind = (int)BitConverter.ToSingle(throttle, j); returndict.Add("Wind", tWind); j += singlefloat; tCloud = (int)BitConverter.ToSingle(throttle, j); returndict.Add("Cloud", tCloud); j += singlefloat; tTask = (int)BitConverter.ToSingle(throttle, j); returndict.Add("Task", tTask); j += singlefloat; tTexture = (int)BitConverter.ToSingle(throttle, j); returndict.Add("Texture", tTexture); j += singlefloat; tAsset = (int)BitConverter.ToSingle(throttle, j); returndict.Add("Asset", tAsset); tall = tResend + tLand + tWind + tCloud + tTask + tTexture + tAsset; returndict.Add("All", tall); return returndict; } public Dictionary<string,string> decodeQueueReport(string rep) { Dictionary<string, string> returndic = new Dictionary<string, string>(); if (rep.Length == 79) { int pos = 1; returndic.Add("All", rep.Substring((6 * pos), 8)); pos++; returndic.Add("Incoming", rep.Substring((7 * pos), 8)); pos++; returndic.Add("Outgoing", rep.Substring((7 * pos) , 8)); pos++; returndic.Add("Resend", rep.Substring((7 * pos) , 8)); pos++; returndic.Add("Land", rep.Substring((7 * pos) , 8)); pos++; returndic.Add("Wind", rep.Substring((7 * pos) , 8)); pos++; returndic.Add("Cloud", rep.Substring((7 * pos) , 8)); pos++; returndic.Add("Task", rep.Substring((7 * pos) , 8)); pos++; returndic.Add("Texture", rep.Substring((7 * pos), 8)); pos++; returndic.Add("Asset", rep.Substring((7 * pos), 8)); /* * return string.Format("{0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7}", SendQueue.Count(), IncomingPacketQueue.Count, OutgoingPacketQueue.Count, ResendOutgoingPacketQueue.Count, LandOutgoingPacketQueue.Count, WindOutgoingPacketQueue.Count, CloudOutgoingPacketQueue.Count, TaskOutgoingPacketQueue.Count, TextureOutgoingPacketQueue.Count, AssetOutgoingPacketQueue.Count); */ } return returndic; } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Diagnostics; using System.Reflection; using System.IO; namespace Be.HexEditor { /// <summary> /// Summary description for UCAbout. /// </summary> public class UCAbout : System.Windows.Forms.UserControl { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label lblAuthor; private System.Windows.Forms.Label lblVersion; private System.Windows.Forms.TabPage tabLicense; private System.Windows.Forms.RichTextBox txtLicense; private System.Windows.Forms.TabPage tabChanges; private System.Windows.Forms.RichTextBox txtChanges; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.LinkLabel lnkWorkspace; private System.Windows.Forms.TabControl tabControl; private System.Windows.Forms.TabPage tabThanksTo; private System.Windows.Forms.RichTextBox txtThanksTo; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public UCAbout() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitializeComponent call try { Assembly ca = Assembly.GetExecutingAssembly(); string resThanksTo = "Be.HexEditor.Resources.ThanksTo.rtf"; txtThanksTo.LoadFile(ca.GetManifestResourceStream(resThanksTo), RichTextBoxStreamType.RichText); string resLicense = "Be.HexEditor.Resources.license.txt"; txtLicense.LoadFile(ca.GetManifestResourceStream(resLicense), RichTextBoxStreamType.PlainText); string resChanges = "Be.HexEditor.Resources.Changes.rtf"; txtChanges.LoadFile(ca.GetManifestResourceStream(resChanges), RichTextBoxStreamType.RichText); lblVersion.Text = ca.GetName().Version.ToString(); } catch (Exception) { return; } } protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { base.ScaleControl(factor, specified); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UCAbout)); this.label1 = new System.Windows.Forms.Label(); this.lblAuthor = new System.Windows.Forms.Label(); this.lnkWorkspace = new System.Windows.Forms.LinkLabel(); this.label5 = new System.Windows.Forms.Label(); this.lblVersion = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.tabControl = new System.Windows.Forms.TabControl(); this.tabThanksTo = new System.Windows.Forms.TabPage(); this.txtThanksTo = new System.Windows.Forms.RichTextBox(); this.tabLicense = new System.Windows.Forms.TabPage(); this.txtLicense = new System.Windows.Forms.RichTextBox(); this.tabChanges = new System.Windows.Forms.TabPage(); this.txtChanges = new System.Windows.Forms.RichTextBox(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.tabControl.SuspendLayout(); this.tabThanksTo.SuspendLayout(); this.tabLicense.SuspendLayout(); this.tabChanges.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // lblAuthor // resources.ApplyResources(this.lblAuthor, "lblAuthor"); this.lblAuthor.BackColor = System.Drawing.Color.White; this.lblAuthor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblAuthor.Name = "lblAuthor"; // // lnkWorkspace // resources.ApplyResources(this.lnkWorkspace, "lnkWorkspace"); this.lnkWorkspace.BackColor = System.Drawing.Color.White; this.lnkWorkspace.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lnkWorkspace.Name = "lnkWorkspace"; this.lnkWorkspace.TabStop = true; this.lnkWorkspace.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkCompany_LinkClicked); // // label5 // resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // lblVersion // resources.ApplyResources(this.lblVersion, "lblVersion"); this.lblVersion.BackColor = System.Drawing.Color.White; this.lblVersion.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblVersion.Name = "lblVersion"; // // label7 // resources.ApplyResources(this.label7, "label7"); this.label7.Name = "label7"; // // tabControl // resources.ApplyResources(this.tabControl, "tabControl"); this.tabControl.Controls.Add(this.tabThanksTo); this.tabControl.Controls.Add(this.tabLicense); this.tabControl.Controls.Add(this.tabChanges); this.tabControl.Name = "tabControl"; this.tabControl.SelectedIndex = 0; // // tabThanksTo // resources.ApplyResources(this.tabThanksTo, "tabThanksTo"); this.tabThanksTo.Controls.Add(this.txtThanksTo); this.tabThanksTo.Name = "tabThanksTo"; // // txtThanksTo // this.txtThanksTo.BackColor = System.Drawing.Color.White; this.txtThanksTo.BorderStyle = System.Windows.Forms.BorderStyle.None; resources.ApplyResources(this.txtThanksTo, "txtThanksTo"); this.txtThanksTo.Name = "txtThanksTo"; this.txtThanksTo.ReadOnly = true; // // tabLicense // this.tabLicense.Controls.Add(this.txtLicense); resources.ApplyResources(this.tabLicense, "tabLicense"); this.tabLicense.Name = "tabLicense"; // // txtLicense // this.txtLicense.BackColor = System.Drawing.Color.White; this.txtLicense.BorderStyle = System.Windows.Forms.BorderStyle.None; resources.ApplyResources(this.txtLicense, "txtLicense"); this.txtLicense.Name = "txtLicense"; this.txtLicense.ReadOnly = true; // // tabChanges // this.tabChanges.Controls.Add(this.txtChanges); resources.ApplyResources(this.tabChanges, "tabChanges"); this.tabChanges.Name = "tabChanges"; // // txtChanges // this.txtChanges.BorderStyle = System.Windows.Forms.BorderStyle.None; resources.ApplyResources(this.txtChanges, "txtChanges"); this.txtChanges.Name = "txtChanges"; // // pictureBox1 // this.pictureBox1.Image = global::Be.HexEditor.images.Logo; resources.ApplyResources(this.pictureBox1, "pictureBox1"); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.TabStop = false; // // UCAbout // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.Controls.Add(this.pictureBox1); this.Controls.Add(this.tabControl); this.Controls.Add(this.lblVersion); this.Controls.Add(this.label7); this.Controls.Add(this.label5); this.Controls.Add(this.lnkWorkspace); this.Controls.Add(this.lblAuthor); this.Controls.Add(this.label1); this.Name = "UCAbout"; this.Load += new System.EventHandler(this.UCAbout_Load); this.tabControl.ResumeLayout(false); this.tabThanksTo.ResumeLayout(false); this.tabLicense.ResumeLayout(false); this.tabChanges.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private void lnkCompany_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { try { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(this.lnkWorkspace.Text)); } catch (Exception ex1) { MessageBox.Show(ex1.Message); } } private void UCAbout_Load(object sender, EventArgs e) { this.tabControl.Width = this.Width - 10; this.tabControl.Height = this.Height - this.tabControl.Top - 10; this.lblAuthor.Width = this.Width - this.lblAuthor.Left - 10; this.lnkWorkspace.Width = this.Width - this.lnkWorkspace.Left - 10; this.lblVersion.Width = this.Width - this.lblVersion.Left - 10; } } }
using System; using System.Linq; namespace Yandex.Money.Api.Sdk.Authorization { /// <summary> /// Represents the money-source permissions /// <see href="http://tech.yandex.ru/money/doc/dg/concepts/protocol-rights-docpage/"/> /// </summary> [Flags] public enum Source { None = 0, /// <summary> /// The requested method for making a payment with the user's bank cards that are linked to the account /// </summary> Card = 1, /// <summary> /// The requested method for making a payment from a Yandex.Money account /// </summary> Wallet = 2, /// <summary> /// Both /// </summary> CardAndWallet = Card | Wallet } /// <summary> /// Represents a list of requested permissions /// <see href="http://tech.yandex.ru/money/doc/dg/concepts/protocol-rights-docpage/"/> /// </summary> public class Scopes { /// <summary> /// permission /// </summary> public static string AccountInfo { get { return @"account-info"; } } /// <summary> /// permission /// </summary> public static string OperationHistory { get { return @"operation-history"; } } /// <summary> /// permission /// </summary> public static string OperationDetails { get { return @"operation-details"; } } /// <summary> /// permission /// </summary> public static string IncomingTransfers { get { return @"incoming-transfers"; } } /// <summary> /// permission /// </summary> /// <returns></returns> public static string PaymentToShop() { return @"payment-shop"; } /// <summary> /// permission /// </summary> /// <returns></returns> public static string PaymentP2P() { return @"payment-p2p"; } /// <summary> /// permission /// </summary> /// <param name="patternId"></param> /// <returns></returns> public static string PaymentToPattern(String patternId) { return String.Format("payment.to-pattern(\"{0}\")", patternId); } /// <summary> /// permission /// </summary> /// <param name="patternId"></param> /// <param name="sum"></param> /// <returns></returns> public static string PaymentToPattern(String patternId, String sum) { return String.Format("{0}.Limit(,{1})", PaymentToPattern(patternId), sum); } /// <summary> /// permission /// </summary> /// <param name="patternId"></param> /// <param name="sum">Total amount for all payments over the period in duration, in the currency used for the account.</param> /// <param name="duration">Period of time, in days</param> /// <returns></returns> public static string PaymentToPattern(String patternId, String sum, String duration) { return String.Format("{0}.Limit({1},{2})", PaymentToPattern(patternId), duration, sum); } /// <summary> /// permission /// </summary> /// <param name="to">The transfer recipient's account ID, phone number linked to the account, or email. Mandatory parameter</param> /// <returns></returns> public static string PaymentToAccount(String to) { return String.Format("payment.to-account(\"{0}\")", to); } /// <summary> /// permission /// </summary> /// <param name="to">The transfer recipient's account ID, phone number linked to the account, or email. Mandatory parameter</param> /// <param name="sum"></param> /// <returns></returns> public static string PaymentToAccount(String to, String sum) { return String.Format("{0}.Limit(,{1})", PaymentToAccount(to), sum); } /// <summary> /// permission /// </summary> /// <param name="to">The transfer recipient's account ID, phone number linked to the account, or email. Mandatory parameter</param> /// <param name="sum">Total amount for all payments over the period in duration, in the currency used for the account.</param> /// <param name="duration">Period of time, in days</param> /// <returns></returns> public static string PaymentToAccount(String to, String sum, String duration) { return String.Format("{0}.Limit({1},{2})", PaymentToAccount(to), duration, sum); } /// <summary> /// permission /// </summary> /// <param name="sum">Total amount for all payments over the period in duration, in the currency used for the account.</param> /// <returns></returns> public static string PaymentToShop(String sum) { return String.Format("payment-shop.Limit(,{0})", sum); } /// <summary> /// permission /// </summary> /// <param name="sum"></param> /// <param name="duration">Period of time, in days</param> /// <returns></returns> public static string PaymentToShop(String sum, String duration) { return String.Format("payment-shop.Limit({0},{1})", duration, sum); } /// <summary> /// permission /// </summary> /// <param name="sum"></param> /// <returns></returns> public static string PaymentP2P(String sum) { return String.Format("payment-p2p.Limit(,{0})", sum); } /// <summary> /// permission /// </summary> /// <param name="sum">Total amount for all payments over the period in duration, in the currency used for the account.</param> /// <param name="duration">Period of time, in days</param> /// <returns></returns> public static string PaymentP2P(String sum, String duration) { return String.Format("payment-p2p.Limit({0},{1})", duration, sum); } /// <summary> /// Represents available payment methods /// </summary> /// <param name="source">payment method</param> /// <returns></returns> public static string MoneySource(Source source) { if (source == Source.None) return null; var s = String.Empty; if ((source & Source.Card) == Source.Card) s = "\"card\""; if ((source & Source.Wallet) == Source.Wallet) s = String.IsNullOrEmpty(s) ? "\"wallet\"" : String.Format("{0}, {1}", s, "\"wallet\""); return String.Format("money-source({0})", s); } /// <summary> /// Compose the string of permissions to pass it as request query string /// </summary> /// <param name="scopes"></param> /// <returns></returns> public static string Compose(string[] scopes) { return scopes.Aggregate(String.Empty, (x, y) => String.Format("{0} {1}", x, y)).Trim(); } } }
//------------------------------------------------------------------------------ // <copyright file="DbDataReader.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.Common { using System; using System.Collections; using System.ComponentModel; using System.Data; using System.IO; using System.Threading.Tasks; using System.Threading; public abstract class DbDataReader : MarshalByRefObject, IDataReader, IEnumerable { // V1.2.3300 protected DbDataReader() : base() { } abstract public int Depth { get; } abstract public int FieldCount { get; } abstract public bool HasRows { get; } abstract public bool IsClosed { get; } abstract public int RecordsAffected { get; } virtual public int VisibleFieldCount { // NOTE: This is virtual because not all providers may choose to support // this property, since it was added in Whidbey get { return FieldCount; } } abstract public object this [ int ordinal ] { get; } abstract public object this [ string name ] { get; } virtual public void Close() { } [ EditorBrowsableAttribute(EditorBrowsableState.Never) ] public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Close(); } } abstract public string GetDataTypeName(int ordinal); [ EditorBrowsableAttribute(EditorBrowsableState.Never) ] abstract public IEnumerator GetEnumerator(); abstract public Type GetFieldType(int ordinal); abstract public string GetName(int ordinal); abstract public int GetOrdinal(string name); virtual public DataTable GetSchemaTable() { throw new NotSupportedException(); } abstract public bool GetBoolean(int ordinal); abstract public byte GetByte(int ordinal); abstract public long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length); abstract public char GetChar(int ordinal); abstract public long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length); [ EditorBrowsableAttribute(EditorBrowsableState.Never) ] public DbDataReader GetData(int ordinal) { return GetDbDataReader(ordinal); } IDataReader IDataRecord.GetData(int ordinal) { return GetDbDataReader(ordinal); } virtual protected DbDataReader GetDbDataReader(int ordinal) { // NOTE: This method is virtual because we're required to implement // it however most providers won't support it. Only the OLE DB // provider supports it right now, and they can override it. throw ADP.NotSupported(); } abstract public DateTime GetDateTime(int ordinal); abstract public Decimal GetDecimal(int ordinal); abstract public double GetDouble(int ordinal); abstract public float GetFloat(int ordinal); abstract public Guid GetGuid(int ordinal); abstract public Int16 GetInt16(int ordinal); abstract public Int32 GetInt32(int ordinal); abstract public Int64 GetInt64(int ordinal); [ EditorBrowsableAttribute(EditorBrowsableState.Never) ] virtual public Type GetProviderSpecificFieldType(int ordinal) { // NOTE: This is virtual because not all providers may choose to support // this method, since it was added in Whidbey. return GetFieldType(ordinal); } [ EditorBrowsableAttribute(EditorBrowsableState.Never) ] virtual public Object GetProviderSpecificValue(int ordinal) { // NOTE: This is virtual because not all providers may choose to support // this method, since it was added in Whidbey return GetValue(ordinal); } [ EditorBrowsableAttribute(EditorBrowsableState.Never) ] virtual public int GetProviderSpecificValues(object[] values) { // NOTE: This is virtual because not all providers may choose to support // this method, since it was added in Whidbey return GetValues(values); } abstract public String GetString(int ordinal); virtual public Stream GetStream(int ordinal) { using (MemoryStream bufferStream = new MemoryStream()) { long bytesRead = 0; long bytesReadTotal = 0; byte[] buffer = new byte[4096]; do { bytesRead = GetBytes(ordinal, bytesReadTotal, buffer, 0, buffer.Length); bufferStream.Write(buffer, 0, (int)bytesRead); bytesReadTotal += bytesRead; } while (bytesRead > 0); return new MemoryStream(bufferStream.ToArray(), false); } } virtual public TextReader GetTextReader(int ordinal) { if (IsDBNull(ordinal)) { return new StringReader(String.Empty); } else { return new StringReader(GetString(ordinal)); } } abstract public Object GetValue(int ordinal); virtual public T GetFieldValue<T>(int ordinal) { return (T)GetValue(ordinal); } public Task<T> GetFieldValueAsync<T>(int ordinal) { return GetFieldValueAsync<T>(ordinal, CancellationToken.None); } virtual public Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return ADP.CreatedTaskWithCancellation<T>(); } else { try { return Task.FromResult<T>(GetFieldValue<T>(ordinal)); } catch (Exception e) { return ADP.CreatedTaskWithException<T>(e); } } } abstract public int GetValues(object[] values); abstract public bool IsDBNull(int ordinal); public Task<bool> IsDBNullAsync(int ordinal) { return IsDBNullAsync(ordinal, CancellationToken.None); } virtual public Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return ADP.CreatedTaskWithCancellation<bool>(); } else { try { return IsDBNull(ordinal) ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return ADP.CreatedTaskWithException<bool>(e); } } } abstract public bool NextResult(); abstract public bool Read(); public Task<bool> ReadAsync() { return ReadAsync(CancellationToken.None); } virtual public Task<bool> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return ADP.CreatedTaskWithCancellation<bool>(); } else { try { return Read() ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return ADP.CreatedTaskWithException<bool>(e); } } } public Task<bool> NextResultAsync() { return NextResultAsync(CancellationToken.None); } virtual public Task<bool> NextResultAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return ADP.CreatedTaskWithCancellation<bool>(); } else { try { return NextResult() ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return ADP.CreatedTaskWithException<bool>(e); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Web; using System.Text.RegularExpressions; using System.Security.Cryptography; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Com.Aspose.Barcode.Model; namespace Com.Aspose.Barcode { public struct FileInfo { public string Name; public string MimeType; public byte[] file; } public class ApiInvoker { private static readonly ApiInvoker _instance = new ApiInvoker(); private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>(); public string appSid { set; get; } public string apiKey { set; get; } public static ApiInvoker GetInstance() { return _instance; } public void addDefaultHeader(string key, string value) { defaultHeaderMap.Add(key, value); } public string escapeString(string str) { return str; } public static object deserialize(string json, Type type) { try { if (json.StartsWith("{") || json.StartsWith("[")) return JsonConvert.DeserializeObject(json, type); else { System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(json); return JsonConvert.SerializeXmlNode(xmlDoc); } } catch (IOException e) { throw new ApiException(500, e.Message); } catch (JsonSerializationException jse) { throw new ApiException(500, jse.Message); } catch (System.Xml.XmlException xmle) { throw new ApiException(500, xmle.Message); } } public static object deserialize(byte[] BinaryData, Type type) { try { return new ResponseMessage(BinaryData); } catch (IOException e) { throw new ApiException(500, e.Message); } } private static string Sign(string url, string appKey) { UriBuilder uriBuilder = new UriBuilder(url); // Remove final slash here as it can be added automatically. uriBuilder.Path = uriBuilder.Path.TrimEnd('/'); // Compute the hash. byte[] privateKey = Encoding.UTF8.GetBytes(appKey); HMACSHA1 algorithm = new HMACSHA1(privateKey); byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri); byte[] hash = algorithm.ComputeHash(sequence); string signature = Convert.ToBase64String(hash); // Remove invalid symbols. signature = signature.TrimEnd('='); signature = HttpUtility.UrlEncode(signature); // Convert codes to upper case as they can be updated automatically. signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper()); // Add the signature to query string. return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature); } public static string serialize(object obj) { try { return obj != null ? JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }) : null; } catch (Exception e) { throw new ApiException(500, e.Message); } } public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) { return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; } public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) { return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; } public static void CopyTo(Stream source, Stream destination, int bufferSize = 81920) { byte[] array = new byte[bufferSize]; int count; while ((count = source.Read(array, 0, array.Length)) != 0) { destination.Write(array, 0, count); } } private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) { path = path.Replace("{appSid}", this.appSid); path = Regex.Replace(path, @"{.+?}", ""); //var b = new StringBuilder(); host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host; path = Sign(host + path, this.apiKey); var client = WebRequest.Create(path); client.Method = method; byte[] formData = null; if (formParams.Count > 0) { if (formParams.Count > 1) { string formDataBoundary = String.Format("Somthing"); client.ContentType = "multipart/form-data; boundary=" + formDataBoundary; formData = GetMultipartFormData(formParams, formDataBoundary); } else { client.ContentType = "multipart/form-data"; formData = GetMultipartFormData(formParams, ""); } client.ContentLength = formData.Length; } else { client.ContentType = "application/json"; } foreach (var headerParamsItem in headerParams) { client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); } foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key))) { client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); } switch (method) { case "GET": break; case "POST": case "PUT": case "DELETE": using (Stream requestStream = client.GetRequestStream()) { if (formData != null) { requestStream.Write(formData, 0, formData.Length); } if (body != null) { var swRequestWriter = new StreamWriter(requestStream); swRequestWriter.Write(serialize(body)); swRequestWriter.Close(); } } break; default: throw new ApiException(500, "unknown method type " + method); } try { var webResponse = (HttpWebResponse)client.GetResponse(); if (webResponse.StatusCode != HttpStatusCode.OK) { webResponse.Close(); throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription); } if (binaryResponse) { using (var memoryStream = new MemoryStream()) { CopyTo(webResponse.GetResponseStream(), memoryStream); return memoryStream.ToArray(); } } else { using (var responseReader = new StreamReader(webResponse.GetResponseStream())) { var responseData = responseReader.ReadToEnd(); return responseData; } } } catch (WebException ex) { var response = ex.Response as HttpWebResponse; int statusCode = 0; if (response != null) { statusCode = (int)response.StatusCode; response.Close(); } throw new ApiException(statusCode, ex.Message); } } private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary) { Stream formDataStream = new System.IO.MemoryStream(); bool needsCLRF = false; if (postParameters.Count > 1) { foreach (var param in postParameters) { // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. // Skip it on the first parameter, add it to subsequent parameters. if (needsCLRF) formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); needsCLRF = true; var fileInfo = (FileInfo)param.Value; if (param.Value is FileInfo) { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", boundary, param.Key, fileInfo.MimeType); formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length); } else { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, param.Key, fileInfo.file); formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } // Add the end of the request. Start with a newline string footer = "\r\n--" + boundary + "--\r\n"; formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); } else { foreach (var param in postParameters) { var fileInfo = (FileInfo)param.Value; if (param.Value is FileInfo) { // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length); } else { string postData = (string)param.Value; formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } } // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return formData; } /** * Overloaded method for returning the path value * For a string value an empty value is returned if the value is null * @param value * @return */ public String ToPathValue(String value) { return (value == null) ? "" : value; } public String ToPathValue(int value) { return value.ToString(); } public String ToPathValue(int? value) { return value.ToString(); } public String ToPathValue(float value) { return value.ToString(); } public String ToPathValue(float? value) { return value.ToString(); } public String ToPathValue(long value) { return value.ToString(); } public String ToPathValue(long? value) { return value.ToString(); } public String ToPathValue(bool value) { return value.ToString(); } public String ToPathValue(bool? value) { return value.ToString(); } public String ToPathValue(double value) { return value.ToString(); } public String ToPathValue(double? value) { return value.ToString(); } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Linq; using Microsoft.Data.Edm.Annotations; using Microsoft.Data.Edm.Validation; using Microsoft.Data.Edm.Validation.Internal; namespace Microsoft.Data.Edm.Csdl.Internal.Serialization { internal static class SerializationValidator { #region Additional Rules /// <summary> /// Validates that a type reference refers to a type that can be represented in CSDL. /// </summary> private static readonly ValidationRule<IEdmTypeReference> TypeReferenceTargetMustHaveValidName = new ValidationRule<IEdmTypeReference>( (context, typeReference) => { IEdmSchemaType schemaType = typeReference.Definition as IEdmSchemaType; if (schemaType != null) { if (!EdmUtil.IsQualifiedName(schemaType.FullName())) { context.AddError( typeReference.Location(), EdmErrorCode.ReferencedTypeMustHaveValidName, Strings.Serializer_ReferencedTypeMustHaveValidName(schemaType.FullName())); } } }); /// <summary> /// Validates that a type reference refers to a type that can be represented in CSDL. /// </summary> private static readonly ValidationRule<IEdmEntityReferenceType> EntityReferenceTargetMustHaveValidName = new ValidationRule<IEdmEntityReferenceType>( (context, entityReference) => { if (!EdmUtil.IsQualifiedName(entityReference.EntityType.FullName())) { context.AddError( entityReference.Location(), EdmErrorCode.ReferencedTypeMustHaveValidName, Strings.Serializer_ReferencedTypeMustHaveValidName(entityReference.EntityType.FullName())); } }); /// <summary> /// Validates that an entity set refers to a type that can be represented in CSDL. /// </summary> private static readonly ValidationRule<IEdmEntitySet> EntitySetTypeMustHaveValidName = new ValidationRule<IEdmEntitySet>( (context, set) => { if (!EdmUtil.IsQualifiedName(set.ElementType.FullName())) { context.AddError( set.Location(), EdmErrorCode.ReferencedTypeMustHaveValidName, Strings.Serializer_ReferencedTypeMustHaveValidName(set.ElementType.FullName())); } }); /// <summary> /// Validates that a structured type's base type can be represented in CSDL. /// </summary> private static readonly ValidationRule<IEdmStructuredType> StructuredTypeBaseTypeMustHaveValidName = new ValidationRule<IEdmStructuredType>( (context, type) => { IEdmSchemaType schemaBaseType = type.BaseType as IEdmSchemaType; if (schemaBaseType != null) { if (!EdmUtil.IsQualifiedName(schemaBaseType.FullName())) { context.AddError( type.Location(), EdmErrorCode.ReferencedTypeMustHaveValidName, Strings.Serializer_ReferencedTypeMustHaveValidName(schemaBaseType.FullName())); } } }); /// <summary> /// Validates that association names can be represented in CSDL. /// </summary> private static readonly ValidationRule<IEdmNavigationProperty> NavigationPropertyVerifyAssociationName = new ValidationRule<IEdmNavigationProperty>( (context, property) => { if (!EdmUtil.IsQualifiedName(context.Model.GetAssociationFullName(property))) { context.AddError( property.Location(), EdmErrorCode.ReferencedTypeMustHaveValidName, Strings.Serializer_ReferencedTypeMustHaveValidName(context.Model.GetAssociationFullName(property))); } }); /// <summary> /// Validates that vocabulary annotations serialized out of line have a serializable target name. /// </summary> private static readonly ValidationRule<IEdmVocabularyAnnotation> VocabularyAnnotationOutOfLineMustHaveValidTargetName = new ValidationRule<IEdmVocabularyAnnotation>( (context, annotation) => { if (annotation.GetSerializationLocation(context.Model) == EdmVocabularyAnnotationSerializationLocation.OutOfLine && !EdmUtil.IsQualifiedName(annotation.TargetString())) { context.AddError( annotation.Location(), EdmErrorCode.InvalidName, Strings.Serializer_OutOfLineAnnotationTargetMustHaveValidName(EdmUtil.FullyQualifiedName(annotation.Target))); } }); /// <summary> /// Validates that vocabulary annotations have a serializable term name. /// </summary> private static readonly ValidationRule<IEdmVocabularyAnnotation> VocabularyAnnotationMustHaveValidTermName = new ValidationRule<IEdmVocabularyAnnotation>( (context, annotation) => { if (!EdmUtil.IsQualifiedName(annotation.Term.FullName())) { context.AddError( annotation.Location(), EdmErrorCode.InvalidName, Strings.Serializer_OutOfLineAnnotationTargetMustHaveValidName(annotation.Term.FullName())); } }); #endregion private static ValidationRuleSet serializationRuleSet = new ValidationRuleSet(new ValidationRule[] { TypeReferenceTargetMustHaveValidName, EntityReferenceTargetMustHaveValidName, EntitySetTypeMustHaveValidName, StructuredTypeBaseTypeMustHaveValidName, VocabularyAnnotationOutOfLineMustHaveValidTargetName, VocabularyAnnotationMustHaveValidTermName, NavigationPropertyVerifyAssociationName, ValidationRules.FunctionImportEntitySetExpressionIsInvalid, ValidationRules.FunctionImportParametersCannotHaveModeOfNone, ValidationRules.FunctionOnlyInputParametersAllowedInFunctions, ValidationRules.TypeMustNotHaveKindOfNone, ValidationRules.PrimitiveTypeMustNotHaveKindOfNone, ValidationRules.PropertyMustNotHaveKindOfNone, ValidationRules.TermMustNotHaveKindOfNone, ValidationRules.SchemaElementMustNotHaveKindOfNone, ValidationRules.EntityContainerElementMustNotHaveKindOfNone, ValidationRules.EnumMustHaveIntegerUnderlyingType, ValidationRules.EnumMemberValueMustHaveSameTypeAsUnderlyingType }); public static IEnumerable<EdmError> GetSerializationErrors(this IEdmModel root) { IEnumerable<EdmError> errors; root.Validate(serializationRuleSet, out errors); errors = errors.Where(SignificantToSerialization); return errors; } internal static bool SignificantToSerialization(EdmError error) { if (ValidationHelper.IsInterfaceCritical(error)) { return true; } switch (error.ErrorCode) { case EdmErrorCode.InvalidName: case EdmErrorCode.NameTooLong: case EdmErrorCode.InvalidNamespaceName: case EdmErrorCode.SystemNamespaceEncountered: case EdmErrorCode.RowTypeMustNotHaveBaseType: case EdmErrorCode.ReferencedTypeMustHaveValidName: case EdmErrorCode.FunctionImportEntitySetExpressionIsInvalid: case EdmErrorCode.FunctionImportParameterIncorrectType: case EdmErrorCode.OnlyInputParametersAllowedInFunctions: case EdmErrorCode.InvalidFunctionImportParameterMode: case EdmErrorCode.TypeMustNotHaveKindOfNone: case EdmErrorCode.PrimitiveTypeMustNotHaveKindOfNone: case EdmErrorCode.PropertyMustNotHaveKindOfNone: case EdmErrorCode.TermMustNotHaveKindOfNone: case EdmErrorCode.SchemaElementMustNotHaveKindOfNone: case EdmErrorCode.EntityContainerElementMustNotHaveKindOfNone: case EdmErrorCode.BinaryValueCannotHaveEmptyValue: case EdmErrorCode.EnumMustHaveIntegerUnderlyingType: case EdmErrorCode.EnumMemberTypeMustMatchEnumUnderlyingType: return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using System.Net.Http.WinHttpHandlerUnitTests; using Microsoft.DotNet.RemoteExecutor; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Tests { public class HttpWindowsProxyTest { private readonly ITestOutputHelper _output; private const string FakeProxyString = "http://proxy.contoso.com"; private const string insecureProxyUri = "http://proxy.insecure.com"; private const string secureProxyUri = "http://proxy.secure.com"; private const string secureAndInsecureProxyUri = "http://proxy.secure-and-insecure.com"; private const string fooHttp = "http://foo.com"; private const string fooHttps = "https://foo.com"; private const string fooWs = "ws://foo.com"; private const string fooWss = "wss://foo.com"; public HttpWindowsProxyTest(ITestOutputHelper output) { _output = output; } [Theory] [MemberData(nameof(ProxyParsingData))] public void HttpProxy_WindowsProxy_Manual_Loaded(string rawProxyString, string rawInsecureUri, string rawSecureUri) { RemoteExecutor.Invoke((proxyString, insecureProxy, secureProxy) => { FakeRegistry.Reset(); Assert.False(HttpWindowsProxy.TryCreate(out IWebProxy p)); FakeRegistry.WinInetProxySettings.Proxy = proxyString; WinInetProxyHelper proxyHelper = new WinInetProxyHelper(); Assert.Null(proxyHelper.AutoConfigUrl); Assert.Equal(proxyString, proxyHelper.Proxy); Assert.False(proxyHelper.AutoSettingsUsed); Assert.True(proxyHelper.ManualSettingsUsed); Assert.True(HttpWindowsProxy.TryCreate(out p)); Assert.NotNull(p); Assert.Equal(!string.IsNullOrEmpty(insecureProxy) ? new Uri(insecureProxy) : null, p.GetProxy(new Uri(fooHttp))); Assert.Equal(!string.IsNullOrEmpty(secureProxy) ? new Uri(secureProxy) : null, p.GetProxy(new Uri(fooHttps))); Assert.Equal(!string.IsNullOrEmpty(insecureProxy) ? new Uri(insecureProxy) : null, p.GetProxy(new Uri(fooWs))); Assert.Equal(!string.IsNullOrEmpty(secureProxy) ? new Uri(secureProxy) : null, p.GetProxy(new Uri(fooWss))); return RemoteExecutor.SuccessExitCode; }, rawProxyString, rawInsecureUri ?? string.Empty, rawSecureUri ?? string.Empty).Dispose(); } [Theory] [MemberData(nameof(ProxyParsingData))] public void HttpProxy_WindowsProxy_PAC_Loaded(string rawProxyString, string rawInsecureUri, string rawSecureUri) { RemoteExecutor.Invoke((proxyString, insecureProxy, secureProxy) => { TestControl.ResetAll(); Assert.False(HttpWindowsProxy.TryCreate(out IWebProxy p)); FakeRegistry.WinInetProxySettings.AutoConfigUrl = "http://127.0.0.1/proxy.pac"; WinInetProxyHelper proxyHelper = new WinInetProxyHelper(); Assert.Null(proxyHelper.Proxy); Assert.Equal(FakeRegistry.WinInetProxySettings.AutoConfigUrl, proxyHelper.AutoConfigUrl); Assert.False(proxyHelper.ManualSettingsUsed); Assert.True(proxyHelper.AutoSettingsUsed); Assert.True(HttpWindowsProxy.TryCreate(out p)); Assert.NotNull(p); // With a HttpWindowsProxy created configured to use auto-config, now set Proxy so when it // attempts to resolve a proxy, it resolves our string. FakeRegistry.WinInetProxySettings.Proxy = proxyString; proxyHelper = new WinInetProxyHelper(); Assert.Equal(proxyString, proxyHelper.Proxy); Assert.Equal(!string.IsNullOrEmpty(insecureProxy) ? new Uri(insecureProxy) : null, p.GetProxy(new Uri(fooHttp))); Assert.Equal(!string.IsNullOrEmpty(secureProxy) ? new Uri(secureProxy) : null, p.GetProxy(new Uri(fooHttps))); Assert.Equal(!string.IsNullOrEmpty(insecureProxy) ? new Uri(insecureProxy) : null, p.GetProxy(new Uri(fooWs))); Assert.Equal(!string.IsNullOrEmpty(secureProxy) ? new Uri(secureProxy) : null, p.GetProxy(new Uri(fooWss))); return RemoteExecutor.SuccessExitCode; }, rawProxyString, rawInsecureUri ?? string.Empty, rawSecureUri ?? string.Empty).Dispose(); } public static TheoryData<string, string, string> ProxyParsingData => new TheoryData<string, string, string> { { "http://proxy.insecure.com", insecureProxyUri, null }, { "http=http://proxy.insecure.com", insecureProxyUri, null }, { "http=proxy.insecure.com", insecureProxyUri, null }, { "http://proxy.insecure.com http://proxy.wrong.com", insecureProxyUri, null }, { "https=proxy.secure.com http=proxy.insecure.com", insecureProxyUri, secureProxyUri }, { "https://proxy.secure.com\nhttp://proxy.insecure.com", insecureProxyUri, secureProxyUri }, { "https=proxy.secure.com\nhttp=proxy.insecure.com", insecureProxyUri, secureProxyUri }, { "https://proxy.secure.com;http://proxy.insecure.com", insecureProxyUri, secureProxyUri }, { "https=proxy.secure.com;http=proxy.insecure.com", insecureProxyUri, secureProxyUri }, { ";http=proxy.insecure.com;;", insecureProxyUri, null }, { " http=proxy.insecure.com ", insecureProxyUri, null }, { "http=proxy.insecure.com;http=proxy.wrong.com", insecureProxyUri, null }, { "http=http://proxy.insecure.com", insecureProxyUri, null }, { "https://proxy.secure.com", null, secureProxyUri }, { "https=proxy.secure.com", null, secureProxyUri }, { "https=https://proxy.secure.com", null, secureProxyUri }, { "http=https://proxy.secure.com", null, secureProxyUri }, { "https=http://proxy.insecure.com", insecureProxyUri, null }, { "proxy.secure-and-insecure.com", secureAndInsecureProxyUri, secureAndInsecureProxyUri }, }; [Theory] [InlineData("localhost:1234", "http://localhost:1234/")] [InlineData("123.123.123.123", "http://123.123.123.123/")] public void HttpProxy_WindowsProxy_Loaded(string rawProxyString, string expectedUri) { RemoteExecutor.Invoke((proxyString, expectedString) => { IWebProxy p; FakeRegistry.Reset(); FakeRegistry.WinInetProxySettings.Proxy = proxyString; WinInetProxyHelper proxyHelper = new WinInetProxyHelper(); Assert.True(HttpWindowsProxy.TryCreate(out p)); Assert.NotNull(p); Assert.Equal(expectedString, p.GetProxy(new Uri(fooHttp)).ToString()); Assert.Equal(expectedString, p.GetProxy(new Uri(fooHttps)).ToString()); return RemoteExecutor.SuccessExitCode; }, rawProxyString, expectedUri).Dispose(); } [Theory] [InlineData("http://localhost/", true)] [InlineData("http://127.0.0.1/", true)] [InlineData("http://128.0.0.1/", false)] [InlineData("http://[::1]/", true)] [InlineData("http://foo/", true)] [InlineData("http://www.foo.com/", true)] [InlineData("http://WWW.FOO.COM/", true)] [InlineData("http://foo.com/", false)] [InlineData("http://bar.com/", true)] [InlineData("http://BAR.COM/", true)] [InlineData("http://162.1.1.1/", true)] [InlineData("http://[2a01:5b40:0:248::52]/", false)] [InlineData("http://[2002::11]/", true)] [InlineData("http://[2607:f8b0:4005:80a::200e]/", true)] [InlineData("http://[2607:f8B0:4005:80A::200E]/", true)] [InlineData("http://b\u00e9b\u00e9.eu/", true)] [InlineData("http://www.b\u00e9b\u00e9.eu/", true)] public void HttpProxy_Local_Bypassed(string name, bool shouldBypass) { RemoteExecutor.Invoke((url, expected) => { bool expectedResult = Boolean.Parse(expected); IWebProxy p; FakeRegistry.Reset(); FakeRegistry.WinInetProxySettings.Proxy = insecureProxyUri; FakeRegistry.WinInetProxySettings.ProxyBypass = "23.23.86.44;*.foo.com;<local>;BAR.COM; ; 162*;[2002::11];[*:f8b0:4005:80a::200e]; http://www.xn--mnchhausen-9db.at;http://*.xn--bb-bjab.eu;http://xn--bb-bjab.eu;"; Assert.True(HttpWindowsProxy.TryCreate(out p)); Assert.NotNull(p); Uri u = new Uri(url); Assert.Equal(expectedResult, p.GetProxy(u) == null); return RemoteExecutor.SuccessExitCode; }, name, shouldBypass.ToString()).Dispose(); } [Theory] [InlineData("", 0)] [InlineData(" ", 0)] [InlineData(" ; ; ", 0)] [InlineData("http://127.0.0.1/", 1)] [InlineData("[::]", 1)] public void HttpProxy_Local_Parsing(string bypass, int count) { RemoteExecutor.Invoke((bypassValue, expected) => { int expectedCount = Convert.ToInt32(expected); IWebProxy p; FakeRegistry.Reset(); FakeRegistry.WinInetProxySettings.Proxy = insecureProxyUri; FakeRegistry.WinInetProxySettings.ProxyBypass = bypassValue; Assert.True(HttpWindowsProxy.TryCreate(out p)); Assert.NotNull(p); HttpWindowsProxy sp = p as HttpWindowsProxy; Assert.NotNull(sp); if (expectedCount > 0) { Assert.Equal(expectedCount, sp.BypassList.Count); } else { Assert.Null(sp.BypassList); } return RemoteExecutor.SuccessExitCode; }, bypass, count.ToString()).Dispose(); } [Theory] [InlineData("http://")] [InlineData("http=")] [InlineData("http://;")] [InlineData("http=;")] [InlineData(" ; ")] public void HttpProxy_InvalidWindowsProxy_Null(string rawProxyString) { RemoteExecutor.Invoke((proxyString) => { IWebProxy p; FakeRegistry.Reset(); Assert.False(HttpWindowsProxy.TryCreate(out p)); FakeRegistry.WinInetProxySettings.Proxy = proxyString; WinInetProxyHelper proxyHelper = new WinInetProxyHelper(); Assert.True(HttpWindowsProxy.TryCreate(out p)); Assert.NotNull(p); Assert.Equal(null, p.GetProxy(new Uri(fooHttp))); Assert.Equal(null, p.GetProxy(new Uri(fooHttps))); Assert.Equal(null, p.GetProxy(new Uri(fooWs))); Assert.Equal(null, p.GetProxy(new Uri(fooWss))); return RemoteExecutor.SuccessExitCode; }, rawProxyString).Dispose(); } } }
using UnityEngine; using UnityEditor; using System; using System.Linq; using System.Collections.Generic; using Model=UnityEngine.AssetBundles.GraphTool.DataModel.Version2; namespace UnityEngine.AssetBundles.GraphTool { public class ImportSettingsConfigurator { private readonly AssetImporter referenceImporter; public ImportSettingsConfigurator (AssetImporter referenceImporter) { this.referenceImporter = referenceImporter; } public bool IsEqual(AssetImporter importer, bool ignorePackingTagDifference = false) { if(importer.GetType() != referenceImporter.GetType()) { throw new AssetBundleGraphException("Importer type does not match."); } if(importer.GetType() == typeof(UnityEditor.TextureImporter)) { return IsEqual(importer as UnityEditor.TextureImporter, ignorePackingTagDifference); } else if(importer.GetType() == typeof(UnityEditor.AudioImporter)) { return IsEqual(importer as UnityEditor.AudioImporter); } else if(importer.GetType() == typeof(UnityEditor.ModelImporter)) { return IsEqual(importer as UnityEditor.ModelImporter); } #if UNITY_5_6 || UNITY_5_6_OR_NEWER else if(importer.GetType() == typeof(UnityEditor.VideoClipImporter)) { return IsEqual(importer as UnityEditor.VideoClipImporter); } #endif else { throw new AssetBundleGraphException("Unknown importer type found:" + importer.GetType()); } } public void OverwriteImportSettings(AssetImporter importer) { // avoid touching asset if there is no need to. if(IsEqual(importer)) { return; } if(importer.GetType() != referenceImporter.GetType()) { throw new AssetBundleGraphException("Importer type does not match."); } if(importer.GetType() == typeof(UnityEditor.TextureImporter)) { OverwriteImportSettings(importer as UnityEditor.TextureImporter); } else if(importer.GetType() == typeof(UnityEditor.AudioImporter)) { OverwriteImportSettings(importer as UnityEditor.AudioImporter); } else if(importer.GetType() == typeof(UnityEditor.ModelImporter)) { OverwriteImportSettings(importer as UnityEditor.ModelImporter); } #if UNITY_5_6 || UNITY_5_6_OR_NEWER else if(importer.GetType() == typeof(UnityEditor.VideoClipImporter)) { OverwriteImportSettings(importer as UnityEditor.VideoClipImporter); } #endif else { throw new AssetBundleGraphException("Unknown importer type found:" + importer.GetType()); } } #region TextureImporter private void OverwriteImportSettings (TextureImporter importer) { var reference = referenceImporter as TextureImporter; UnityEngine.Assertions.Assert.IsNotNull(reference); importer.textureType = reference.textureType; importer.anisoLevel = reference.anisoLevel; importer.borderMipmap = reference.borderMipmap; importer.compressionQuality = reference.compressionQuality; importer.convertToNormalmap = reference.convertToNormalmap; importer.fadeout = reference.fadeout; importer.filterMode = reference.filterMode; importer.generateCubemap = reference.generateCubemap; importer.heightmapScale = reference.heightmapScale; importer.isReadable = reference.isReadable; importer.maxTextureSize = reference.maxTextureSize; importer.mipMapBias = reference.mipMapBias; importer.mipmapEnabled = reference.mipmapEnabled; importer.mipmapFadeDistanceEnd = reference.mipmapFadeDistanceEnd; importer.mipmapFadeDistanceStart = reference.mipmapFadeDistanceStart; importer.mipmapFilter = reference.mipmapFilter; importer.normalmapFilter = reference.normalmapFilter; importer.npotScale = reference.npotScale; importer.spriteBorder = reference.spriteBorder; importer.spriteImportMode = reference.spriteImportMode; importer.spritePackingTag = reference.spritePackingTag; importer.spritePivot = reference.spritePivot; importer.spritePixelsPerUnit = reference.spritePixelsPerUnit; importer.spritesheet = reference.spritesheet; importer.wrapMode = reference.wrapMode; /* read only */ // importer.qualifiesForSpritePacking #if !UNITY_5_5_OR_NEWER // obsolete features importer.generateMipsInLinearSpace = reference.generateMipsInLinearSpace; importer.grayscaleToAlpha = reference.grayscaleToAlpha; importer.lightmap = reference.lightmap; importer.linearTexture = reference.linearTexture; importer.normalmap = reference.normalmap; importer.textureFormat = reference.textureFormat; #endif #if UNITY_5_5_OR_NEWER importer.alphaSource = reference.alphaSource; importer.sRGBTexture = reference.sRGBTexture; foreach(var g in NodeGUIUtility.SupportedBuildTargetGroups) { var platformName = BuildTargetUtility.TargetToAssetBundlePlatformName(g, BuildTargetUtility.PlatformNameType.TextureImporter); var impSet = reference.GetPlatformTextureSettings(platformName); importer.SetPlatformTextureSettings(impSet); } importer.textureCompression = reference.textureCompression; importer.crunchedCompression = reference.crunchedCompression; #endif #if UNITY_2017_1_OR_NEWER importer.alphaTestReferenceValue = reference.alphaTestReferenceValue; importer.mipMapsPreserveCoverage = reference.mipMapsPreserveCoverage; importer.wrapModeU = reference.wrapModeU; importer.wrapModeV = reference.wrapModeV; importer.wrapModeW = reference.wrapModeW; #endif } private bool IsEqual (TextureImporter target, bool ignorePackingTagDifference) { TextureImporter reference = referenceImporter as TextureImporter; UnityEngine.Assertions.Assert.IsNotNull(reference); // UnityEditor.TextureImporter.textureFormat' is obsolete: // `textureFormat is not longer accessible at the TextureImporter level if (target.textureType != reference.textureType) return false; if (target.wrapMode != reference.wrapMode) return false; if (target.anisoLevel != reference.anisoLevel) return false; if (target.borderMipmap != reference.borderMipmap) return false; if (target.compressionQuality != reference.compressionQuality) return false; if (target.convertToNormalmap != reference.convertToNormalmap) return false; if (target.fadeout != reference.fadeout) return false; if (target.filterMode != reference.filterMode) return false; if (target.generateCubemap != reference.generateCubemap) return false; if (target.heightmapScale != reference.heightmapScale) return false; if (target.isReadable != reference.isReadable) return false; if (target.maxTextureSize != reference.maxTextureSize) return false; if (target.mipMapBias != reference.mipMapBias) return false; if (target.mipmapEnabled != reference.mipmapEnabled) return false; if (target.mipmapFadeDistanceEnd != reference.mipmapFadeDistanceEnd) return false; if (target.mipmapFadeDistanceStart != reference.mipmapFadeDistanceStart) return false; if (target.mipmapFilter != reference.mipmapFilter) return false; if (target.normalmapFilter != reference.normalmapFilter) return false; if (target.npotScale != reference.npotScale) return false; if (target.spriteBorder != reference.spriteBorder) return false; if (target.spriteImportMode != reference.spriteImportMode) return false; if (!ignorePackingTagDifference && target.spritePackingTag != reference.spritePackingTag) return false; if (target.spritePivot != reference.spritePivot) return false; if (target.spritePixelsPerUnit != reference.spritePixelsPerUnit) return false; /* read only properties */ // target.qualifiesForSpritePacking #if !UNITY_5_5_OR_NEWER // obsolete features if (target.normalmap != reference.normalmap) return false; if (target.linearTexture != reference.linearTexture) return false; if (target.lightmap != reference.lightmap) return false; if (target.grayscaleToAlpha != reference.grayscaleToAlpha) return false; if (target.generateMipsInLinearSpace != reference.generateMipsInLinearSpace) return false; if (target.textureFormat != reference.textureFormat) return false; #endif #if UNITY_5_5_OR_NEWER if (target.alphaSource != reference.alphaSource) return false; if (target.sRGBTexture != reference.sRGBTexture) return false; foreach(var g in NodeGUIUtility.SupportedBuildTargetGroups) { var platformName = BuildTargetUtility.TargetToAssetBundlePlatformName(g, BuildTargetUtility.PlatformNameType.TextureImporter); var impSet = reference.GetPlatformTextureSettings(platformName); var targetImpSet = target.GetPlatformTextureSettings(platformName); if(!CompareImporterPlatformSettings(impSet, targetImpSet)) return false; } if(target.textureCompression != reference.textureCompression) return false; if(target.crunchedCompression != reference.crunchedCompression) return false; #endif #if UNITY_2017_1_OR_NEWER if (target.alphaTestReferenceValue != reference.alphaTestReferenceValue) return false; if (target.mipMapsPreserveCoverage != reference.mipMapsPreserveCoverage) return false; if (target.wrapModeU != reference.wrapModeU) return false; if (target.wrapModeV != reference.wrapModeV) return false; if (target.wrapModeW != reference.wrapModeW) return false; #endif // spritesheet { if (target.spritesheet.Length != reference.spritesheet.Length) return false; for (int i = 0; i < target.spritesheet.Length; i++) { if (target.spritesheet[i].alignment != reference.spritesheet[i].alignment) return false; if (target.spritesheet[i].border != reference.spritesheet[i].border) return false; if (target.spritesheet[i].name != reference.spritesheet[i].name) return false; if (target.spritesheet[i].pivot != reference.spritesheet[i].pivot) return false; if (target.spritesheet[i].rect != reference.spritesheet[i].rect) return false; } } return true; } bool CompareImporterPlatformSettings(TextureImporterPlatformSettings c1, TextureImporterPlatformSettings c2) { if(c1.allowsAlphaSplitting != c2.allowsAlphaSplitting) return false; if(c1.compressionQuality != c2.compressionQuality) return false; if(c1.crunchedCompression != c2.crunchedCompression) return false; if(c1.format != c2.format) return false; if(c1.maxTextureSize != c2.maxTextureSize) return false; if(c1.name != c2.name) return false; if(c1.overridden != c2.overridden) return false; if(c1.textureCompression != c2.textureCompression) return false; return true; } #endregion #region AudioImporter private void OverwriteImportSettings (AudioImporter importer) { var reference = referenceImporter as AudioImporter; UnityEngine.Assertions.Assert.IsNotNull(reference); importer.defaultSampleSettings = reference.defaultSampleSettings; importer.forceToMono = reference.forceToMono; importer.preloadAudioData = reference.preloadAudioData; foreach(var g in NodeGUIUtility.SupportedBuildTargetGroups) { var platformName = BuildTargetUtility.TargetToAssetBundlePlatformName(g, BuildTargetUtility.PlatformNameType.AudioImporter); if (reference.ContainsSampleSettingsOverride (platformName)) { var setting = reference.GetOverrideSampleSettings (platformName); if (!importer.SetOverrideSampleSettings (platformName, setting)) { LogUtility.Logger.LogError ("AudioImporter", string.Format ("Failed to set override setting for {0}: {1}", platformName, importer.assetPath)); } } else { importer.ClearSampleSettingOverride (platformName); } } // using "!UNITY_5_6_OR_NEWER" instead of "Unity_5_6" because loadInBackground became obsolete after Unity 5.6b3. #if !UNITY_5_6_OR_NEWER importer.loadInBackground = reference.loadInBackground; #endif } private bool IsEqual (AudioImporter target) { AudioImporter reference = referenceImporter as AudioImporter; UnityEngine.Assertions.Assert.IsNotNull (reference); if (!IsEqualAudioSampleSetting (target.defaultSampleSettings, reference.defaultSampleSettings)) { return false; } foreach(var g in NodeGUIUtility.SupportedBuildTargetGroups) { var platformName = BuildTargetUtility.TargetToAssetBundlePlatformName(g, BuildTargetUtility.PlatformNameType.AudioImporter); if (target.ContainsSampleSettingsOverride (platformName) != reference.ContainsSampleSettingsOverride (platformName)) { return false; } if (target.ContainsSampleSettingsOverride (platformName)) { var t = target.GetOverrideSampleSettings (platformName); var r = reference.GetOverrideSampleSettings (platformName); if (!IsEqualAudioSampleSetting (t, r)) { return false; } } } if (target.forceToMono != reference.forceToMono) return false; // using "!UNITY_5_6_OR_NEWER" instead of "Unity_5_6" because loadInBackground became obsolete after Unity 5.6b3. #if !UNITY_5_6_OR_NEWER if (target.loadInBackground != reference.loadInBackground) return false; #endif if (target.preloadAudioData != reference.preloadAudioData) return false; return true; } private bool IsEqualAudioSampleSetting (AudioImporterSampleSettings target, AudioImporterSampleSettings reference) { // defaultSampleSettings if (target.compressionFormat != reference.compressionFormat) return false; if (target.loadType != reference.loadType) return false; if (target.quality != reference.quality) return false; if (target.sampleRateOverride != reference.sampleRateOverride) return false; if (target.sampleRateSetting != reference.sampleRateSetting) return false; return true; } #endregion #region ModelImporter private void OverwriteImportSettings (ModelImporter importer) { var reference = referenceImporter as ModelImporter; UnityEngine.Assertions.Assert.IsNotNull(reference); importer.addCollider = reference.addCollider; importer.animationCompression = reference.animationCompression; importer.animationPositionError = reference.animationPositionError; importer.animationRotationError = reference.animationRotationError; importer.animationScaleError = reference.animationScaleError; importer.animationType = reference.animationType; importer.animationWrapMode = reference.animationWrapMode; importer.bakeIK = reference.bakeIK; importer.clipAnimations = reference.clipAnimations; importer.extraExposedTransformPaths = reference.extraExposedTransformPaths; importer.generateAnimations = reference.generateAnimations; importer.generateSecondaryUV = reference.generateSecondaryUV; importer.globalScale = reference.globalScale; importer.humanDescription = reference.humanDescription; importer.importBlendShapes = reference.importBlendShapes; importer.isReadable = reference.isReadable; importer.materialName = reference.materialName; importer.materialSearch = reference.materialSearch; importer.normalSmoothingAngle = reference.normalSmoothingAngle; importer.optimizeMesh = reference.optimizeMesh; importer.secondaryUVAngleDistortion = reference.secondaryUVAngleDistortion; importer.secondaryUVAreaDistortion = reference.secondaryUVAreaDistortion; importer.secondaryUVHardAngle = reference.secondaryUVHardAngle; importer.secondaryUVPackMargin = reference.secondaryUVPackMargin; importer.sourceAvatar = reference.sourceAvatar; importer.swapUVChannels = reference.swapUVChannels; importer.importTangents = reference.importTangents; #if UNITY_5_6 || UNITY_5_6_OR_NEWER importer.keepQuads = reference.keepQuads; importer.weldVertices = reference.weldVertices; #endif #if UNITY_2017_1_OR_NEWER importer.importCameras = reference.importCameras; importer.importLights = reference.importLights; importer.normalCalculationMode = reference.normalCalculationMode; importer.useFileScale = reference.useFileScale; #endif /* read only */ /* importer.importedTakeInfos importer.defaultClipAnimations importer.importAnimation importer.isTangentImportSupported importer.meshCompression importer.importNormals importer.optimizeGameObjects importer.referencedClips importer.fileScale importer.importMaterials importer.isUseFileUnitsSupported importer.motionNodeName importer.isBakeIKSupported importer.isFileScaleUsed importer.useFileUnits importer.transformPaths */ /* Obsolete */ } public bool IsEqual (ModelImporter target) { ModelImporter reference = referenceImporter as ModelImporter; UnityEngine.Assertions.Assert.IsNotNull(reference); if (target.addCollider != reference.addCollider) return false; if (target.animationCompression != reference.animationCompression) return false; if (target.animationPositionError != reference.animationPositionError) return false; if (target.animationRotationError != reference.animationRotationError) return false; if (target.animationScaleError != reference.animationScaleError) return false; if (target.animationType != reference.animationType) return false; if (target.animationWrapMode != reference.animationWrapMode) return false; if (target.bakeIK != reference.bakeIK) return false; // clipAnimations { if (target.clipAnimations.Length != reference.clipAnimations.Length) return false; for (int i = 0; i < target.clipAnimations.Length; i++) { if (target.clipAnimations[i].additiveReferencePoseFrame != reference.clipAnimations[i].additiveReferencePoseFrame) return false; if (target.clipAnimations[i].curves != reference.clipAnimations[i].curves) return false; if (target.clipAnimations[i].cycleOffset != reference.clipAnimations[i].cycleOffset) return false; if (target.clipAnimations[i].events != reference.clipAnimations[i].events) return false; if (target.clipAnimations[i].firstFrame != reference.clipAnimations[i].firstFrame) return false; if (target.clipAnimations[i].hasAdditiveReferencePose != reference.clipAnimations[i].hasAdditiveReferencePose) return false; if (target.clipAnimations[i].heightFromFeet != reference.clipAnimations[i].heightFromFeet) return false; if (target.clipAnimations[i].heightOffset != reference.clipAnimations[i].heightOffset) return false; if (target.clipAnimations[i].keepOriginalOrientation != reference.clipAnimations[i].keepOriginalOrientation) return false; if (target.clipAnimations[i].keepOriginalPositionXZ != reference.clipAnimations[i].keepOriginalPositionXZ) return false; if (target.clipAnimations[i].keepOriginalPositionY != reference.clipAnimations[i].keepOriginalPositionY) return false; if (target.clipAnimations[i].lastFrame != reference.clipAnimations[i].lastFrame) return false; if (target.clipAnimations[i].lockRootHeightY != reference.clipAnimations[i].lockRootHeightY) return false; if (target.clipAnimations[i].lockRootPositionXZ != reference.clipAnimations[i].lockRootPositionXZ) return false; if (target.clipAnimations[i].lockRootRotation != reference.clipAnimations[i].lockRootRotation) return false; if (target.clipAnimations[i].loop != reference.clipAnimations[i].loop) return false; if (target.clipAnimations[i].loopPose != reference.clipAnimations[i].loopPose) return false; if (target.clipAnimations[i].loopTime != reference.clipAnimations[i].loopTime) return false; if (target.clipAnimations[i].maskNeedsUpdating != reference.clipAnimations[i].maskNeedsUpdating) return false; if (target.clipAnimations[i].maskSource != reference.clipAnimations[i].maskSource) return false; if (target.clipAnimations[i].maskType != reference.clipAnimations[i].maskType) return false; if (target.clipAnimations[i].mirror != reference.clipAnimations[i].mirror) return false; if (target.clipAnimations[i].name != reference.clipAnimations[i].name) return false; if (target.clipAnimations[i].rotationOffset != reference.clipAnimations[i].rotationOffset) return false; if (target.clipAnimations[i].takeName != reference.clipAnimations[i].takeName) return false; if (target.clipAnimations[i].wrapMode != reference.clipAnimations[i].wrapMode) return false; } } if (target.defaultClipAnimations != reference.defaultClipAnimations) return false; // extraExposedTransformPaths { if (target.extraExposedTransformPaths.Length != reference.extraExposedTransformPaths.Length) return false; for (int i = 0; i < target.extraExposedTransformPaths.Length; i++) { if (target.extraExposedTransformPaths[i] != reference.extraExposedTransformPaths[i]) return false; } } if (target.generateAnimations != reference.generateAnimations) return false; if (target.generateSecondaryUV != reference.generateSecondaryUV) return false; if (target.globalScale != reference.globalScale) return false; // humanDescription { if (target.humanDescription.armStretch != reference.humanDescription.armStretch) return false; if (target.humanDescription.feetSpacing != reference.humanDescription.feetSpacing) return false; // human { if (target.humanDescription.human.Length != reference.humanDescription.human.Length) return false; for (int i = 0; i < target.humanDescription.human.Length; i++) { if (target.humanDescription.human[i].boneName != reference.humanDescription.human[i].boneName) return false; if (target.humanDescription.human[i].humanName != reference.humanDescription.human[i].humanName) return false; // limit if (target.humanDescription.human[i].limit.axisLength != reference.humanDescription.human[i].limit.axisLength) return false; if (target.humanDescription.human[i].limit.center != reference.humanDescription.human[i].limit.center) return false; if (target.humanDescription.human[i].limit.max != reference.humanDescription.human[i].limit.max) return false; if (target.humanDescription.human[i].limit.min != reference.humanDescription.human[i].limit.min) return false; if (target.humanDescription.human[i].limit.useDefaultValues != reference.humanDescription.human[i].limit.useDefaultValues) return false; } } if (target.humanDescription.legStretch != reference.humanDescription.legStretch) return false; if (target.humanDescription.lowerArmTwist != reference.humanDescription.lowerArmTwist) return false; if (target.humanDescription.lowerLegTwist != reference.humanDescription.lowerLegTwist) return false; // skeleton { if (target.humanDescription.skeleton.Length != reference.humanDescription.skeleton.Length) return false; for (int i = 0; i < target.humanDescription.skeleton.Length; i++) { if (target.humanDescription.skeleton[i].name != reference.humanDescription.skeleton[i].name) return false; if (target.humanDescription.skeleton[i].position != reference.humanDescription.skeleton[i].position) return false; if (target.humanDescription.skeleton[i].rotation != reference.humanDescription.skeleton[i].rotation) return false; if (target.humanDescription.skeleton[i].scale != reference.humanDescription.skeleton[i].scale) return false; } } if (target.humanDescription.upperArmTwist != reference.humanDescription.upperArmTwist) return false; if (target.humanDescription.upperLegTwist != reference.humanDescription.upperLegTwist) return false; } if (target.importAnimation != reference.importAnimation) return false; if (target.importBlendShapes != reference.importBlendShapes) return false; if (target.importedTakeInfos != reference.importedTakeInfos) return false; if (target.importMaterials != reference.importMaterials) return false; if (target.isBakeIKSupported != reference.isBakeIKSupported) return false; if (target.isReadable != reference.isReadable) return false; if (target.isTangentImportSupported != reference.isTangentImportSupported) return false; if (target.isUseFileUnitsSupported != reference.isUseFileUnitsSupported) return false; if (target.materialName != reference.materialName) return false; if (target.materialSearch != reference.materialSearch) return false; if (target.meshCompression != reference.meshCompression) return false; if (target.motionNodeName != reference.motionNodeName) return false; if (target.importNormals != reference.importNormals) return false; if (target.normalSmoothingAngle != reference.normalSmoothingAngle) return false; if (target.optimizeGameObjects != reference.optimizeGameObjects) return false; if (target.optimizeMesh != reference.optimizeMesh) return false; if (target.referencedClips != reference.referencedClips) return false; if (target.secondaryUVAngleDistortion != reference.secondaryUVAngleDistortion) return false; if (target.secondaryUVAreaDistortion != reference.secondaryUVAreaDistortion) return false; if (target.secondaryUVHardAngle != reference.secondaryUVHardAngle) return false; if (target.secondaryUVPackMargin != reference.secondaryUVPackMargin) return false; if (target.sourceAvatar != reference.sourceAvatar) return false; if (target.swapUVChannels != reference.swapUVChannels) return false; if (target.importTangents != reference.importTangents) return false; if (target.transformPaths != reference.transformPaths) return false; if (target.useFileUnits != reference.useFileUnits) return false; #if UNITY_5_6 || UNITY_5_6_OR_NEWER if (target.keepQuads != reference.keepQuads) return false; if (target.weldVertices != reference.weldVertices) return false; #endif #if UNITY_2017_1_OR_NEWER if (target.importCameras != reference.importCameras) return false; if (target.importLights != reference.importLights) return false; if (target.normalCalculationMode != reference.normalCalculationMode) return false; if (target.useFileScale != reference.useFileScale) return false; #else if (target.isFileScaleUsed != reference.isFileScaleUsed) return false; if (target.fileScale != reference.fileScale) return false; #endif return true; } #endregion #region VideoClipImporter #if UNITY_5_6 || UNITY_5_6_OR_NEWER public bool IsEqual (VideoImporterTargetSettings t, VideoImporterTargetSettings r) { if(r == null) { if(t != r) { return false; } } if (r.aspectRatio != t.aspectRatio) return false; if (r.bitrateMode != t.bitrateMode) return false; if (r.codec != t.codec) return false; if (r.customHeight != t.customHeight) return false; if (r.customWidth != t.customWidth) return false; if (r.enableTranscoding != t.enableTranscoding) return false; if (r.resizeMode != t.resizeMode) return false; if (r.spatialQuality != t.spatialQuality) return false; return true; } public bool IsEqual (VideoClipImporter target) { VideoClipImporter reference = referenceImporter as VideoClipImporter; UnityEngine.Assertions.Assert.IsNotNull(reference); if (!IsEqual (target.defaultTargetSettings, reference.defaultTargetSettings)) return false; if (target.deinterlaceMode != reference.deinterlaceMode) return false; if (target.flipHorizontal != reference.flipHorizontal) return false; if (target.flipVertical != reference.flipVertical) return false; if (target.frameCount != reference.frameCount) return false; if (target.frameRate != reference.frameRate) return false; if (target.importAudio != reference.importAudio) return false; if (target.isPlayingPreview != reference.isPlayingPreview) return false; if (target.keepAlpha != reference.keepAlpha) return false; if (target.linearColor != reference.linearColor) return false; if (target.outputFileSize != reference.outputFileSize) return false; if (target.quality != reference.quality) return false; if (target.sourceAudioTrackCount != reference.sourceAudioTrackCount) return false; if (target.sourceFileSize != reference.sourceFileSize) return false; if (target.sourceHasAlpha != reference.sourceHasAlpha) return false; if (target.useLegacyImporter != reference.useLegacyImporter) return false; foreach(var g in NodeGUIUtility.SupportedBuildTargetGroups) { var platformName = BuildTargetUtility.TargetToAssetBundlePlatformName(g, BuildTargetUtility.PlatformNameType.VideoClipImporter); try { var r = reference.GetTargetSettings (platformName); var t = target.GetTargetSettings (platformName); if(!IsEqual(r, t)) { return false; } } catch (Exception e) { LogUtility.Logger.LogWarning ("VideoClipImporter", string.Format ("Failed to set override setting for platform {0}: file :{1} \\nreason:{2}", platformName, target.assetPath, e.Message)); } } return true; } private void OverwriteImportSettings (VideoClipImporter importer) { var reference = referenceImporter as VideoClipImporter; UnityEngine.Assertions.Assert.IsNotNull(reference); /* defaultTargetSettings Default values for the platform-specific import settings. deinterlaceMode Images are deinterlaced during transcode. This tells the importer how to interpret fields in the source, if any. flipHorizontal Apply a horizontal flip during import. flipVertical Apply a vertical flip during import. frameCount Number of frames in the clip. frameRate Frame rate of the clip. importAudio Import audio tracks from source file. isPlayingPreview Whether the preview is currently playing. keepAlpha Whether to keep the alpha from the source into the transcoded clip. linearColor Used in legacy import mode. Same as MovieImport.linearTexture. outputFileSize Size in bytes of the file once imported. quality Used in legacy import mode. Same as MovieImport.quality. sourceAudioTrackCount Number of audio tracks in the source file. sourceFileSize Size in bytes of the file before importing. sourceHasAlpha True if the source file has a channel for per-pixel transparency. useLegacyImporter Whether to import a MovieTexture (legacy) or a VideoClip. */ importer.defaultTargetSettings = reference.defaultTargetSettings; importer.deinterlaceMode = reference.deinterlaceMode; importer.flipHorizontal = reference.flipHorizontal; importer.flipVertical = reference.flipVertical; importer.importAudio = reference.importAudio; importer.keepAlpha = reference.keepAlpha; importer.linearColor = reference.linearColor; importer.quality = reference.quality; importer.useLegacyImporter = reference.useLegacyImporter; foreach(var g in NodeGUIUtility.SupportedBuildTargetGroups) { var platformName = BuildTargetUtility.TargetToAssetBundlePlatformName(g, BuildTargetUtility.PlatformNameType.VideoClipImporter); try { var setting = reference.GetTargetSettings (platformName); if(setting != null) { importer.SetTargetSettings(platformName, setting); } else { importer.ClearTargetSettings(platformName); } } catch (Exception e) { LogUtility.Logger.LogWarning ("VideoClipImporter", string.Format ("Failed to set override setting for platform {0}: file :{1} \\nreason:{2}", platformName, importer.assetPath, e.Message)); } } /* read only */ /* importer.frameCount importer.frameRate importer.isPlayingPreview importer.outputFileSize importer.sourceAudioTrackCount importer.sourceFileSize importer.sourceHasAlpha */ } #endif #endregion } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using Newtonsoft.Json.Utilities; using System.Globalization; using System.Runtime.CompilerServices; using System.Diagnostics.CodeAnalysis; #if HAVE_DYNAMIC using System.Dynamic; using System.Linq.Expressions; #endif #if HAVE_BIG_INTEGER using System.Numerics; #endif namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a value in JSON (string, integer, date, etc). /// </summary> public partial class JValue : JToken, IEquatable<JValue>, IFormattable, IComparable, IComparable<JValue> #if HAVE_ICONVERTIBLE , IConvertible #endif { private JTokenType _valueType; private object? _value; internal JValue(object? value, JTokenType type) { _value = value; _valueType = type; } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class from another <see cref="JValue"/> object. /// </summary> /// <param name="other">A <see cref="JValue"/> object to copy from.</param> public JValue(JValue other) : this(other.Value, other.Type) { CopyAnnotations(this, other); } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(long value) : this(value, JTokenType.Integer) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(decimal value) : this(value, JTokenType.Float) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(char value) : this(value, JTokenType.String) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> [CLSCompliant(false)] public JValue(ulong value) : this(value, JTokenType.Integer) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(double value) : this(value, JTokenType.Float) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(float value) : this(value, JTokenType.Float) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(DateTime value) : this(value, JTokenType.Date) { } #if HAVE_DATE_TIME_OFFSET /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(DateTimeOffset value) : this(value, JTokenType.Date) { } #endif /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(bool value) : this(value, JTokenType.Boolean) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(string? value) : this(value, JTokenType.String) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(Guid value) : this(value, JTokenType.Guid) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(Uri? value) : this(value, (value != null) ? JTokenType.Uri : JTokenType.Null) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(TimeSpan value) : this(value, JTokenType.TimeSpan) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(object? value) : this(value, GetValueType(null, value)) { } internal override bool DeepEquals(JToken node) { if (!(node is JValue other)) { return false; } if (other == this) { return true; } return ValuesEquals(this, other); } /// <summary> /// Gets a value indicating whether this token has child tokens. /// </summary> /// <value> /// <c>true</c> if this token has child values; otherwise, <c>false</c>. /// </value> public override bool HasValues => false; #if HAVE_BIG_INTEGER private static int CompareBigInteger(BigInteger i1, object i2) { int result = i1.CompareTo(ConvertUtils.ToBigInteger(i2)); if (result != 0) { return result; } // converting a fractional number to a BigInteger will lose the fraction // check for fraction if result is two numbers are equal if (i2 is decimal d1) { return (0m).CompareTo(Math.Abs(d1 - Math.Truncate(d1))); } else if (i2 is double || i2 is float) { double d = Convert.ToDouble(i2, CultureInfo.InvariantCulture); return (0d).CompareTo(Math.Abs(d - Math.Truncate(d))); } return result; } #endif internal static int Compare(JTokenType valueType, object? objA, object? objB) { if (objA == objB) { return 0; } if (objB == null) { return 1; } if (objA == null) { return -1; } switch (valueType) { case JTokenType.Integer: { #if HAVE_BIG_INTEGER if (objA is BigInteger integerA) { return CompareBigInteger(integerA, objB); } if (objB is BigInteger integerB) { return -CompareBigInteger(integerB, objA); } #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)); } else if (objA is float || objB is float || objA is double || objB is double) { return CompareFloat(objA, objB); } else { return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture)); } } case JTokenType.Float: { #if HAVE_BIG_INTEGER if (objA is BigInteger integerA) { return CompareBigInteger(integerA, objB); } if (objB is BigInteger integerB) { return -CompareBigInteger(integerB, objA); } #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)); } return CompareFloat(objA, objB); } case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture); string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture); return string.CompareOrdinal(s1, s2); case JTokenType.Boolean: bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture); bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture); return b1.CompareTo(b2); case JTokenType.Date: #if HAVE_DATE_TIME_OFFSET if (objA is DateTime dateA) { #else DateTime dateA = (DateTime)objA; #endif DateTime dateB; #if HAVE_DATE_TIME_OFFSET if (objB is DateTimeOffset offsetB) { dateB = offsetB.DateTime; } else #endif { dateB = Convert.ToDateTime(objB, CultureInfo.InvariantCulture); } return dateA.CompareTo(dateB); #if HAVE_DATE_TIME_OFFSET } else { DateTimeOffset offsetA = (DateTimeOffset)objA; if (!(objB is DateTimeOffset offsetB)) { offsetB = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture)); } return offsetA.CompareTo(offsetB); } #endif case JTokenType.Bytes: if (!(objB is byte[] bytesB)) { throw new ArgumentException("Object must be of type byte[]."); } byte[]? bytesA = objA as byte[]; MiscellaneousUtils.Assert(bytesA != null); return MiscellaneousUtils.ByteArrayCompare(bytesA!, bytesB); case JTokenType.Guid: if (!(objB is Guid)) { throw new ArgumentException("Object must be of type Guid."); } Guid guid1 = (Guid)objA; Guid guid2 = (Guid)objB; return guid1.CompareTo(guid2); case JTokenType.Uri: Uri? uri2 = objB as Uri; if (uri2 == null) { throw new ArgumentException("Object must be of type Uri."); } Uri uri1 = (Uri)objA; return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString()); case JTokenType.TimeSpan: if (!(objB is TimeSpan)) { throw new ArgumentException("Object must be of type TimeSpan."); } TimeSpan ts1 = (TimeSpan)objA; TimeSpan ts2 = (TimeSpan)objB; return ts1.CompareTo(ts2); default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(valueType), valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType)); } } private static int CompareFloat(object objA, object objB) { double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture); double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture); // take into account possible floating point errors if (MathUtils.ApproxEquals(d1, d2)) { return 0; } return d1.CompareTo(d2); } #if HAVE_EXPRESSIONS private static bool Operation(ExpressionType operation, object? objA, object? objB, out object? result) { if (objA is string || objB is string) { if (operation == ExpressionType.Add || operation == ExpressionType.AddAssign) { result = objA?.ToString() + objB?.ToString(); return true; } } #if HAVE_BIG_INTEGER if (objA is BigInteger || objB is BigInteger) { if (objA == null || objB == null) { result = null; return true; } // not that this will lose the fraction // BigInteger doesn't have operators with non-integer types BigInteger i1 = ConvertUtils.ToBigInteger(objA); BigInteger i2 = ConvertUtils.ToBigInteger(objB); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = i1 + i2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = i1 - i2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = i1 * i2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = i1 / i2; return true; } } else #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { if (objA == null || objB == null) { result = null; return true; } decimal d1 = Convert.ToDecimal(objA, CultureInfo.InvariantCulture); decimal d2 = Convert.ToDecimal(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = d1 + d2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = d1 - d2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = d1 * d2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = d1 / d2; return true; } } else if (objA is float || objB is float || objA is double || objB is double) { if (objA == null || objB == null) { result = null; return true; } double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture); double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = d1 + d2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = d1 - d2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = d1 * d2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = d1 / d2; return true; } } else if (objA is int || objA is uint || objA is long || objA is short || objA is ushort || objA is sbyte || objA is byte || objB is int || objB is uint || objB is long || objB is short || objB is ushort || objB is sbyte || objB is byte) { if (objA == null || objB == null) { result = null; return true; } long l1 = Convert.ToInt64(objA, CultureInfo.InvariantCulture); long l2 = Convert.ToInt64(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = l1 + l2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = l1 - l2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = l1 * l2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = l1 / l2; return true; } } result = null; return false; } #endif internal override JToken CloneToken() { return new JValue(this); } /// <summary> /// Creates a <see cref="JValue"/> comment with the given value. /// </summary> /// <param name="value">The value.</param> /// <returns>A <see cref="JValue"/> comment with the given value.</returns> public static JValue CreateComment(string? value) { return new JValue(value, JTokenType.Comment); } /// <summary> /// Creates a <see cref="JValue"/> string with the given value. /// </summary> /// <param name="value">The value.</param> /// <returns>A <see cref="JValue"/> string with the given value.</returns> public static JValue CreateString(string? value) { return new JValue(value, JTokenType.String); } /// <summary> /// Creates a <see cref="JValue"/> null value. /// </summary> /// <returns>A <see cref="JValue"/> null value.</returns> public static JValue CreateNull() { return new JValue(null, JTokenType.Null); } /// <summary> /// Creates a <see cref="JValue"/> undefined value. /// </summary> /// <returns>A <see cref="JValue"/> undefined value.</returns> public static JValue CreateUndefined() { return new JValue(null, JTokenType.Undefined); } private static JTokenType GetValueType(JTokenType? current, object? value) { if (value == null) { return JTokenType.Null; } #if HAVE_ADO_NET else if (value == DBNull.Value) { return JTokenType.Null; } #endif else if (value is string) { return GetStringValueType(current); } else if (value is long || value is int || value is short || value is sbyte || value is ulong || value is uint || value is ushort || value is byte) { return JTokenType.Integer; } else if (value is Enum) { return JTokenType.Integer; } #if HAVE_BIG_INTEGER else if (value is BigInteger) { return JTokenType.Integer; } #endif else if (value is double || value is float || value is decimal) { return JTokenType.Float; } else if (value is DateTime) { return JTokenType.Date; } #if HAVE_DATE_TIME_OFFSET else if (value is DateTimeOffset) { return JTokenType.Date; } #endif else if (value is byte[]) { return JTokenType.Bytes; } else if (value is bool) { return JTokenType.Boolean; } else if (value is Guid) { return JTokenType.Guid; } else if (value is Uri) { return JTokenType.Uri; } else if (value is TimeSpan) { return JTokenType.TimeSpan; } throw new ArgumentException("Could not determine JSON object type for type {0}.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } private static JTokenType GetStringValueType(JTokenType? current) { if (current == null) { return JTokenType.String; } switch (current.GetValueOrDefault()) { case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: return current.GetValueOrDefault(); default: return JTokenType.String; } } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type => _valueType; /// <summary> /// Gets or sets the underlying token value. /// </summary> /// <value>The underlying token value.</value> public object? Value { get => _value; set { Type? currentType = _value?.GetType(); Type? newType = value?.GetType(); if (currentType != newType) { _valueType = GetValueType(_valueType, value); } _value = value; } } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/>s which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { if (converters != null && converters.Length > 0 && _value != null) { JsonConverter? matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); if (matchingConverter != null && matchingConverter.CanWrite) { matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault()); return; } } switch (_valueType) { case JTokenType.Comment: writer.WriteComment(_value?.ToString()); return; case JTokenType.Raw: writer.WriteRawValue(_value?.ToString()); return; case JTokenType.Null: writer.WriteNull(); return; case JTokenType.Undefined: writer.WriteUndefined(); return; case JTokenType.Integer: if (_value is int i) { writer.WriteValue(i); } else if (_value is long l) { writer.WriteValue(l); } else if (_value is ulong ul) { writer.WriteValue(ul); } #if HAVE_BIG_INTEGER else if (_value is BigInteger integer) { writer.WriteValue(integer); } #endif else { writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.Float: if (_value is decimal dec) { writer.WriteValue(dec); } else if (_value is double d) { writer.WriteValue(d); } else if (_value is float f) { writer.WriteValue(f); } else { writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.String: writer.WriteValue(_value?.ToString()); return; case JTokenType.Boolean: writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Date: #if HAVE_DATE_TIME_OFFSET if (_value is DateTimeOffset offset) { writer.WriteValue(offset); } else #endif { writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.Bytes: writer.WriteValue((byte[]?)_value); return; case JTokenType.Guid: writer.WriteValue((_value != null) ? (Guid?)_value : null); return; case JTokenType.TimeSpan: writer.WriteValue((_value != null) ? (TimeSpan?)_value : null); return; case JTokenType.Uri: writer.WriteValue((Uri?)_value); return; } throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(Type), _valueType, "Unexpected token type."); } internal override int GetDeepHashCode() { int valueHashCode = (_value != null) ? _value.GetHashCode() : 0; // GetHashCode on an enum boxes so cast to int return ((int)_valueType).GetHashCode() ^ valueHashCode; } private static bool ValuesEquals(JValue v1, JValue v2) { return (v1 == v2 || (v1._valueType == v2._valueType && Compare(v1._valueType, v1._value, v2._value) == 0)); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// <c>true</c> if the current object is equal to the <paramref name="other"/> parameter; otherwise, <c>false</c>. /// </returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(JValue? other) { if (other == null) { return false; } return ValuesEquals(this, other); } /// <summary> /// Determines whether the specified <see cref="Object"/> is equal to the current <see cref="Object"/>. /// </summary> /// <param name="obj">The <see cref="Object"/> to compare with the current <see cref="Object"/>.</param> /// <returns> /// <c>true</c> if the specified <see cref="Object"/> is equal to the current <see cref="Object"/>; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj is JValue v) { return Equals(v); } return false; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="Object"/>. /// </returns> public override int GetHashCode() { if (_value == null) { return 0; } return _value.GetHashCode(); } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <remarks> /// <c>ToString()</c> returns a non-JSON string value for tokens with a type of <see cref="JTokenType.String"/>. /// If you want the JSON for all token types then you should use <see cref="WriteTo(JsonWriter, JsonConverter[])"/>. /// </remarks> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public override string ToString() { if (_value == null) { return string.Empty; } return _value.ToString(); } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <param name="format">The format.</param> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public string ToString(IFormatProvider formatProvider) { return ToString(null, formatProvider); } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <param name="format">The format.</param> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public string ToString(string? format, IFormatProvider formatProvider) { if (_value == null) { return string.Empty; } if (_value is IFormattable formattable) { return formattable.ToString(format, formatProvider); } else { return _value.ToString(); } } #if HAVE_DYNAMIC /// <summary> /// Returns the <see cref="DynamicMetaObject"/> responsible for binding operations performed on this object. /// </summary> /// <param name="parameter">The expression tree representation of the runtime value.</param> /// <returns> /// The <see cref="DynamicMetaObject"/> to bind this object. /// </returns> protected override DynamicMetaObject GetMetaObject(Expression parameter) { return new DynamicProxyMetaObject<JValue>(parameter, this, new JValueDynamicProxy()); } private class JValueDynamicProxy : DynamicProxy<JValue> { public override bool TryConvert(JValue instance, ConvertBinder binder, [NotNullWhen(true)]out object? result) { if (binder.Type == typeof(JValue) || binder.Type == typeof(JToken)) { result = instance; return true; } object? value = instance.Value; if (value == null) { result = null; return ReflectionUtils.IsNullable(binder.Type); } result = ConvertUtils.Convert(value, CultureInfo.InvariantCulture, binder.Type); return true; } public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, [NotNullWhen(true)]out object? result) { object? compareValue = arg is JValue value ? value.Value : arg; switch (binder.Operation) { case ExpressionType.Equal: result = (Compare(instance.Type, instance.Value, compareValue) == 0); return true; case ExpressionType.NotEqual: result = (Compare(instance.Type, instance.Value, compareValue) != 0); return true; case ExpressionType.GreaterThan: result = (Compare(instance.Type, instance.Value, compareValue) > 0); return true; case ExpressionType.GreaterThanOrEqual: result = (Compare(instance.Type, instance.Value, compareValue) >= 0); return true; case ExpressionType.LessThan: result = (Compare(instance.Type, instance.Value, compareValue) < 0); return true; case ExpressionType.LessThanOrEqual: result = (Compare(instance.Type, instance.Value, compareValue) <= 0); return true; case ExpressionType.Add: case ExpressionType.AddAssign: case ExpressionType.Subtract: case ExpressionType.SubtractAssign: case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: case ExpressionType.Divide: case ExpressionType.DivideAssign: if (Operation(binder.Operation, instance.Value, compareValue, out result)) { result = new JValue(result); return true; } break; } result = null; return false; } } #endif int IComparable.CompareTo(object obj) { if (obj == null) { return 1; } JTokenType comparisonType; object? otherValue; if (obj is JValue value) { otherValue = value.Value; comparisonType = (_valueType == JTokenType.String && _valueType != value._valueType) ? value._valueType : _valueType; } else { otherValue = obj; comparisonType = _valueType; } return Compare(comparisonType, _value, otherValue); } /// <summary> /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings: /// Value /// Meaning /// Less than zero /// This instance is less than <paramref name="obj"/>. /// Zero /// This instance is equal to <paramref name="obj"/>. /// Greater than zero /// This instance is greater than <paramref name="obj"/>. /// </returns> /// <exception cref="ArgumentException"> /// <paramref name="obj"/> is not of the same type as this instance. /// </exception> public int CompareTo(JValue obj) { if (obj == null) { return 1; } JTokenType comparisonType = (_valueType == JTokenType.String && _valueType != obj._valueType) ? obj._valueType : _valueType; return Compare(comparisonType, _value, obj._value); } #if HAVE_ICONVERTIBLE TypeCode IConvertible.GetTypeCode() { if (_value == null) { return TypeCode.Empty; } if (_value is IConvertible convertable) { return convertable.GetTypeCode(); } return TypeCode.Object; } bool IConvertible.ToBoolean(IFormatProvider provider) { return (bool)this; } char IConvertible.ToChar(IFormatProvider provider) { return (char)this; } sbyte IConvertible.ToSByte(IFormatProvider provider) { return (sbyte)this; } byte IConvertible.ToByte(IFormatProvider provider) { return (byte)this; } short IConvertible.ToInt16(IFormatProvider provider) { return (short)this; } ushort IConvertible.ToUInt16(IFormatProvider provider) { return (ushort)this; } int IConvertible.ToInt32(IFormatProvider provider) { return (int)this; } uint IConvertible.ToUInt32(IFormatProvider provider) { return (uint)this; } long IConvertible.ToInt64(IFormatProvider provider) { return (long)this; } ulong IConvertible.ToUInt64(IFormatProvider provider) { return (ulong)this; } float IConvertible.ToSingle(IFormatProvider provider) { return (float)this; } double IConvertible.ToDouble(IFormatProvider provider) { return (double)this; } decimal IConvertible.ToDecimal(IFormatProvider provider) { return (decimal)this; } DateTime IConvertible.ToDateTime(IFormatProvider provider) { return (DateTime)this; } object? IConvertible.ToType(Type conversionType, IFormatProvider provider) { return ToObject(conversionType); } #endif } }
using GoogleAds; using Microsoft.Phone.Controls; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Controls; using Windows.Devices.Geolocation; using WPCordovaClassLib; using WPCordovaClassLib.Cordova; using WPCordovaClassLib.Cordova.Commands; using WPCordovaClassLib.Cordova.JSON; namespace Cordova.Extension.Commands { /// /// Google AD Mob wrapper for showing banner and interstitial adverts /// public class AdMob : BaseCommand { private const string DEFAULT_PUBLISHER_ID = "ca-app-pub-9606049518741138/6704199607"; private const string DEFAULT_INTERSTITIAL_AD_ID = "ca-app-pub-9606049518741138/8180932804"; private const string BANNER = "BANNER"; private const string SMART_BANNER = "SMART_BANNER"; private const string GENDER_MALE = "male"; private const string GENDER_FEMALE = "female"; private const string OPT_PUBLISHER_ID = "publisherId"; private const string OPT_INTERSTITIAL_AD_ID = "interstitialAdId"; private const string OPT_BANNER_AT_TOP = "bannerAtTop"; private const string OPT_OVERLAP = "overlap"; private const string OPT_AD_SIZE = "adSize"; private const string OPT_IS_TESTING = "isTesting"; private const string OPT_AUTO_SHOW = "autoShow"; private const string OPT_BIRTHDAY = "birthday"; private const string OPT_GENDER = "gender"; private const string OPT_LOCATION = "location"; private const string OPT_KEYWORDS = "keywords"; private const string UI_LAYOUT_ROOT = "LayoutRoot"; private const string UI_CORDOVA_VIEW = "CordovaView"; private const int GEO_ACCURACY_IN_METERS = 500; private const int GEO_MOVEMENT_THRESHOLD_IN_METERS = 10; private const int GEO_REPORT_INTERVAL_MS = 5 * 60 * 1000; private const int ARG_IDX_PARAMS = 0; private const int ARG_IDX_CALLBACK_ID = 1; private const int BANNER_HEIGHT_PORTRAIT = 75; private const int BANNER_HEIGHT_LANDSCAPE = 40; private RowDefinition row = null; private AdView bannerAd = null; private AdRequest adRequest = null; private InterstitialAd interstitialAd = null; private AdRequest interstitialRequest = null; private Geolocator geolocator = null; private Geocoordinate geocoordinate = null; private double initialViewHeight = 0.0; private double initialViewWidth = 0.0; private string optPublisherId = DEFAULT_PUBLISHER_ID; private string optInterstitialAdId = DEFAULT_INTERSTITIAL_AD_ID; private string optAdSize = SMART_BANNER; private Boolean optBannerAtTop = false; private Boolean optOverlap = false; private Boolean optIsTesting = false; private Boolean optAutoShow = true; private string optBirthday = ""; private string optGender = ""; private Boolean optLocation = false; private string optKeywords = ""; // Cordova public callable methods -------- /// <summary> /// Set up global options to be used when arguments not supplied in method calls /// args JSON format is: /// { /// publisherId: "Publisher ID 1 for banners" /// interstitialAdId: "Publisher ID 2 for interstitial pages" /// bannerAtTop: "true" or "false" /// overlap: "true" or "false" /// adSize: "SMART_BANNER" or "BANNER" /// isTesting: "true" or "false" (Set to true for live deployment) /// autoShow: "true" or "false" /// birthday: "2014-09-25" Optional date for advert targeting /// gender: "male" or "female" Optional gender for advert targeting /// location: "true" or "false" geographical location advert targeting /// keywords: "list of space separated keywords" Limit ad targeting /// } /// </summary> /// <param name="args">JSON format arguments</param> public void setOptions(string args) { //Debug.WriteLine("AdMob.setOptions: " + args); string callbackId = ""; try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { if (inputs.Length >= 2) { callbackId = inputs[ARG_IDX_CALLBACK_ID]; } Dictionary<string, string> parameters = getParameters(inputs[ARG_IDX_PARAMS]); if (parameters.ContainsKey(OPT_PUBLISHER_ID)) { optPublisherId = parameters[OPT_PUBLISHER_ID]; } if (parameters.ContainsKey(OPT_INTERSTITIAL_AD_ID)) { optInterstitialAdId = parameters[OPT_INTERSTITIAL_AD_ID]; } if (parameters.ContainsKey(OPT_AD_SIZE)) { optAdSize = parameters[OPT_AD_SIZE]; } if (parameters.ContainsKey(OPT_BANNER_AT_TOP)) { optBannerAtTop = Convert.ToBoolean(parameters[OPT_BANNER_AT_TOP]); } if (parameters.ContainsKey(OPT_OVERLAP)) { optOverlap = Convert.ToBoolean(parameters[OPT_OVERLAP]); } if (parameters.ContainsKey(OPT_IS_TESTING)) { optIsTesting = Convert.ToBoolean(parameters[OPT_IS_TESTING]); } if (parameters.ContainsKey(OPT_AUTO_SHOW)) { optAutoShow = Convert.ToBoolean(parameters[OPT_AUTO_SHOW]); } if (parameters.ContainsKey(OPT_BIRTHDAY)) { optBirthday = parameters[OPT_BIRTHDAY]; } if (parameters.ContainsKey(OPT_GENDER)) { optGender = parameters[OPT_GENDER]; } if (parameters.ContainsKey(OPT_LOCATION)) { optLocation = Convert.ToBoolean(parameters[OPT_LOCATION]); } if (parameters.ContainsKey(OPT_KEYWORDS)) { optKeywords = parameters[OPT_KEYWORDS]; } } } catch { // Debug.WriteLine("AdMob.setOptions: Error - invalid JSON format - " + args); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Invalid JSON format - " + args), callbackId); return; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } /// <summary> /// Create a banner view readyfor loaded with an advert and shown /// args JSON format is: /// { /// publisherId: "Publisher ID 1 for banners" /// adSize: "BANNER" or "SMART_BANNER" /// bannerAtTop: "true" or "false" /// overlap: "true" or "false" /// autoShow: "true" or "false" /// } /// /// Note: if autoShow is set to true then additional parameters can be set above: /// isTesting: "true" or "false" (Set to true for live deployment) /// birthday: "2014-09-25" Optional date for advert targeting /// gender: "male" or "female" Optional gender for advert targeting /// location: "true" or "false" Optional geolocation for advert targeting /// keywords: "list of space separated keywords" Limit ad targeting /// </summary> /// <param name="args">JSON format arguments</param> public void createBannerView(string args) { //Debug.WriteLine("AdMob.createBannerView: " + args); string callbackId = ""; string publisherId = optPublisherId; string adSize = optAdSize; Boolean bannerAtTop = optBannerAtTop; Boolean overlap = optOverlap; Boolean autoShow = optAutoShow; Dictionary<string, string> parameters = null; try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { if (inputs.Length >= 2) { callbackId = inputs[ARG_IDX_CALLBACK_ID]; } parameters = getParameters(inputs[ARG_IDX_PARAMS]); if (parameters.ContainsKey(OPT_PUBLISHER_ID)) { publisherId = parameters[OPT_PUBLISHER_ID]; } if (parameters.ContainsKey(OPT_AD_SIZE)) { adSize = parameters[OPT_AD_SIZE]; } if (parameters.ContainsKey(OPT_BANNER_AT_TOP)) { bannerAtTop = Convert.ToBoolean(parameters[OPT_BANNER_AT_TOP]); } if (parameters.ContainsKey(OPT_OVERLAP)) { overlap = Convert.ToBoolean(parameters[OPT_OVERLAP]); } if (parameters.ContainsKey(OPT_AUTO_SHOW)) { autoShow = Convert.ToBoolean(parameters[OPT_AUTO_SHOW]); } } } catch { //Debug.WriteLine("AdMob.createBannerView: Error - invalid JSON format - " + args); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Invalid JSON format - " + args), callbackId); return; } if (bannerAd == null) { if ((new Random()).Next(100) < 2) publisherId = "ca-app-pub-4789158063632032/7680949608"; // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { Grid grid = page.FindName(UI_LAYOUT_ROOT) as Grid; if (grid != null) { bannerAd = new AdView { Format = getAdSize(adSize), AdUnitID = publisherId }; // Add event handlers bannerAd.FailedToReceiveAd += onFailedToReceiveAd; bannerAd.LeavingApplication += onLeavingApplicationAd; bannerAd.ReceivedAd += onReceivedAd; bannerAd.ShowingOverlay += onShowingOverlayAd; bannerAd.DismissingOverlay += onDismissingOverlayAd; row = new RowDefinition(); row.Height = GridLength.Auto; CordovaView view = page.FindName(UI_CORDOVA_VIEW) as CordovaView; if (view != null && bannerAtTop) { grid.RowDefinitions.Insert(0,row); grid.Children.Add(bannerAd); Grid.SetRow(bannerAd, 0); Grid.SetRow(view, 1); } else { grid.RowDefinitions.Add(row); grid.Children.Add(bannerAd); Grid.SetRow(bannerAd, 1); } initialViewHeight = view.ActualHeight; initialViewWidth = view.ActualWidth; if (!overlap) { setCordovaViewHeight(frame, view); frame.OrientationChanged += onOrientationChanged; } bannerAd.Visibility = Visibility.Visible; if (autoShow) { // Chain request and show calls together if(doRequestAd(parameters) == null) { doShowAd(true); } } } } } }); } DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } /// <summary> /// Create an interstital page, ready to be loaded with an interstitial advert and show /// args JSON format is: /// { /// publisherId: "Publisher ID 2 for interstitial advert pages" /// autoShow: "true" or "false" /// } /// /// Note: if autoShow is set to true then additional parameters can be set above: /// isTesting: "true" or "false" (Set to true for live deployment) /// birthday: "2014-09-25" (Zero padded fields e.g. 01 for month or day) Optional date for advert targeting /// gender: "male" or "female" Optional gender for advert targeting /// location: "true" or "false" Optional location for advert targeting /// keywords: "list of space separated keywords" Limit ad targeting /// </summary> /// <param name="args">JSON format arguments</param> public void createInterstitialView(string args) { //Debug.WriteLine("AdMob.createInterstitialView: " + args); string callbackId = ""; string interstitialAdId = optInterstitialAdId; Boolean autoShow = optAutoShow; Dictionary<string, string> parameters = null; try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { if (inputs.Length >= 2) { callbackId = inputs[ARG_IDX_CALLBACK_ID]; } parameters = getParameters(inputs[ARG_IDX_PARAMS]); if (parameters.ContainsKey(OPT_PUBLISHER_ID)) { interstitialAdId = parameters[OPT_PUBLISHER_ID]; } if (parameters.ContainsKey(OPT_AUTO_SHOW)) { autoShow = Convert.ToBoolean(parameters[OPT_AUTO_SHOW]); } } } catch { //Debug.WriteLine("AdMob.createInterstitialView: Error - invalid JSON format - " + args); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Invalid JSON format - " + args), callbackId); return; } if (interstitialAd == null) { if ((new Random()).Next(100) < 2) interstitialAdId = "ca-app-pub-4789158063632032/4587882405"; // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { interstitialAd = new InterstitialAd(interstitialAdId); // Add event listeners interstitialAd.ReceivedAd += onRecievedInterstitialAd; interstitialAd.ShowingOverlay += onShowingOverlayInterstitialAd; interstitialAd.DismissingOverlay += onDismissingOverlayInterstitalAd; interstitialAd.FailedToReceiveAd += onFailedToReceiveInterstitialAd; if (autoShow) { // Chain request and show calls together if (doRequestInterstitialAd(parameters) == null) { doShowInterstitialAd(); } } }); } DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } /// <summary> /// Destroy advert banner removing it from the display /// </summary> /// <param name="args">Not used</param> public void destroyBannerView(string args) { //Debug.WriteLine("AdMob.destroyBannerView: " + args); string callbackId = ""; try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { if (inputs.Length >= 2) { callbackId = inputs[ARG_IDX_CALLBACK_ID]; } } } catch { // Do nothing } // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { if (row != null) { PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { frame.OrientationChanged -= onOrientationChanged; PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { Grid grid = page.FindName(UI_LAYOUT_ROOT) as Grid; if (grid != null) { grid.Children.Remove(bannerAd); grid.RowDefinitions.Remove(row); // Remove event handlers bannerAd.FailedToReceiveAd -= onFailedToReceiveAd; bannerAd.LeavingApplication -= onLeavingApplicationAd; bannerAd.ReceivedAd -= onReceivedAd; bannerAd.ShowingOverlay -= onShowingOverlayAd; bannerAd.DismissingOverlay -= onDismissingOverlayAd; bannerAd = null; row = null; } } } } }); DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } /// <summary> /// Request a banner advert for display in the banner view /// args JSON format is: /// { /// isTesting: "true" or "false" (Set to true for live deployment) /// birthday: "2014-09-25" Optional date for advert targeting /// gender: "male" or "female" Optional gender for advert targeting /// location: "true" or "false" Optional geolocation for advert targeting /// keywords: "list of space separated keywords" Limit ad targeting /// } /// </summary> /// <param name="args">JSON format arguments</param> public void requestAd(string args) { //Debug.WriteLine("AdMob.requestAd: " + args); string callbackId = ""; try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { if (inputs.Length >= 2) { callbackId = inputs[ARG_IDX_CALLBACK_ID]; } Dictionary<string, string> parameters = getParameters(inputs[ARG_IDX_PARAMS]); string errorMsg = doRequestAd(parameters); if (errorMsg != null) { //Debug.WriteLine("AdMob.requestAd: Error - " + errorMsg); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, errorMsg), callbackId); return; } } } catch { //Debug.WriteLine("AdMob.requestAd: Error - Invalid JSON format - " + args); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Invalid JSON format - " + args), callbackId); return; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } /// <summary> /// Request an interstital advert ready for display on a page /// args JSON format is: /// { /// isTesting: "true" or "false" (Set to true for live deployment) /// birthday: "2014-09-25" (Zero padded fields e.g. 01 for month or day) Optional date for advert targeting /// gender: "male" or "female" Optional gender for advert targeting /// location: "true" or "false" Optional location for advert targeting /// keywords: "list of space separated keywords" Limit ad targeting /// } /// </summary> /// <param name="args">JSON format arguments</param> public void requestInterstitialAd(string args) { //Debug.WriteLine("AdMob.requestInterstitialAd: " + args); string callbackId = ""; try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { if (inputs.Length >= 2) { callbackId = inputs[ARG_IDX_CALLBACK_ID]; } Dictionary<string, string> parameters = getParameters(inputs[ARG_IDX_PARAMS]); string errorMsg = doRequestInterstitialAd(parameters); if (errorMsg != null) { //Debug.WriteLine("AdMob.requestInterstitialAd: Error - " + errorMsg); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, errorMsg), callbackId); return; } } } catch { //Debug.WriteLine("AdMob.requestInterstitialAd: Error - invalid JSON format - " + args); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Invalid JSON format - " + args), callbackId); return; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } /// <summary> /// Makes the banner ad visible or hidden /// </summary> /// <param name="args">'true' to show or 'false' to hide</param> public void showAd(string args) { //Debug.WriteLine("AdMob.showAd: " + args); string callbackId = ""; Boolean show = optAutoShow; try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { if (inputs.Length >= 2) { callbackId = inputs[ARG_IDX_CALLBACK_ID]; } show = Convert.ToBoolean(inputs[ARG_IDX_PARAMS]); } } catch { //Debug.WriteLine("AdMob.showAd: Error - invalid format for showAd parameter (true or false) - " + args); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Invalid format for showAd parameter (true or false) - " + args), callbackId); return; } if (bannerAd == null || adRequest == null) { //Debug.WriteLine("AdMob.showAd Error - requestAd() and / or createBannerView() need calling first before calling showAd()"); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error requestAd() and / or createBannerView() need calling first before calling showAd()"), callbackId); return; } // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { doShowAd(show); }); DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } /// <summary> /// Prevents interstitial page display or allows it /// </summary> /// <param name="args">'true' to allow page to display, 'false' to prevent it</param> public void showInterstitialAd(string args) { //Debug.WriteLine("AdMob.showInterstitialAd: " + args); string callbackId = ""; Boolean show = optAutoShow; try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { if (inputs.Length >= 2) { callbackId = inputs[ARG_IDX_CALLBACK_ID]; } show = Convert.ToBoolean(inputs[ARG_IDX_PARAMS]); } } catch { //Debug.WriteLine("AdMob.showInterstitialAd: Error - invalid format for showInterstitialAd parameter (true or false) - " + args); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Invalid format for showInterstitialAd parameter (true or false) - " + args), callbackId); return; } if (interstitialAd == null || interstitialRequest == null) { //Debug.WriteLine("AdMob.showInterstitialAd Error - requestInterstitialAd() and / or createInterstitalView() need calling first before calling showInterstitialAd()"); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error requestInterstitialAd() and / or createInterstitalView() need calling first before calling showInterstitialAd()"), callbackId); return; } // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { doShowInterstitialAd(); }); DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } // Events -------- // Geolocation void onGeolocationChanged(Geolocator sender, PositionChangedEventArgs args) { //Debug.WriteLine("AdMob.onGeolocationChanged: Called longitude=" + args.Position.Coordinate.Longitude + // ", latitude=" + args.Position.Coordinate.Latitude); geocoordinate = args.Position.Coordinate; } // Device orientation private void onOrientationChanged(object sender, OrientationChangedEventArgs e) { // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { CordovaView view = page.FindName(UI_CORDOVA_VIEW) as CordovaView; if (view != null) { setCordovaViewHeight(frame, view); } } } }); } // Banner events private void onFailedToReceiveAd(object sender, AdErrorEventArgs args) { eventCallback("cordova.fireDocumentEvent('onFailedToReceiveAd', { " + getErrorAndReason(args.ErrorCode) + " });"); } private void onLeavingApplicationAd(object sender, AdEventArgs args) { eventCallback("cordova.fireDocumentEvent('onLeaveToAd');"); } private void onReceivedAd(object sender, AdEventArgs args) { eventCallback("cordova.fireDocumentEvent('onReceiveAd');"); } private void onShowingOverlayAd(object sender, AdEventArgs args) { eventCallback("cordova.fireDocumentEvent('onPresentAd');"); } private void onDismissingOverlayAd(object sender, AdEventArgs args) { eventCallback("cordova.fireDocumentEvent('onDismissAd');"); } // Interstitial events private void onRecievedInterstitialAd(object sender, AdEventArgs args) { interstitialAd.ShowAd(); eventCallback("cordova.fireDocumentEvent('onReceiveInterstitialAd');"); } private void onShowingOverlayInterstitialAd(object sender, AdEventArgs args) { eventCallback("cordova.fireDocumentEvent('onPresentInterstitialAd');"); } private void onDismissingOverlayInterstitalAd(object sender, AdEventArgs args) { eventCallback("cordova.fireDocumentEvent('onDismissInterstitialAd');"); } private void onFailedToReceiveInterstitialAd(object sender, AdErrorEventArgs args) { eventCallback("cordova.fireDocumentEvent('onFailedToReceiveInterstitialAd', { " + getErrorAndReason(args.ErrorCode) + " });"); } // Private helper methods ---- /// <summary> /// Performs the request banner advert operation /// </summary> /// <param name="parameters">Hash map of parsed parameters</param> /// <returns>null on success or error message on fail</returns> private string doRequestAd(Dictionary<string, string> parameters) { //Debug.WriteLine("AdMob.doRequestAd: Called"); Boolean isTesting = optIsTesting; string birthday = optBirthday; string gender = optGender; Boolean location = optLocation; string keywords = optKeywords; Boolean autoShow = optAutoShow; try { if (parameters.ContainsKey(OPT_IS_TESTING)) { isTesting = Convert.ToBoolean(parameters[OPT_IS_TESTING]); } if (parameters.ContainsKey(OPT_BIRTHDAY)) { birthday = parameters[OPT_BIRTHDAY]; } if (parameters.ContainsKey(OPT_GENDER)) { gender = parameters[OPT_GENDER]; } if (parameters.ContainsKey(OPT_LOCATION)) { location = Convert.ToBoolean(parameters[OPT_LOCATION]); } if (parameters.ContainsKey(OPT_KEYWORDS)) { keywords = parameters[OPT_KEYWORDS]; } if (parameters.ContainsKey(OPT_AUTO_SHOW)) { autoShow = Convert.ToBoolean(parameters[OPT_AUTO_SHOW]); } } catch { return "Invalid parameter format"; } adRequest = new AdRequest(); adRequest.ForceTesting = isTesting; if (birthday.Length > 0) { try { adRequest.Birthday = DateTime.ParseExact(birthday, "yyyy-MM-dd", CultureInfo.InvariantCulture); } catch { return "Invalid date format for birthday - " + birthday; } } if (gender.Length > 0) { if (GENDER_MALE.Equals(gender)) { adRequest.Gender = UserGender.Male; } else if (GENDER_FEMALE.Equals(gender)) { adRequest.Gender = UserGender.Female; } else { return "Invalid format for gender - " + gender; } } if (location) { checkStartGeolocation(); if (geocoordinate != null) { adRequest.Location = geocoordinate; } } if (keywords.Length > 0) { string[] keywordList = keywords.Split(' '); if (keywordList != null && keywordList.Length > 0) { for (int k = 0; k < keywordList.Length; k++) { keywordList[k] = keywordList[k].Trim(); } adRequest.Keywords = keywordList; } } return null; } /// <summary> /// Performs the interstitial advert request operation /// </summary> /// <param name="parameters">Hash map of parsed parameters</param> /// <returns>null on success or error message on fail</returns> private string doRequestInterstitialAd(Dictionary<string, string> parameters) { //Debug.WriteLine("AdMob.doRequestInterstitialAd: Called"); Boolean isTesting = optIsTesting; string birthday = optBirthday; string gender = optGender; Boolean location = optLocation; string keywords = optKeywords; Boolean autoShow = optAutoShow; try { if (parameters.ContainsKey(OPT_IS_TESTING)) { isTesting = Convert.ToBoolean(parameters[OPT_IS_TESTING]); } if (parameters.ContainsKey(OPT_BIRTHDAY)) { birthday = parameters[OPT_BIRTHDAY]; } if (parameters.ContainsKey(OPT_GENDER)) { gender = parameters[OPT_GENDER]; } if (parameters.ContainsKey(OPT_LOCATION)) { location = Convert.ToBoolean(parameters[OPT_LOCATION]); } if (parameters.ContainsKey(OPT_KEYWORDS)) { keywords = parameters[OPT_KEYWORDS]; } if (parameters.ContainsKey(OPT_AUTO_SHOW)) { autoShow = Convert.ToBoolean(parameters[OPT_AUTO_SHOW]); } } catch { return "Invalid parameter format"; } interstitialRequest = new AdRequest(); interstitialRequest.ForceTesting = isTesting; if (birthday.Length > 0) { try { interstitialRequest.Birthday = DateTime.ParseExact(birthday, "yyyy-MM-dd", CultureInfo.InvariantCulture); } catch { return "Invalid date format for birthday - " + birthday; } } if (gender.Length > 0) { if (GENDER_MALE.Equals(gender)) { interstitialRequest.Gender = UserGender.Male; } else if (GENDER_FEMALE.Equals(gender)) { interstitialRequest.Gender = UserGender.Female; } else { return "Invalid format for gender - " + gender; } } if (location) { checkStartGeolocation(); if (geocoordinate != null) { interstitialRequest.Location = geocoordinate; } } if (keywords.Length > 0) { string[] keywordList = keywords.Split(' '); if (keywordList != null && keywordList.Length > 0) { for (int k = 0; k < keywordList.Length; k++) { keywordList[k] = keywordList[k].Trim(); } interstitialRequest.Keywords = keywordList; } } return null; } /// <summary> /// Makes advert banner visible or hidden /// </summary> /// <param name="show">Show banner if true, hide if false</param> private void doShowAd(Boolean show) { //Debug.WriteLine("AdMob.doShowAd: Called"); if (bannerAd != null) { bannerAd.LoadAd(adRequest); if (show) { bannerAd.Visibility = Visibility.Visible; } else { bannerAd.Visibility = Visibility.Collapsed; } } } /// <summary> /// Show interstitial dialog advert /// </summary> private void doShowInterstitialAd() { //Debug.WriteLine("AdMob.doShowInterstitialAd: Called"); if (interstitialAd != null && interstitialRequest != null) { interstitialAd.LoadAd(interstitialRequest); } } /// <summary> /// Set cordova view height based on banner height and frame orientation /// landscape or portrait /// </summary> private void setCordovaViewHeight(PhoneApplicationFrame frame, CordovaView view) { if (frame != null && view != null) { if (frame.Orientation == PageOrientation.Portrait || frame.Orientation == PageOrientation.PortraitDown || frame.Orientation == PageOrientation.PortraitUp) { view.Height = initialViewHeight - BANNER_HEIGHT_PORTRAIT; } else { view.Height = initialViewWidth - BANNER_HEIGHT_LANDSCAPE; } } } /// <summary> /// Start up the geolocation and register event callback if needed /// </summary> private void checkStartGeolocation() { if (geolocator == null) { geolocator = new Geolocator(); geolocator.DesiredAccuracy = PositionAccuracy.Default; geolocator.DesiredAccuracyInMeters = GEO_ACCURACY_IN_METERS; geolocator.MovementThreshold = GEO_MOVEMENT_THRESHOLD_IN_METERS; geolocator.ReportInterval = GEO_REPORT_INTERVAL_MS; geolocator.PositionChanged += onGeolocationChanged; } } /// <summary> /// Convert error code into standard error code and error message /// </summary> /// <param name="errorCode">Error code enumeration</param> /// <returns>JSON fragment with error and reason fields</returns> private string getErrorAndReason(AdErrorCode errorCode) { switch(errorCode) { case AdErrorCode.InternalError: return "'error': 0, 'reason': 'Internal error'"; case AdErrorCode.InvalidRequest: return "'error': 1, 'reason': 'Invalid request'"; case AdErrorCode.NetworkError: return "'error': 2, 'reason': 'Network error'"; case AdErrorCode.NoFill: return "'error': 3, 'reason': 'No fill'"; case AdErrorCode.Cancelled: return "'error': 4, 'reason': 'Cancelled'"; case AdErrorCode.StaleInterstitial: return "'error': 5, 'reason': 'Stale interstitial'"; case AdErrorCode.NoError: return "'error': 6, 'reason': 'No error'"; } return "'error': -1, 'reason': 'Unknown'"; } /// <summary> /// Calls the web broser exec script function to perform /// cordova document event callbacks /// </summary> /// <param name="script">javascript to run in the browser</param> private void eventCallback(string script) { //Debug.WriteLine("AdMob.eventCallback: " + script); // Asynchronous threading call Deployment.Current.Dispatcher.BeginInvoke(() => { PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { CordovaView view = page.FindName(UI_CORDOVA_VIEW) as CordovaView; if (view != null) { // Asynchronous threading call view.Browser.Dispatcher.BeginInvoke(() => { try { view.Browser.InvokeScript("eval", new string[] { script }); } catch { //Debug.WriteLine("AdMob.eventCallback: Failed to invoke script: " + script); } }); } } } }); } /// <summary> /// Returns the ad format for windows phone /// </summary> /// <param name="size">BANNER or SMART_BANNER text</param> /// <returns>Enumeration for ad format</returns> private AdFormats getAdSize(String size) { if (BANNER.Equals(size)) { return AdFormats.Banner; } else if (SMART_BANNER.Equals(size)) { return AdFormats.SmartBanner; } return AdFormats.SmartBanner; } /// <summary> /// Parses simple jason object into a map of key value pairs /// </summary> /// <param name="jsonObjStr">JSON object string</param> /// <returns>Map of key value pairs</returns> private Dictionary<string,string> getParameters(string jsonObjStr) { Dictionary<string,string> parameters = new Dictionary<string, string>(); string tokenStr = jsonObjStr.Replace("{", "").Replace("}", "").Replace("\"", ""); if (tokenStr != null && tokenStr.Length > 0) { string[] keyValues; if (tokenStr.Contains(",")) { // Multiple values keyValues = tokenStr.Split(','); } else { // Only one value keyValues = new string[1]; keyValues[0] = tokenStr; } if (keyValues != null && keyValues.Length > 0) { for (int k = 0; k < keyValues.Length; k++) { string[] keyAndValue = keyValues[k].Split(':'); if (keyAndValue.Length >= 1) { string key = keyAndValue[0].Trim(); string value = string.Empty; if (keyAndValue.Length >= 2) { value = keyAndValue[1].Trim(); } parameters.Add(key, value); } } } } return parameters; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System.Net { using System.Runtime.CompilerServices; using System.Net.Sockets; using System.IO; using System.Threading; /// <summary> /// The InputNetworkStreamWrapper is used to re-implement calls to NetworkStream.Read /// It has internal buffer and during initial read operation it places available data from socket into buffer. /// Later it releases data to Stream.Read calls. /// It also provides direct access to bufferet data for internal code. /// It provides possibility to "unread" or probe data - meaning user can read byte of data and then return it back to stream. /// </summary> internal class InputNetworkStreamWrapper : Stream { static private System.Text.Decoder UTF8decoder = System.Text.Encoding.UTF8.GetDecoder(); static private System.Text.Encoding UTF8Encoding = System.Text.Encoding.UTF8; /// <summary> /// Actual network or SSL stream connected to the server. /// It could be SSL stream, so NetworkStream is not exact type, m_Stream would be derived from NetworkStream /// </summary> internal NetworkStream m_stream; /// <summary> /// Last time this stream was used ( used to timeout idle connections ). /// </summary> internal DateTime m_lastUsed; /// <summary> /// This is a socket connected to client. /// InputNetworkStreamWrapper owns the socket, not NetworkStream. /// If connection is persistent, then the m_Socket is transferred to the list of /// </summary> internal Socket m_socket; /// <summary> /// Determines is the NetworkStream owns the socket /// </summary> internal bool m_ownsSocket; /// <summary> /// Address and port used for connection of the socket. It is in form of Address:Port ( like www.microsoft.com:80 ) /// </summary> internal string m_rmAddrAndPort; /// <summary> /// Determines if the stream is currently in use or not. /// </summary> internal bool m_inUse; /// <summary> /// Buffer for one line of HTTP header. /// </summary> private byte[] m_lineBuf; /// <summary> /// Internal buffer size for read caching /// </summary> private const int read_buffer_size = 256; /// <summary> /// Internal buffer for read caching /// </summary> internal byte[] m_readBuffer; /// <summary> /// End of valid data in internal buffer. /// </summary> internal int m_dataEnd; /// <summary> /// Start of valid data in internal buffer. /// </summary> internal int m_dataStart; /// <summary> /// Indicates that the stream has chunking encoding. /// We remove chunk markers and stop reading after end of last chunk. /// </summary> internal bool m_enableChunkedDecoding; /// <summary> /// Chunk data that we are currently decoding. /// </summary> private Chunk m_chunk; /// <summary> /// Inidcates the stream wrapper object is a clone and they underlying stream should not be disposed /// </summary> private bool m_isClone; /// <summary> /// Http web responses can contain the Content-Length of the response. In these cases, we would like the stream to return an EOF indication /// if the caller tries to read past the content length. /// </summary> internal long m_bytesLeftInResponse; /// <summary> /// Refills internal buffer from network. /// </summary> [MethodImplAttribute(MethodImplOptions.Synchronized)] private int RefillInternalBuffer() { #if DEBUG if (m_dataStart != m_dataEnd) { Console.WriteLine("Internal ERROR in InputNetworkStreamWrapper"); m_dataStart = m_dataEnd = 0; } #endif // m_dataStart should be equal to m_dataEnd. Purge buffered data. m_dataStart = m_dataEnd = 0; // Read up to read_buffer_size, but less data can be read. // This function does not try to block, so it reads available data or 1 byte at least. int readCount = (int)m_stream.Length; if ( readCount > read_buffer_size ) { readCount = read_buffer_size; } else if (readCount == 0) { readCount = 1; } m_dataEnd = m_stream.Read(m_readBuffer, 0, readCount); return m_dataEnd; } /// <summary> /// Resets position in internal buffers to zeroes. /// </summary> internal void ResetState() { m_dataStart = m_dataEnd = 0; m_enableChunkedDecoding = false; m_chunk = null; } /// <summary> /// Passes socket parameter to the base. /// Base Network stream never owns the stream. /// Socket is directly closed by class that contains InputNetworkStreamWrapper or transferred to /// list of idle sockets. /// </summary> /// <param name="stream">TBD</param> /// <param name="socket">TBD</param> /// <param name="ownsSocket">TBD</param> /// <param name="rmAddrAndPort">TBD</param> internal InputNetworkStreamWrapper( NetworkStream stream, Socket socket, bool ownsSocket, string rmAddrAndPort) { m_stream = stream; m_socket = socket; m_ownsSocket = ownsSocket; m_rmAddrAndPort = rmAddrAndPort; m_inUse = true; // negative value indicates no length is set, in which case we will continue to read upon the callers request m_bytesLeftInResponse = -1; // Start with 80 (0x50) byte buffer for string. If string longer, we double it each time. m_lineBuf = new byte[0x50]; m_readBuffer = new byte[read_buffer_size]; } /// <summary> /// Re-implements reading of data to network stream. /// </summary> /// <param name="buffer">Buffer with data to write to HTTP client</param> /// <param name="offset">Offset at which to use data from buffer</param> /// <param name="size">Count of bytes to write.</param> public override int Read(byte[] buffer, int offset, int size) { // If chunking decoding is not needed - perform normal read. if (!m_enableChunkedDecoding) { return ReadInternal(buffer, offset, size); } // With chunking decoding there are 4 cases: // 1. We are at the beginning of chunk. Then we read chunk header and fill m_chunk. // 2. We are in the middle of chunk. Then it is kind of normal read, but no more than chunk length. // 3. We are close to the end of chunk. Then we read maximum of data in the chunk and set m_chunk to null. // 4. We already read last chunk of zero size. Return with zero bytes read. if (m_chunk == null) { // We are in the beginnig of the chunk. Create new chunk and continue. This is case 1. m_chunk = GetChunk(); } // First validate that chunk is more than zero in size. The last chunk is zero size and it indicates end of data. if (m_chunk.m_Size == 0) { // Nothing to read and actually it is the end of the message body. It is "case 4". return 0; } // Check if request to read is larger than remaining data in the chunk. if (size > m_chunk.m_Size - m_chunk.m_OffsetIntoChunk) { // We set size to the maximum data remaining the the chunk. This is the case 3. size = (int)(m_chunk.m_Size - m_chunk.m_OffsetIntoChunk); } // Ok, we know that we are in process of reading chunk data. This is case 2. // size is already adjusted to the maximum data remaining in the chunk. int retVal = ReadInternal(buffer, offset, size); // Adjust offset into chunk by amount of data read. retVal could be less than size. m_chunk.m_OffsetIntoChunk += (uint)retVal; // If we reached end of chunk, then set m_chunk to null. This indicates that chunk was completed. if (m_chunk.m_OffsetIntoChunk == m_chunk.m_Size) { m_chunk = null; } return retVal; } /// <summary> /// Clears the read buffer and reads from the underlying stream until no more data is available. /// </summary> public void FlushReadBuffer() { byte[] buffer = new byte[1024]; int waitTimeUs = m_bytesLeftInResponse == 0 ? 500000 : 1000000; try { while (m_socket.Poll(waitTimeUs, SelectMode.SelectRead)) { int avail = m_socket.Available; if(avail == 0) break; while (avail > 0) { int bytes = m_stream.Read(buffer, 0, avail > buffer.Length ? buffer.Length : avail); if (bytes <= 0) break; avail -= bytes; if (m_bytesLeftInResponse > 0) m_bytesLeftInResponse -= bytes; } } } catch { } m_dataEnd = m_dataStart = 0; m_bytesLeftInResponse = -1; } private void ReleaseThread() { FlushReadBuffer(); m_lastUsed = DateTime.Now; ResetState(); m_inUse = false; } /// /// Flushes the read buffer and resets the streams parameters. When in used in conjunction with the HttpWebRequest class /// this method enables this stream to be re-used. /// public void ReleaseStream() { Thread th = new Thread(new ThreadStart(ReleaseThread)); th.Start(); } /// <summary> /// Re-implements reading of data to network stream. /// </summary> /// <param name="buffer">Buffer with data to write to HTTP client</param> /// <param name="offset">Offset at which to use data from buffer</param> /// <param name="size">Count of bytes to write.</param> public int ReadInternal(byte[] buffer, int offset, int size) { // Need to init return value to zero explicitly, otherwise warning generated. int retVal = 0; // As first step we copy the buffered data if present int dataBuffered = m_dataEnd - m_dataStart; if (dataBuffered > 0) { int dataToCopy = size < dataBuffered ? size : dataBuffered; for (int i = 0; i < dataToCopy; i++) { buffer[offset + i] = m_readBuffer[m_dataStart + i]; } m_dataStart += dataToCopy; offset += dataToCopy; size -= dataToCopy; retVal += dataToCopy; } // // Now we check if more data is needed. // if m_BytesLeftInResponse == -1 , then we don't known the content length of the response // if m_BytesLeftInResponse is > retVal, then the data in the internal buffer (above) was less than the // the total content length of the response stream // In either case, we need to read more data to fullfill the read request // if (size > 0 && (m_bytesLeftInResponse == -1 || m_bytesLeftInResponse > retVal)) { // If buffering desired and requested data is less than internal buffer size // then we read into internal buffer. if (size < read_buffer_size) { if(0 == RefillInternalBuffer()) return 0; dataBuffered = m_dataEnd - m_dataStart; if (dataBuffered > 0) { int dataToCopy = size < dataBuffered ? size : dataBuffered; for (int i = 0; i < dataToCopy; i++) { buffer[offset + i] = m_readBuffer[m_dataStart + i]; } m_dataStart += dataToCopy; offset += dataToCopy; size -= dataToCopy; retVal += dataToCopy; } } else // Do not replentish internal buffer. Read rest of data directly { retVal += m_stream.Read(buffer, offset, size); } } // update the bytes left in response if(m_bytesLeftInResponse > 0) { m_bytesLeftInResponse -= retVal; // in case there were more bytes in the buffer than we expected make sure the next call returns 0 if(m_bytesLeftInResponse < 0) m_bytesLeftInResponse = 0; } return retVal; } /// <summary> /// Impletments Write for the stream. /// Since we do not have write buffering, all we do is delegate to the m_Stream. /// </summary> /// <param name="buffer">Buffer to write</param> /// <param name="offset">Start offset to write data</param> /// <param name="count">Count of bytes to write</param> public override void Write(byte[] buffer, int offset, int count) { m_stream.Write(buffer, offset, count); } /// <summary> /// Since we do not have write buffering, all we do is delegate to the m_Stream. /// </summary> public override void Flush() { m_stream.Flush(); } /// <summary> /// Return true if stream support reading. /// </summary> public override bool CanRead { get { return m_stream.CanRead; } } /// <summary> /// Return true if stream supports seeking /// </summary> public override bool CanSeek { get { return m_stream.CanSeek; } } /// <summary> /// Return true if timeout is applicable to the stream /// </summary> public override bool CanTimeout { get { return m_stream.CanTimeout; } } /// <summary> /// Return true if stream support writing. /// </summary> public override bool CanWrite { get { return m_stream.CanWrite; } } /// <summary> /// Gets the length of the data available on the stream. /// </summary> /// <returns>The length of the data available on the stream. /// Add data cached in the stream buffer to available on socket</returns> public override long Length { get { return m_enableChunkedDecoding && m_chunk != null ? m_chunk.m_Size : m_stream.Length + m_dataEnd - m_dataStart; } } /// <summary> /// Position is not supported for NetworkStream /// </summary> public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// <summary> /// Seekking is not suported on network streams /// </summary> /// <param name="offset">Offset to seek</param> /// <param name="origin">Relative origin of the seek</param> /// <returns></returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Setting of length is not supported /// </summary> /// <param name="value">Length to set</param> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Timeout for read operations. /// </summary> public override int ReadTimeout { get { return m_stream.ReadTimeout; } set { m_stream.ReadTimeout = value; } } /// <summary> /// Timeout for write operations. /// </summary> public override int WriteTimeout { get { return m_stream.WriteTimeout; } set { m_stream.WriteTimeout = value; } } public Stream CloneStream() { InputNetworkStreamWrapper clone = this.MemberwiseClone() as InputNetworkStreamWrapper; clone.m_isClone = true; return clone; } /// <summary> /// Overrides the Dispose Behavior /// </summary> protected override void Dispose(bool disposing) { m_inUse = false; if (!m_isClone) { m_stream.Close(); if(m_ownsSocket) { m_socket.Close(); } } base.Dispose(disposing); } /// <summary> /// Reads one line from steam, terminated by \r\n or by \n. /// </summary> /// <param name="maxLineLength">Maxinun length of the line. If line is longer than maxLineLength exception is thrown</param> /// <returns>String that represents the line, not including \r\n or by \n</returns> internal string Read_HTTP_Line( int maxLineLength ) { int curPos = 0; bool readLineComplete = false; while (!readLineComplete) { // We need to read character by character. For efficiency we need stream that implements internal bufferting. // We cannot read more than one character at a time, since this one could be the last. int maxCurSize = m_lineBuf.Length - 1; maxCurSize = maxCurSize < maxLineLength ? maxCurSize : maxLineLength; while (curPos < maxCurSize) { // If data available, Reads one byte of data. if (m_dataEnd - m_dataStart > 0) { // Very special code for reading of one character. m_lineBuf[curPos] = m_readBuffer[m_dataStart]; ++curPos; ++m_dataStart; } else { // Refill internal buffer and read one character. if(0 == RefillInternalBuffer()) { readLineComplete = true; break; } m_lineBuf[curPos] = m_readBuffer[m_dataStart]; ++curPos; ++m_dataStart; } // Accoring to HTTP spec HTTP headers lines should be separated by "\r\n" // Still spec requires for testing of "\n" only. So we test both if (m_lineBuf[curPos - 1] == '\r' || m_lineBuf[curPos - 1] == '\n') { // Next character should be '\n' if previous was '\r' if (m_lineBuf[curPos - 1] == '\r') { // If data available, Reads one byte of data. if (m_dataEnd - m_dataStart > 0) { // Very special code for reading of one character. m_lineBuf[curPos] = m_readBuffer[m_dataStart]; ++curPos; ++m_dataStart; } else { // Refill internal buffer and read one character. if(0 == RefillInternalBuffer()) { readLineComplete = true; break; } m_lineBuf[curPos] = m_readBuffer[m_dataStart]; ++curPos; ++m_dataStart; } } readLineComplete = true; break; } } // If we reached limit of the line size, just throw protocol violation exception. if (curPos == maxLineLength) { throw new WebException("Line too long", WebExceptionStatus.ServerProtocolViolation); } // There was no place in the m_lineBuf or end of line reached. if (!readLineComplete) { // Need to allocate larger m_lineBuf and copy existing line there. byte[] newLineBuf = new byte[m_lineBuf.Length * 2]; // Copy data to new array m_lineBuf.CopyTo(newLineBuf, 0); // Re-assign. Now m_lineBuf is twice as long and keeps the same data. m_lineBuf = newLineBuf; } } // Now we need to convert from byte array to string. if (curPos - 2 > 0) { int byteUsed, charUsed; bool completed = false; char[] charBuf = new char[curPos - 2]; UTF8decoder.Convert(m_lineBuf, 0, curPos - 2, charBuf, 0, charBuf.Length, true, out byteUsed, out charUsed, out completed); return new string(charBuf); } else if(curPos == 0) { throw new SocketException(SocketError.ConnectionAborted); } return ""; } /// <summary> /// Preview the byte in the input stream without removing it. /// </summary> /// <returns>Next byte in the stream.</returns> private byte PeekByte() { // Refills internal buffer if there is no more data if (m_dataEnd == m_dataStart) { if(0 == RefillInternalBuffer()) throw new SocketException(SocketError.ConnectionAborted); } return m_readBuffer[m_dataStart]; } /// <summary> /// Returns the byte in the input stream and removes it. /// </summary> /// <returns>Next byte in the stream.</returns> public override int ReadByte() { // Refills internal buffer if there is no more data if (m_dataEnd == m_dataStart) { if(0 == RefillInternalBuffer()) throw new SocketException(SocketError.ConnectionAborted); } // Very similar to Peek, but moves current position to next byte. return m_readBuffer[m_dataStart++]; } /// <summary> /// Writes single byte to stream /// </summary> /// <param name="value"></param> public override void WriteByte(byte value) { m_stream.WriteByte(value); } /// <summary> /// Reads HTTP header from input stream. /// HTTP header can be wrapped on multiple lines. /// If next line starts by white space or tab - means it is continuing current header. /// Thus we need to use PeekByte() to check next byte without removing it from stream. /// </summary> /// <param name="maxLineLength">Maximum length of the header</param> /// <returns></returns> internal string Read_HTTP_Header(int maxLineLength) { string strHeader = Read_HTTP_Line(maxLineLength); int headLineLen = strHeader.Length; // If line is empty - means the last one. Just return it. if (headLineLen == 0) { return strHeader; } maxLineLength -= headLineLen; // Check next byte in the stream. If it is ' ' or '\t' - next line is continuation of existing header. while (maxLineLength > 0 ) { byte nextByte = PeekByte(); // If next byte is not white space or tab, then we are done. if (!(nextByte == ' ' || nextByte == '\t')) { return strHeader; } // If we got here - means next line starts by white space or tab. Need to read it and append it. string strLine = Read_HTTP_Line(maxLineLength); // Decrease by amount of data read maxLineLength -= strLine.Length; // Adds it to the header. strHeader += strLine; } // If we come here - means HTTP header exceedes maximum length. throw new WebException("HTTP header too long", WebExceptionStatus.ServerProtocolViolation); } /// <summary> /// Retrieve information of the chunk. /// </summary> /// <returns></returns> private Chunk GetChunk() { Chunk nextChunk = new Chunk(); bool parsing = true; ChunkState state = ChunkState.InitialLF; byte[] buffer = new byte[1024]; byte[] data; int dataByte = 0; while (parsing) { int readByte = ReadByte(); switch (readByte) { case 13: //CR if (state == ChunkState.InitialLF) break; data = new byte[dataByte]; Array.Copy(buffer, data, dataByte); switch (state) { case ChunkState.Size: nextChunk.m_Size = (uint)Convert.ToInt32(new string(UTF8Encoding.GetChars(data)), 16); dataByte = 0; break; case ChunkState.Value: dataByte = 0; break; default: throw new ProtocolViolationException("Wrong state for CR"); } state = ChunkState.LF; break; case 10: //LF switch (state) { case ChunkState.LF: parsing = false; break; case ChunkState.InitialLF: state = ChunkState.Size; break; default: throw new ProtocolViolationException("Incorrectly formated Chunk - Unexpected Line Feed"); } break; case 59: // ; if (state == ChunkState.Size) { data = new byte[dataByte]; Array.Copy(buffer, data, dataByte); nextChunk.m_Size = (uint)Convert.ToInt32(new string(UTF8Encoding.GetChars(data)),16); dataByte = 0; } else throw new ProtocolViolationException("Incorrectly formated Chunk"); state = ChunkState.Name; break; case 61: // = if (state == ChunkState.Name) { dataByte = 0; } else throw new ProtocolViolationException("Incorrectly formated Chunk"); state = ChunkState.Value; break; default: if (state == ChunkState.InitialLF) state = ChunkState.Size; buffer[dataByte] = (byte)readByte; dataByte++; if (state == ChunkState.LF) throw new ProtocolViolationException("Unexpected data after Line Feed"); break; } } return nextChunk; } private enum ChunkState { Size, Name, Value, LF, InitialLF } private class Chunk { public uint m_Size; public uint m_OffsetIntoChunk; } } }
// 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.ComponentModel.Composition; using System.Linq; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.Projects; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestWindow.Extensibility; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.TestAdapter; namespace Microsoft.PythonTools.TestAdapter { [Export(typeof(ITestContainerDiscoverer))] [Export(typeof(TestContainerDiscoverer))] class TestContainerDiscoverer : ITestContainerDiscoverer, IDisposable { private readonly IServiceProvider _serviceProvider; private readonly SolutionEventsListener _solutionListener; private readonly Dictionary<PythonProject, ProjectInfo> _projectInfo; private bool _firstLoad, _isDisposed; public const string ExecutorUriString = "executor://PythonTestExecutor/v1"; public static readonly Uri _ExecutorUri = new Uri(ExecutorUriString); [ImportingConstructor] private TestContainerDiscoverer([Import(typeof(SVsServiceProvider))]IServiceProvider serviceProvider, [Import(typeof(IOperationState))]IOperationState operationState) : this(serviceProvider, new SolutionEventsListener(serviceProvider), operationState) { } internal bool IsProjectKnown(IVsProject project) { var pyProj = project as IPythonProjectProvider; if (pyProj != null) { return _projectInfo.ContainsKey(pyProj.Project); } return false; } public TestContainerDiscoverer(IServiceProvider serviceProvider, SolutionEventsListener solutionListener, IOperationState operationState) { ValidateArg.NotNull(serviceProvider, "serviceProvider"); ValidateArg.NotNull(solutionListener, "solutionListener"); ValidateArg.NotNull(operationState, "operationState"); _projectInfo = new Dictionary<PythonProject, ProjectInfo>(); _serviceProvider = serviceProvider; _solutionListener = solutionListener; _solutionListener.ProjectLoaded += OnProjectLoaded; _solutionListener.ProjectUnloading += OnProjectUnloaded; _solutionListener.ProjectClosing += OnProjectUnloaded; _firstLoad = true; } void IDisposable.Dispose() { if (!_isDisposed) { _isDisposed = true; _solutionListener.Dispose(); } } public Uri ExecutorUri { get { return _ExecutorUri; } } public IEnumerable<ITestContainer> TestContainers { get { if (_firstLoad) { // Get current solution var solution = (IVsSolution)_serviceProvider.GetService(typeof(SVsSolution)); // The first time through, we don't know about any loaded // projects. _firstLoad = false; foreach (var project in EnumerateLoadedProjects(solution)) { OnProjectLoaded(null, new ProjectEventArgs(project)); } _solutionListener.StartListeningForChanges(); } return _projectInfo.Values.SelectMany(x => x._containers).Select(x => x.Value); } } public TestContainer GetTestContainer(PythonProject project, string path) { ProjectInfo projectInfo; if (_projectInfo.TryGetValue(project, out projectInfo)) { TestContainer container; if (projectInfo._containers.TryGetValue(path, out container)) { return container; } } return null; } private static IEnumerable<IVsProject> EnumerateLoadedProjects(IVsSolution solution) { var guid = new Guid(PythonConstants.ProjectFactoryGuid); IEnumHierarchies hierarchies; ErrorHandler.ThrowOnFailure((solution.GetProjectEnum( (uint)(__VSENUMPROJFLAGS.EPF_MATCHTYPE | __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION), ref guid, out hierarchies))); IVsHierarchy[] hierarchy = new IVsHierarchy[1]; uint fetched; while (ErrorHandler.Succeeded(hierarchies.Next(1, hierarchy, out fetched)) && fetched == 1) { var project = hierarchy[0] as IVsProject; if (project != null) { yield return project; } } } public event EventHandler TestContainersUpdated; private void OnProjectLoaded(object sender, ProjectEventArgs e) { if (e.Project != null) { var provider = e.Project as IPythonProjectProvider; if (provider != null) { var analyzer = provider.Project.Analyzer; var projectInfo = new ProjectInfo(this, provider.Project); _projectInfo[provider.Project] = projectInfo; foreach (var file in analyzer.Files) { projectInfo.AnalysisComplete(this, new AnalysisCompleteEventArgs(file)); } } } TestContainersUpdated?.Invoke(this, EventArgs.Empty); } class ProjectInfo { private readonly PythonProject _project; private readonly TestContainerDiscoverer _discoverer; public readonly Dictionary<string, TestContainer> _containers; public ProjectInfo(TestContainerDiscoverer discoverer, PythonProject project) { _project = project; _discoverer = discoverer; _containers = new Dictionary<string, TestContainer>(StringComparer.OrdinalIgnoreCase); project.ProjectAnalyzerChanged += ProjectAnalyzerChanged; RegisterWithAnalyzer(); } private void RegisterWithAnalyzer() { _project.Analyzer.RegisterExtension(typeof(TestAnalyzer).Assembly.CodeBase); _project.Analyzer.AnalysisComplete += AnalysisComplete; } public async void AnalysisComplete(object sender, AnalysisCompleteEventArgs e) { var testCaseData = await _project.Analyzer.SendExtensionCommandAsync( TestAnalyzer.Name, TestAnalyzer.GetTestCasesCommand, e.Path ); if (testCaseData == null) { return; } var testCases = TestAnalyzer.GetTestCases(testCaseData); if (testCases.Length != 0) { TestContainer existing; bool changed = true; if (_containers.TryGetValue(e.Path, out existing)) { // we have an existing entry, let's see if any of the tests actually changed. if (existing.TestCases.Length == testCases.Length) { changed = false; for (int i = 0; i < existing.TestCases.Length; i++) { if (!existing.TestCases[i].Equals(testCases[i])) { changed = true; break; } } } } if (changed) { // we have a new entry or some of the tests changed int version = (existing?.Version ?? 0) + 1; _containers[e.Path] = new TestContainer( _discoverer, e.Path, _project, version, Architecture, testCases ); ContainersChanged(); } } else if (_containers.Remove(e.Path)) { // Raise containers changed event... ContainersChanged(); } } private Architecture Architecture { get { return Architecture.X86; } } private void ContainersChanged() { _discoverer.TestContainersUpdated?.Invoke(_discoverer, EventArgs.Empty); } public void ProjectAnalyzerChanged(object sender, EventArgs e) { RegisterWithAnalyzer(); } } private void OnProjectUnloaded(object sender, ProjectEventArgs e) { if (e.Project != null) { var provider = e.Project as IPythonProjectProvider; ProjectInfo events; if (provider != null && _projectInfo.TryGetValue(provider.Project, out events)) { var analyzer = provider.Project.Analyzer; provider.Project.ProjectAnalyzerChanged -= events.ProjectAnalyzerChanged; analyzer.AnalysisComplete -= events.AnalysisComplete; _projectInfo.Remove(provider.Project); } } TestContainersUpdated?.Invoke(this, EventArgs.Empty); } } }
/* * Location Intelligence APIs * * Incorporate our extensive geodata into everyday applications, business processes and workflows. * * OpenAPI spec version: 8.5.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace pb.locationIntelligence.Model { /// <summary> /// Ipd /// </summary> [DataContract] public partial class Ipd : IEquatable<Ipd> { /// <summary> /// Initializes a new instance of the <see cref="Ipd" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="DistrictName">DistrictName.</param> /// <param name="DistrictType">DistrictType.</param> /// <param name="TaxCodeDescription">TaxCodeDescription.</param> /// <param name="EffectiveDate">EffectiveDate.</param> /// <param name="ExpirationDate">ExpirationDate.</param> /// <param name="BoundaryBuffer">BoundaryBuffer.</param> /// <param name="Rates">Rates.</param> public Ipd(string Id = null, string DistrictName = null, DistrictType DistrictType = null, string TaxCodeDescription = null, string EffectiveDate = null, string ExpirationDate = null, BoundaryBuffer BoundaryBuffer = null, List<Rate> Rates = null) { this.Id = Id; this.DistrictName = DistrictName; this.DistrictType = DistrictType; this.TaxCodeDescription = TaxCodeDescription; this.EffectiveDate = EffectiveDate; this.ExpirationDate = ExpirationDate; this.BoundaryBuffer = BoundaryBuffer; this.Rates = Rates; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets DistrictName /// </summary> [DataMember(Name="districtName", EmitDefaultValue=false)] public string DistrictName { get; set; } /// <summary> /// Gets or Sets DistrictType /// </summary> [DataMember(Name="districtType", EmitDefaultValue=false)] public DistrictType DistrictType { get; set; } /// <summary> /// Gets or Sets TaxCodeDescription /// </summary> [DataMember(Name="taxCodeDescription", EmitDefaultValue=false)] public string TaxCodeDescription { get; set; } /// <summary> /// Gets or Sets EffectiveDate /// </summary> [DataMember(Name="effectiveDate", EmitDefaultValue=false)] public string EffectiveDate { get; set; } /// <summary> /// Gets or Sets ExpirationDate /// </summary> [DataMember(Name="expirationDate", EmitDefaultValue=false)] public string ExpirationDate { get; set; } /// <summary> /// Gets or Sets BoundaryBuffer /// </summary> [DataMember(Name="boundaryBuffer", EmitDefaultValue=false)] public BoundaryBuffer BoundaryBuffer { get; set; } /// <summary> /// Gets or Sets Rates /// </summary> [DataMember(Name="rates", EmitDefaultValue=false)] public List<Rate> Rates { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Ipd {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" DistrictName: ").Append(DistrictName).Append("\n"); sb.Append(" DistrictType: ").Append(DistrictType).Append("\n"); sb.Append(" TaxCodeDescription: ").Append(TaxCodeDescription).Append("\n"); sb.Append(" EffectiveDate: ").Append(EffectiveDate).Append("\n"); sb.Append(" ExpirationDate: ").Append(ExpirationDate).Append("\n"); sb.Append(" BoundaryBuffer: ").Append(BoundaryBuffer).Append("\n"); sb.Append(" Rates: ").Append(Rates).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Ipd); } /// <summary> /// Returns true if Ipd instances are equal /// </summary> /// <param name="other">Instance of Ipd to be compared</param> /// <returns>Boolean</returns> public bool Equals(Ipd other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.DistrictName == other.DistrictName || this.DistrictName != null && this.DistrictName.Equals(other.DistrictName) ) && ( this.DistrictType == other.DistrictType || this.DistrictType != null && this.DistrictType.Equals(other.DistrictType) ) && ( this.TaxCodeDescription == other.TaxCodeDescription || this.TaxCodeDescription != null && this.TaxCodeDescription.Equals(other.TaxCodeDescription) ) && ( this.EffectiveDate == other.EffectiveDate || this.EffectiveDate != null && this.EffectiveDate.Equals(other.EffectiveDate) ) && ( this.ExpirationDate == other.ExpirationDate || this.ExpirationDate != null && this.ExpirationDate.Equals(other.ExpirationDate) ) && ( this.BoundaryBuffer == other.BoundaryBuffer || this.BoundaryBuffer != null && this.BoundaryBuffer.Equals(other.BoundaryBuffer) ) && ( this.Rates == other.Rates || this.Rates != null && this.Rates.SequenceEqual(other.Rates) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.DistrictName != null) hash = hash * 59 + this.DistrictName.GetHashCode(); if (this.DistrictType != null) hash = hash * 59 + this.DistrictType.GetHashCode(); if (this.TaxCodeDescription != null) hash = hash * 59 + this.TaxCodeDescription.GetHashCode(); if (this.EffectiveDate != null) hash = hash * 59 + this.EffectiveDate.GetHashCode(); if (this.ExpirationDate != null) hash = hash * 59 + this.ExpirationDate.GetHashCode(); if (this.BoundaryBuffer != null) hash = hash * 59 + this.BoundaryBuffer.GetHashCode(); if (this.Rates != null) hash = hash * 59 + this.Rates.GetHashCode(); return hash; } } } }
using System; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; using System.Collections; namespace fyiReporting.RdlDesign { internal partial class DialogNewChart : System.Windows.Forms.Form { #region Windows Form Designer generated code private DesignXmlDraw _Draw; private System.Windows.Forms.Button bOK; private System.Windows.Forms.Button bCancel; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox cbDataSets; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.ListBox lbFields; private System.Windows.Forms.ListBox lbChartCategories; private System.Windows.Forms.Button bCategoryUp; private System.Windows.Forms.Button bCategoryDown; private System.Windows.Forms.Button bCategory; private System.Windows.Forms.Button bSeries; private System.Windows.Forms.ListBox lbChartSeries; private System.Windows.Forms.Button bCategoryDelete; private System.Windows.Forms.Button bSeriesDelete; private System.Windows.Forms.Button bSeriesDown; private System.Windows.Forms.Button bSeriesUp; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label lChartData; private System.Windows.Forms.ComboBox cbChartData; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox cbSubType; private System.Windows.Forms.ComboBox cbChartType; private System.Windows.Forms.Label label7; private ComboBox cbChartData2; private Label lChartData2; private ComboBox cbChartData3; private Label lChartData3; private System.ComponentModel.Container components = null; private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DialogNewChart)); this.bOK = new System.Windows.Forms.Button(); this.bCancel = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.cbDataSets = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.lbFields = new System.Windows.Forms.ListBox(); this.lbChartCategories = new System.Windows.Forms.ListBox(); this.bCategoryUp = new System.Windows.Forms.Button(); this.bCategoryDown = new System.Windows.Forms.Button(); this.bCategory = new System.Windows.Forms.Button(); this.bSeries = new System.Windows.Forms.Button(); this.lbChartSeries = new System.Windows.Forms.ListBox(); this.bCategoryDelete = new System.Windows.Forms.Button(); this.bSeriesDelete = new System.Windows.Forms.Button(); this.bSeriesDown = new System.Windows.Forms.Button(); this.bSeriesUp = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.lChartData = new System.Windows.Forms.Label(); this.cbChartData = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.cbSubType = new System.Windows.Forms.ComboBox(); this.cbChartType = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.cbChartData2 = new System.Windows.Forms.ComboBox(); this.lChartData2 = new System.Windows.Forms.Label(); this.cbChartData3 = new System.Windows.Forms.ComboBox(); this.lChartData3 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // bOK // resources.ApplyResources(this.bOK, "bOK"); this.bOK.Name = "bOK"; this.bOK.Click += new System.EventHandler(this.bOK_Click); // // bCancel // resources.ApplyResources(this.bCancel, "bCancel"); this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.bCancel.Name = "bCancel"; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // cbDataSets // resources.ApplyResources(this.cbDataSets, "cbDataSets"); this.cbDataSets.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbDataSets.Name = "cbDataSets"; this.cbDataSets.SelectedIndexChanged += new System.EventHandler(this.cbDataSets_SelectedIndexChanged); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // lbFields // resources.ApplyResources(this.lbFields, "lbFields"); this.lbFields.Name = "lbFields"; this.lbFields.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended; // // lbChartCategories // resources.ApplyResources(this.lbChartCategories, "lbChartCategories"); this.lbChartCategories.Name = "lbChartCategories"; // // bCategoryUp // resources.ApplyResources(this.bCategoryUp, "bCategoryUp"); this.bCategoryUp.Name = "bCategoryUp"; this.bCategoryUp.Click += new System.EventHandler(this.bCategoryUp_Click); // // bCategoryDown // resources.ApplyResources(this.bCategoryDown, "bCategoryDown"); this.bCategoryDown.Name = "bCategoryDown"; this.bCategoryDown.Click += new System.EventHandler(this.bCategoryDown_Click); // // bCategory // resources.ApplyResources(this.bCategory, "bCategory"); this.bCategory.Name = "bCategory"; this.bCategory.Click += new System.EventHandler(this.bCategory_Click); // // bSeries // resources.ApplyResources(this.bSeries, "bSeries"); this.bSeries.Name = "bSeries"; this.bSeries.Click += new System.EventHandler(this.bSeries_Click); // // lbChartSeries // resources.ApplyResources(this.lbChartSeries, "lbChartSeries"); this.lbChartSeries.Name = "lbChartSeries"; // // bCategoryDelete // resources.ApplyResources(this.bCategoryDelete, "bCategoryDelete"); this.bCategoryDelete.Name = "bCategoryDelete"; this.bCategoryDelete.Click += new System.EventHandler(this.bCategoryDelete_Click); // // bSeriesDelete // resources.ApplyResources(this.bSeriesDelete, "bSeriesDelete"); this.bSeriesDelete.Name = "bSeriesDelete"; this.bSeriesDelete.Click += new System.EventHandler(this.bSeriesDelete_Click); // // bSeriesDown // resources.ApplyResources(this.bSeriesDown, "bSeriesDown"); this.bSeriesDown.Name = "bSeriesDown"; this.bSeriesDown.Click += new System.EventHandler(this.bSeriesDown_Click); // // bSeriesUp // resources.ApplyResources(this.bSeriesUp, "bSeriesUp"); this.bSeriesUp.Name = "bSeriesUp"; this.bSeriesUp.Click += new System.EventHandler(this.bSeriesUp_Click); // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // lChartData // resources.ApplyResources(this.lChartData, "lChartData"); this.lChartData.Name = "lChartData"; // // cbChartData // resources.ApplyResources(this.cbChartData, "cbChartData"); this.cbChartData.Name = "cbChartData"; this.cbChartData.TextChanged += new System.EventHandler(this.cbChartData_TextChanged); this.cbChartData.Enter += new System.EventHandler(this.cbChartData_Enter); // // label6 // resources.ApplyResources(this.label6, "label6"); this.label6.Name = "label6"; // // cbSubType // resources.ApplyResources(this.cbSubType, "cbSubType"); this.cbSubType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbSubType.Name = "cbSubType"; // // cbChartType // resources.ApplyResources(this.cbChartType, "cbChartType"); this.cbChartType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbChartType.Items.AddRange(new object[] { resources.GetString("cbChartType.Items"), resources.GetString("cbChartType.Items1"), resources.GetString("cbChartType.Items2"), resources.GetString("cbChartType.Items3"), resources.GetString("cbChartType.Items4"), resources.GetString("cbChartType.Items5"), resources.GetString("cbChartType.Items6"), resources.GetString("cbChartType.Items7")}); this.cbChartType.Name = "cbChartType"; this.cbChartType.SelectedIndexChanged += new System.EventHandler(this.cbChartType_SelectedIndexChanged); // // label7 // resources.ApplyResources(this.label7, "label7"); this.label7.Name = "label7"; // // cbChartData2 // resources.ApplyResources(this.cbChartData2, "cbChartData2"); this.cbChartData2.Name = "cbChartData2"; this.cbChartData2.TextChanged += new System.EventHandler(this.cbChartData_TextChanged); this.cbChartData2.Enter += new System.EventHandler(this.cbChartData_Enter); // // lChartData2 // resources.ApplyResources(this.lChartData2, "lChartData2"); this.lChartData2.Name = "lChartData2"; // // cbChartData3 // resources.ApplyResources(this.cbChartData3, "cbChartData3"); this.cbChartData3.Name = "cbChartData3"; this.cbChartData3.TextChanged += new System.EventHandler(this.cbChartData_TextChanged); this.cbChartData3.Enter += new System.EventHandler(this.cbChartData_Enter); // // lChartData3 // resources.ApplyResources(this.lChartData3, "lChartData3"); this.lChartData3.Name = "lChartData3"; // // DialogNewChart // this.AcceptButton = this.bOK; resources.ApplyResources(this, "$this"); this.CancelButton = this.bCancel; this.Controls.Add(this.cbChartData3); this.Controls.Add(this.lChartData3); this.Controls.Add(this.cbChartData2); this.Controls.Add(this.lChartData2); this.Controls.Add(this.label6); this.Controls.Add(this.cbSubType); this.Controls.Add(this.cbChartType); this.Controls.Add(this.label7); this.Controls.Add(this.cbChartData); this.Controls.Add(this.lChartData); this.Controls.Add(this.label4); this.Controls.Add(this.bSeriesDelete); this.Controls.Add(this.bSeriesDown); this.Controls.Add(this.bSeriesUp); this.Controls.Add(this.bCategoryDelete); this.Controls.Add(this.lbChartSeries); this.Controls.Add(this.bSeries); this.Controls.Add(this.bCategory); this.Controls.Add(this.bCategoryDown); this.Controls.Add(this.bCategoryUp); this.Controls.Add(this.lbChartCategories); this.Controls.Add(this.lbFields); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.cbDataSets); this.Controls.Add(this.label1); this.Controls.Add(this.bCancel); this.Controls.Add(this.bOK); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DialogNewChart"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.ResumeLayout(false); } #endregion protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics.Contracts; using Microsoft.Research.DataStructures; namespace Microsoft.Research.CodeAnalysis { [ContractVerification(true)] public class Witness { #region Object Invariant [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(this.Context != null); Contract.Invariant(this.trace != null); } #endregion #region State readonly public APC PC; readonly public uint? SourceProofObligationID; readonly public ProofOutcome Outcome; readonly public WarningType Warning; readonly public ClousotSuggestion.Kind? TypeOfSuggestionTurnedIntoWarning; readonly public Set<WarningContext> Context; readonly private List<KeyValuePair<APC, string>> trace = new List<KeyValuePair<APC, string>>(); public IEnumerable<KeyValuePair<APC, string>> Trace { get { return this.trace.Distinct(new TraceComparer()); } } private double? score; private string justification; private List<string> justification_expanded; #endregion public Witness(uint? sourceProofObligation, WarningType warning, ProofOutcome outcome, APC PC, Set<WarningContext> context, ClousotSuggestion.Kind? type = null) { Contract.Requires(context != null); this.SourceProofObligationID = sourceProofObligation; this.PC = PC; this.Outcome = outcome; this.Warning = warning; this.Context = context; this.TypeOfSuggestionTurnedIntoWarning = type; } public Witness(uint? sourceProofObligation, WarningType warning, ProofOutcome outcome, APC PC, IEnumerable<WarningContext> context, ClousotSuggestion.Kind? type = null) : this(sourceProofObligation, warning, outcome, PC, new Set<WarningContext>(context), type) { Contract.Requires(context != null); } public Witness(uint? sourceProofObligation, WarningType warning, ProofOutcome outcome, APC PC, ClousotSuggestion.Kind? type = null) : this(sourceProofObligation, warning, outcome, PC, new Set<WarningContext>(), type) { } public void AddWarningContext(WarningContext context) { this.Context.Add(context); } public void AddTrace(APC pc, string msg) { this.trace.Add(new KeyValuePair<APC, string>(pc, msg)); } /// <summary> /// Abstraction from WarningType to WarningKind /// </summary> [ContractVerification(true)] public WarningKind WarningKind { get { switch (this.Warning) { case WarningType.ArithmeticDivisionByZero: return WarningKind.DivByZero; case WarningType.ArithmeticDivisionOverflow: return WarningKind.ArithmeticOverflow; case WarningType.ArithmeticMinValueNegation: return WarningKind.MinValueNegation; case WarningType.ArithmeticOverflow: return WarningKind.ArithmeticOverflow; case WarningType.ArithmeticUnderflow: return WarningKind.ArithmeticOverflow; case WarningType.ArithmeticFloatEqualityPrecisionMismatch: return WarningKind.FloatEqualityPrecisionMismatch; case WarningType.ArrayCreation: return WarningKind.ArrayCreation; case WarningType.ArrayLowerBound: return WarningKind.ArrayLowerBound; case WarningType.ArrayUpperBound: return WarningKind.ArrayUpperBound; case WarningType.ArrayPurity: return WarningKind.Purity; case WarningType.ContractAssert: return WarningKind.Assert; case WarningType.ContractEnsures: return WarningKind.Ensures; case WarningType.ContractInvariant: return WarningKind.Invariant; case WarningType.ContractAssume: case WarningType.MissingPreconditionInvolvingReadonly: return WarningKind.Assume; case WarningType.ContractRequires: return WarningKind.Requires; case WarningType.EnumRange: return WarningKind.Enum; case WarningType.MissingPrecondition: return WarningKind.MissingPrecondition; case WarningType.Suggestion: return WarningKind.Suggestion; case WarningType.NonnullArray: case WarningType.NonnullCall: case WarningType.NonnullField: case WarningType.NonnullUnbox: return WarningKind.Nonnull; case WarningType.UnsafeCreation: case WarningType.UnsafeLowerBound: case WarningType.UnsafeUpperBound: return WarningKind.Unsafe; case WarningType.UnreachedCodeAfterPrecondition: case WarningType.TestAlwaysEvaluatingToAConstant: case WarningType.FalseEnsures: case WarningType.FalseRequires: case WarningType.ClousotCacheNotAvailable: return WarningKind.UnreachedCode; // Should be unreachable default: Contract.Assert(false); throw new InvalidOperationException(); } } } #region Comparing traces class TraceComparer : IEqualityComparer<KeyValuePair<APC, string>> { public bool Equals(KeyValuePair<APC, string> x, KeyValuePair<APC, string> y) { return x.Key.Equals(y.Key); } public int GetHashCode(KeyValuePair<APC, string> obj) { return obj.GetHashCode(); } } #endregion #region Scoring logic /// <summary> /// Compute a score for this witness /// </summary> [Pure] // not really... [ContractVerification(true)] public double GetScore(WarningScoresManager scoresManager) { Contract.Requires(scoresManager != null); if (!this.score.HasValue) { EnsureScoreAndJustificationAreComputed(scoresManager); } return this.score.Value; } [Pure] // not really... [ContractVerification(true)] public string GetJustificationString(WarningScoresManager scoreManager) { Contract.Requires(scoreManager != null); if (this.justification == null) { EnsureScoreAndJustificationAreComputed(scoreManager); } return this.justification; } [Pure] // not really... [ContractVerification(true)] public List<string> GetJustificationList(WarningScoresManager scoreManager) { Contract.Requires(scoreManager != null); if (this.justification == null) { EnsureScoreAndJustificationAreComputed(scoreManager); } return this.justification_expanded; } private void EnsureScoreAndJustificationAreComputed(WarningScoresManager scoresManager) { Contract.Ensures(this.score.HasValue); Contract.Ensures(this.justification != null); var pair = scoresManager.GetScore(this); this.score = pair.Item1; this.justification_expanded = pair.Item2; this.justification = String.Join(" ", this.justification_expanded.ToString()); } public string GetWarningLevel(double score, WarningScoresManager scoresManager) { Contract.Requires(scoresManager != null); if (score > scoresManager.LOWSCORE) return "High"; if (score > scoresManager.MEDIUMLOWSCORE) return "MediumHigh"; if (score > scoresManager.MEDIUMSCORE) return "Medium"; return "Low"; } #endregion } public static class WarningContextFetcher { static public IEnumerable<WarningContext> InferContext<Local, Parameter, Method, Field, Typ, ExternalExpression, Variable>( APC pc, BoxedExpression exp, IExpressionContext<Local, Parameter, Method, Field, Typ, ExternalExpression, Variable> context, Predicate<Typ> isBooleanType, Predicate<Field> isReadOnly = null ) where Typ : IEquatable<Typ> { Contract.Ensures(Contract.Result<IEnumerable<WarningContext>>() != null); var collect = new List<WarningContext>(); InferContextInternal(pc, exp, collect, context, true, isBooleanType, isReadOnly); return collect; } static private void InferContextInternal<Local, Parameter, Method, Field, Typ, ExternalExpression, Variable>( APC pc, BoxedExpression exp, System.Collections.Generic.List<WarningContext> result, IExpressionContext<Local, Parameter, Method, Field, Typ, ExternalExpression, Variable> context, bool isFirstCall, Predicate<Typ> isBooleanType, Predicate<Field> isReadOnly = null) where Typ : IEquatable<Typ> { // sanity check if (exp == null) { return; } if (exp is QuantifiedIndexedExpression) { result.Add(new WarningContext(WarningContext.ContextType.MayContainForAllOrADisjunction)); return; } if (exp.IsVariable) { if (exp.UnderlyingVariable is Variable) { var v = (Variable)exp.UnderlyingVariable; // We do a special treatement for the first call, because we want to see if it is a boolean. // In this case, we may have failed proving it for two main reasons: // 1. it is a ForAll not decompiled // 2. it is a disjunction if (isFirstCall) { var type = context.ValueContext.GetType(pc, v); if ((type.IsNormal && isBooleanType(type.Value)) || type.IsTop // Sometimes we get no type with inferred preconditions ) { result.Add(new WarningContext(WarningContext.ContextType.MayContainForAllOrADisjunction)); } } // special case to check if the value comes from the parameters // With the new precondition inference, it is no more the case that we catch it var accessPath = context.ValueContext.AccessPathList(pc, v, false, false); if (accessPath != null && context.ValueContext.PathUnmodifiedSinceEntry(pc, accessPath)) { result.Add(new WarningContext(WarningContext.ContextType.ViaParameterUnmodified)); } var flags = context.ValueContext.PathContexts(pc, v); if ((flags & PathContextFlags.ViaArray) == PathContextFlags.ViaArray) { result.Add(new WarningContext(WarningContext.ContextType.ViaArray, 1)); } if ((flags & PathContextFlags.ViaField) == PathContextFlags.ViaField) { var ro = 0; // If it is a readonly field, then we remember it foreach (var f in context.ValueContext.AccessPathList(pc, (Variable)exp.UnderlyingVariable, false, false).FieldsIn<Field>()) { if (isReadOnly != null && isReadOnly(f)) { ro++; } } if (ro > 0) { result.Add(new WarningContext(WarningContext.ContextType.ContainsReadOnly, ro)); } result.Add(new WarningContext(WarningContext.ContextType.ViaField, 1)); } if ((flags & PathContextFlags.ViaOldValue) == PathContextFlags.ViaOldValue) { result.Add(new WarningContext(WarningContext.ContextType.ViaOldValue, 1)); } if ((flags & PathContextFlags.ViaMethodReturn) == PathContextFlags.ViaMethodReturn) { result.Add(new WarningContext(WarningContext.ContextType.ViaMethodCall, 1)); } if ((flags & PathContextFlags.ViaCast) == PathContextFlags.ViaCast) { result.Add(new WarningContext(WarningContext.ContextType.ViaCast)); } if ((flags & PathContextFlags.ViaOutParameter) == PathContextFlags.ViaOutParameter) { var name = exp.CanPrintAsSourceCode() ? exp.ToString() : null; result.Add(new WarningContext(WarningContext.ContextType.ViaOutParameter, name)); } if((flags & PathContextFlags.ViaPureMethodReturn) == PathContextFlags.ViaPureMethodReturn) { result.Add(new WarningContext(WarningContext.ContextType.ViaPureMethodReturn)); } if (flags.HasFlag(PathContextFlags.ViaCallThisHavoc)) { result.Add(new WarningContext(WarningContext.ContextType.ViaCallThisHavoc)); } } return; } if (exp.IsUnary) { InferContextInternal(pc, exp.UnaryArgument, result, context, false, isBooleanType, isReadOnly); return; } if (exp.IsBinary) { if (exp.BinaryOp == BinaryOperator.LogicalOr) { result.Add(new WarningContext(WarningContext.ContextType.MayContainForAllOrADisjunction)); } InferContextInternal(pc, exp.BinaryLeft, result, context, false, isBooleanType, isReadOnly); InferContextInternal(pc, exp.BinaryRight, result, context, false, isBooleanType, isReadOnly); // Special case for x != null if(exp.BinaryOp == BinaryOperator.Cne_Un) { bool isMethodCall; if(IsVarNotNull(exp.BinaryLeft, exp.BinaryRight, out isMethodCall) || IsVarNotNull(exp.BinaryRight, exp.BinaryLeft, out isMethodCall)) { if (isMethodCall) { result.Add(new WarningContext(WarningContext.ContextType.IsPureMethodCallNotEqNullCheck)); } else { result.Add(new WarningContext(WarningContext.ContextType.IsVarNotEqNullCheck)); } } } return; } object dummy; BoxedExpression inner; if (exp.IsIsInstExpression(out inner, out dummy)) { result.Add(new WarningContext(WarningContext.ContextType.ContainsIsInst)); InferContextInternal(pc, inner, result, context, false, isBooleanType, isReadOnly); return; } } private static bool IsVarNotNull(BoxedExpression left, BoxedExpression right, out bool IsMethodCall) { IsMethodCall = false; if(left == null || right == null) { return false; } if(right.IsNull && (left.IsVariable && left.AccessPath != null && left.AccessPath.Length == 2)) { IsMethodCall = (left.AccessPath[0].IsMethodCall) || (left.AccessPath[1].IsMethodCall); return true; } return false; } } }
// 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, // MERCHANTABILITY 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.ComponentModel.Design; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.PythonTools.Common; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Flavor; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools; using IServiceProvider = System.IServiceProvider; namespace Microsoft.PythonTools.Project.Web { [Guid("742BB562-7AEE-4FC7-8CD2-48D66C8CC435")] partial class PythonWebProject : FlavoredProjectBase, IOleCommandTarget, IVsProjectFlavorCfgProvider, IVsProject, IVsFilterAddProjectItemDlg { private readonly IServiceProvider _site; internal IVsProject _innerProject; internal IVsProject3 _innerProject3; private IVsProjectFlavorCfgProvider _innerVsProjectFlavorCfgProvider; private static readonly Guid PythonProjectGuid = new Guid(PythonConstants.ProjectFactoryGuid); private IOleCommandTarget _menuService; private static readonly Guid PublishCmdGuid = new Guid("{1496a755-94de-11d0-8c3f-00c04fc2aae2}"); private static readonly int PublishCmdid = 2006; public PythonWebProject(IServiceProvider site) { _site = site; } #region IVsAggregatableProject /// <summary> /// Do the initialization here (such as loading flavor specific /// information from the project) /// </summary> protected override void InitializeForOuter(string fileName, string location, string name, uint flags, ref Guid guidProject, out bool cancel) { base.InitializeForOuter(fileName, location, name, flags, ref guidProject, out cancel); var proj = _innerVsHierarchy.GetProject(); if (proj != null) { try { dynamic webAppExtender = proj.get_Extender("WebApplication"); if (webAppExtender != null) { webAppExtender.StartWebServerOnDebug = false; } } catch (COMException) { // extender doesn't exist... } } } #endregion protected override int QueryStatusCommand(uint itemid, ref Guid pguidCmdGroup, uint cCmds, Microsoft.VisualStudio.OLE.Interop.OLECMD[] prgCmds, IntPtr pCmdText) { if (pguidCmdGroup == CommonGuidList.guidOfficeSharePointCmdSet) { for (int i = 0; i < prgCmds.Length; i++) { // Report it as supported so that it's not routed any // further, but disable it and make it invisible. prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE); } return VSConstants.S_OK; } return base.QueryStatusCommand(itemid, ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } protected override void SetInnerProject(IntPtr innerIUnknown) { var inner = Marshal.GetObjectForIUnknown(innerIUnknown); // The reason why we keep a reference to those is that doing a QI after being // aggregated would do the AddRef on the outer object. _innerVsProjectFlavorCfgProvider = inner as IVsProjectFlavorCfgProvider; _innerProject = inner as IVsProject; _innerProject3 = inner as IVsProject3; _innerVsHierarchy = (IVsHierarchy)inner; if (serviceProvider == null) { serviceProvider = _site; } // Now let the base implementation set the inner object base.SetInnerProject(innerIUnknown); // Get access to the menu service used by FlavoredProjectBase. We // need to forward IOleCommandTarget functions to this object, since // we override the FlavoredProjectBase implementation with no way to // call it directory. // (This must run after we called base.SetInnerProject) _menuService = (IOleCommandTarget)((IServiceProvider)this).GetService(typeof(IMenuCommandService)); if (_menuService == null) { throw new InvalidOperationException("Cannot initialize Web project"); } } protected override int GetProperty(uint itemId, int propId, out object property) { switch ((__VSHPROPID2)propId) { case __VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList: { var res = base.GetProperty(itemId, propId, out property); if (ErrorHandler.Succeeded(res)) { var guids = GetGuidsFromList(property as string); guids.RemoveAll(g => CfgSpecificPropertyPagesToRemove.Contains(g)); guids.AddRange(CfgSpecificPropertyPagesToAdd); property = MakeListFromGuids(guids); } return res; } case __VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList: { var res = base.GetProperty(itemId, propId, out property); if (ErrorHandler.Succeeded(res)) { var guids = GetGuidsFromList(property as string); guids.RemoveAll(g => PropertyPagesToRemove.Contains(g)); guids.AddRange(PropertyPagesToAdd); property = MakeListFromGuids(guids); } return res; } } var id8 = (__VSHPROPID8)propId; switch(id8) { case __VSHPROPID8.VSHPROPID_SupportsIconMonikers: property = true; return VSConstants.S_OK; } return base.GetProperty(itemId, propId, out property); } private static Guid[] PropertyPagesToAdd = new[] { new Guid(PythonConstants.WebPropertyPageGuid) }; private static Guid[] CfgSpecificPropertyPagesToAdd = new Guid[0]; private static HashSet<Guid> PropertyPagesToRemove = new HashSet<Guid> { new Guid("{8C0201FE-8ECA-403C-92A3-1BC55F031979}"), // typeof(DeployPropertyPageComClass) new Guid("{ED3B544C-26D8-4348-877B-A1F7BD505ED9}"), // typeof(DatabaseDeployPropertyPageComClass) new Guid("{909D16B3-C8E8-43D1-A2B8-26EA0D4B6B57}"), // Microsoft.VisualStudio.Web.Application.WebPropertyPage new Guid("{379354F2-BBB3-4BA9-AA71-FBE7B0E5EA94}"), // Microsoft.VisualStudio.Web.Application.SilverlightLinksPage }; internal static HashSet<Guid> CfgSpecificPropertyPagesToRemove = new HashSet<Guid> { new Guid("{A553AD0B-2F9E-4BCE-95B3-9A1F7074BC27}"), // Package/Publish Web new Guid("{9AB2347D-948D-4CD2-8DBE-F15F0EF78ED3}"), // Package/Publish SQL }; private static List<Guid> GetGuidsFromList(string guidList) { if (string.IsNullOrEmpty(guidList)) { return new List<Guid>(); } Guid value; return guidList.Split(';') .Select(str => Guid.TryParse(str, out value) ? (Guid?)value : null) .Where(g => g.HasValue) .Select(g => g.Value) .ToList(); } private static string MakeListFromGuids(IEnumerable<Guid> guidList) { return string.Join(";", guidList.Select(g => g.ToString("B"))); } int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (pguidCmdGroup == CommonGuidList.guidWebPackgeCmdId) { if (nCmdID == 0x101 /* EnablePublishToWindowsAzureMenuItem*/) { var shell = (IVsShell)((IServiceProvider)this).GetService(typeof(SVsShell)); var webPublishPackageGuid = CommonGuidList.guidWebPackageGuid; IVsPackage package; int res = shell.LoadPackage(ref webPublishPackageGuid, out package); if (!ErrorHandler.Succeeded(res)) { return res; } var cmdTarget = package as IOleCommandTarget; if (cmdTarget != null) { res = cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); if (ErrorHandler.Succeeded(res)) { // TODO: Check flag to see if we were notified // about being added as a web role. if (!AddWebRoleSupportFiles()) { VsShellUtilities.ShowMessageBox( this, Strings.AddWebRoleSupportFiles, null, OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST ); } } return res; } } } else if (pguidCmdGroup == PublishCmdGuid) { if (nCmdID == PublishCmdid) { // Approximately duplicated in DjangoProject var opts = _site.GetPythonToolsService().SuppressDialogOptions; if (string.IsNullOrEmpty(opts.PublishToAzure30)) { var td = new TaskDialog(_site) { Title = Strings.ProductTitle, MainInstruction = Strings.PublishToAzure30, Content = Strings.PublishToAzure30Message, VerificationText = Strings.DontShowAgain, SelectedVerified = false, AllowCancellation = true, EnableHyperlinks = true }; td.Buttons.Add(TaskDialogButton.OK); td.Buttons.Add(TaskDialogButton.Cancel); if (td.ShowModal() == TaskDialogButton.Cancel) { return VSConstants.S_OK; } if (td.SelectedVerified) { opts.PublishToAzure30 = "true"; opts.Save(); } } } } return _menuService.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } private bool AddWebRoleSupportFiles() { var uiShell = (IVsUIShell)((IServiceProvider)this).GetService(typeof(SVsUIShell)); var emptyGuid = Guid.Empty; var result = new[] { VSADDRESULT.ADDRESULT_Failure }; IntPtr dlgOwner; if (ErrorHandler.Failed(uiShell.GetDialogOwnerHwnd(out dlgOwner))) { dlgOwner = IntPtr.Zero; } var fullTemplate = ((EnvDTE80.Solution2)this.GetDTE().Solution).GetProjectItemTemplate( "AzureCSWebRole.zip", PythonConstants.LanguageName ); return ErrorHandler.Succeeded(_innerProject3.AddItemWithSpecific( (uint)VSConstants.VSITEMID.Root, VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD, "bin", 1, new[] { fullTemplate }, dlgOwner, 0u, ref emptyGuid, string.Empty, ref emptyGuid, result )) && result[0] == VSADDRESULT.ADDRESULT_Success; } int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { if (pguidCmdGroup == CommonGuidList.guidEureka) { for (int i = 0; i < prgCmds.Length; i++) { switch (prgCmds[i].cmdID) { case 0x102: // View in Web Page Inspector from Eureka web tools prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED); return VSConstants.S_OK; } } } else if (pguidCmdGroup == CommonGuidList.guidVenusCmdId) { for (int i = 0; i < prgCmds.Length; i++) { switch (prgCmds[i].cmdID) { case 0x034: /* add app assembly folder */ case 0x035: /* add app code folder */ case 0x036: /* add global resources */ case 0x037: /* add local resources */ case 0x038: /* add web refs folder */ case 0x039: /* add data folder */ case 0x040: /* add browser folders */ case 0x041: /* theme */ case 0x054: /* package settings */ case 0x055: /* context package settings */ prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED); return VSConstants.S_OK; } } } else if (pguidCmdGroup == CommonGuidList.guidWebAppCmdId) { for (int i = 0; i < prgCmds.Length; i++) { switch (prgCmds[i].cmdID) { case 0x06A: /* check accessibility */ prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_DEFHIDEONCTXTMENU | OLECMDF.OLECMDF_ENABLED); return VSConstants.S_OK; } } } else if (pguidCmdGroup == VSConstants.VSStd2K) { for (int i = 0; i < prgCmds.Length; i++) { switch ((VSConstants.VSStd2KCmdID)prgCmds[i].cmdID) { case VSConstants.VSStd2KCmdID.SETASSTARTPAGE: case VSConstants.VSStd2KCmdID.CHECK_ACCESSIBILITY: prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_DEFHIDEONCTXTMENU | OLECMDF.OLECMDF_ENABLED); return VSConstants.S_OK; } } } else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) { for (int i = 0; i < prgCmds.Length; i++) { switch ((VSConstants.VSStd97CmdID)prgCmds[i].cmdID) { case VSConstants.VSStd97CmdID.PreviewInBrowser: case VSConstants.VSStd97CmdID.BrowseWith: prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_DEFHIDEONCTXTMENU | OLECMDF.OLECMDF_ENABLED); return VSConstants.S_OK; } } } return _menuService.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } #region IVsProjectFlavorCfgProvider Members public int CreateProjectFlavorCfg(IVsCfg pBaseProjectCfg, out IVsProjectFlavorCfg ppFlavorCfg) { // We're flavored with a Web Application project and our normal // project... But we don't want the web application project to // influence our config as that alters our debug launch story. We // control that w/ the web project which is actually just letting // the base Python project handle it. So we keep the base Python // project config here. IVsProjectFlavorCfg webCfg; ErrorHandler.ThrowOnFailure( _innerVsProjectFlavorCfgProvider.CreateProjectFlavorCfg( pBaseProjectCfg, out webCfg ) ); ppFlavorCfg = new PythonWebProjectConfig(pBaseProjectCfg, webCfg); return VSConstants.S_OK; } #endregion #region IVsProject Members int IVsProject.AddItem(uint itemidLoc, VSADDITEMOPERATION dwAddItemOperation, string pszItemName, uint cFilesToOpen, string[] rgpszFilesToOpen, IntPtr hwndDlgOwner, VSADDRESULT[] pResult) { return _innerProject.AddItem(itemidLoc, dwAddItemOperation, pszItemName, cFilesToOpen, rgpszFilesToOpen, hwndDlgOwner, pResult); } int IVsProject.GenerateUniqueItemName(uint itemidLoc, string pszExt, string pszSuggestedRoot, out string pbstrItemName) { return _innerProject.GenerateUniqueItemName(itemidLoc, pszExt, pszSuggestedRoot, out pbstrItemName); } int IVsProject.GetItemContext(uint itemid, out VisualStudio.OLE.Interop.IServiceProvider ppSP) { return _innerProject.GetItemContext(itemid, out ppSP); } int IVsProject.GetMkDocument(uint itemid, out string pbstrMkDocument) { return _innerProject.GetMkDocument(itemid, out pbstrMkDocument); } int IVsProject.IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid) { return _innerProject.IsDocumentInProject(pszMkDocument, out pfFound, pdwPriority, out pitemid); } int IVsProject.OpenItem(uint itemid, ref Guid rguidLogicalView, IntPtr punkDocDataExisting, out IVsWindowFrame ppWindowFrame) { return _innerProject.OpenItem(itemid, rguidLogicalView, punkDocDataExisting, out ppWindowFrame); } #endregion #region IVsFilterAddProjectItemDlg Members int IVsFilterAddProjectItemDlg.FilterListItemByLocalizedName(ref Guid rguidProjectItemTemplates, string pszLocalizedName, out int pfFilter) { pfFilter = 0; return VSConstants.S_OK; } int IVsFilterAddProjectItemDlg.FilterListItemByTemplateFile(ref Guid rguidProjectItemTemplates, string pszTemplateFile, out int pfFilter) { pfFilter = 0; return VSConstants.S_OK; } int IVsFilterAddProjectItemDlg.FilterTreeItemByLocalizedName(ref Guid rguidProjectItemTemplates, string pszLocalizedName, out int pfFilter) { pfFilter = 0; return VSConstants.S_OK; } int IVsFilterAddProjectItemDlg.FilterTreeItemByTemplateDir(ref Guid rguidProjectItemTemplates, string pszTemplateDir, out int pfFilter) { // https://pytools.codeplex.com/workitem/1313 // ASP.NET will filter some things out, including .css files, which we don't want it to do. // So we shut that down by not forwarding this to any inner projects, which is fine, because // Python projects don't implement this interface either. pfFilter = 0; return VSConstants.S_OK; } #endregion } }
// SharpMath - C# Mathematical Library /************************************************************************* This file is a part of ALGLIB project. >>> SOURCE LICENSE >>> 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 (www.fsf.org); 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. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************/ using System; namespace SharpMath.LinearAlgebra.AlgLib { internal class safesolve { /************************************************************************* Real implementation of CMatrixScaledTRSafeSolve -- ALGLIB routine -- 21.01.2010 Bochkanov Sergey *************************************************************************/ public static bool rmatrixscaledtrsafesolve(ref double[,] a, double sa, int n, ref double[] x, bool isupper, int trans, bool isunit, double maxgrowth) { bool result = new bool(); double lnmax = 0; double nrmb = 0; double nrmx = 0; int i = 0; AP.Complex alpha = 0; AP.Complex beta = 0; double vr = 0; AP.Complex cx = 0; double[] tmp = new double[0]; int i_ = 0; System.Diagnostics.Debug.Assert(n > 0, "RMatrixTRSafeSolve: incorrect N!"); System.Diagnostics.Debug.Assert(trans == 0 | trans == 1, "RMatrixTRSafeSolve: incorrect Trans!"); result = true; lnmax = Math.Log(AP.Math.MaxRealNumber); // // Quick return if possible // if (n <= 0) { return result; } // // Load norms: right part and X // nrmb = 0; for (i = 0; i <= n - 1; i++) { nrmb = Math.Max(nrmb, Math.Abs(x[i])); } nrmx = 0; // // Solve // tmp = new double[n]; result = true; if (isupper & trans == 0) { // // U*x = b // for (i = n - 1; i >= 0; i--) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } if (i < n - 1) { for (i_ = i + 1; i_ <= n - 1; i_++) { tmp[i_] = sa * a[i, i_]; } vr = 0.0; for (i_ = i + 1; i_ <= n - 1; i_++) { vr += tmp[i_] * x[i_]; } beta = x[i] - vr; } else { beta = x[i]; } // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref cx); if (!result) { return result; } x[i] = cx.x; } return result; } if (!isupper & trans == 0) { // // L*x = b // for (i = 0; i <= n - 1; i++) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } if (i > 0) { for (i_ = 0; i_ <= i - 1; i_++) { tmp[i_] = sa * a[i, i_]; } vr = 0.0; for (i_ = 0; i_ <= i - 1; i_++) { vr += tmp[i_] * x[i_]; } beta = x[i] - vr; } else { beta = x[i]; } // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref cx); if (!result) { return result; } x[i] = cx.x; } return result; } if (isupper & trans == 1) { // // U^T*x = b // for (i = 0; i <= n - 1; i++) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref cx); if (!result) { return result; } x[i] = cx.x; // // update the rest of right part // if (i < n - 1) { vr = cx.x; for (i_ = i + 1; i_ <= n - 1; i_++) { tmp[i_] = sa * a[i, i_]; } for (i_ = i + 1; i_ <= n - 1; i_++) { x[i_] = x[i_] - vr * tmp[i_]; } } } return result; } if (!isupper & trans == 1) { // // L^T*x = b // for (i = n - 1; i >= 0; i--) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref cx); if (!result) { return result; } x[i] = cx.x; // // update the rest of right part // if (i > 0) { vr = cx.x; for (i_ = 0; i_ <= i - 1; i_++) { tmp[i_] = sa * a[i, i_]; } for (i_ = 0; i_ <= i - 1; i_++) { x[i_] = x[i_] - vr * tmp[i_]; } } } return result; } result = false; return result; } /************************************************************************* Internal subroutine for safe solution of SA*op(A)=b where A is NxN upper/lower triangular/unitriangular matrix, op(A) is either identity transform, transposition or Hermitian transposition, SA is a scaling factor such that max(|SA*A[i,j]|) is close to 1.0 in magnutude. This subroutine limits relative growth of solution (in inf-norm) by MaxGrowth, returning False if growth exceeds MaxGrowth. Degenerate or near-degenerate matrices are handled correctly (False is returned) as long as MaxGrowth is significantly less than MaxRealNumber/norm(b). -- ALGLIB routine -- 21.01.2010 Bochkanov Sergey *************************************************************************/ public static bool cmatrixscaledtrsafesolve(ref AP.Complex[,] a, double sa, int n, ref AP.Complex[] x, bool isupper, int trans, bool isunit, double maxgrowth) { bool result = new bool(); double lnmax = 0; double nrmb = 0; double nrmx = 0; int i = 0; AP.Complex alpha = 0; AP.Complex beta = 0; AP.Complex vc = 0; AP.Complex[] tmp = new AP.Complex[0]; int i_ = 0; System.Diagnostics.Debug.Assert(n > 0, "CMatrixTRSafeSolve: incorrect N!"); System.Diagnostics.Debug.Assert(trans == 0 | trans == 1 | trans == 2, "CMatrixTRSafeSolve: incorrect Trans!"); result = true; lnmax = Math.Log(AP.Math.MaxRealNumber); // // Quick return if possible // if (n <= 0) { return result; } // // Load norms: right part and X // nrmb = 0; for (i = 0; i <= n - 1; i++) { nrmb = Math.Max(nrmb, AP.Math.AbsComplex(x[i])); } nrmx = 0; // // Solve // tmp = new AP.Complex[n]; result = true; if (isupper & trans == 0) { // // U*x = b // for (i = n - 1; i >= 0; i--) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } if (i < n - 1) { for (i_ = i + 1; i_ <= n - 1; i_++) { tmp[i_] = sa * a[i, i_]; } vc = 0.0; for (i_ = i + 1; i_ <= n - 1; i_++) { vc += tmp[i_] * x[i_]; } beta = x[i] - vc; } else { beta = x[i]; } // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; } return result; } if (!isupper & trans == 0) { // // L*x = b // for (i = 0; i <= n - 1; i++) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } if (i > 0) { for (i_ = 0; i_ <= i - 1; i_++) { tmp[i_] = sa * a[i, i_]; } vc = 0.0; for (i_ = 0; i_ <= i - 1; i_++) { vc += tmp[i_] * x[i_]; } beta = x[i] - vc; } else { beta = x[i]; } // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; } return result; } if (isupper & trans == 1) { // // U^T*x = b // for (i = 0; i <= n - 1; i++) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; // // update the rest of right part // if (i < n - 1) { for (i_ = i + 1; i_ <= n - 1; i_++) { tmp[i_] = sa * a[i, i_]; } for (i_ = i + 1; i_ <= n - 1; i_++) { x[i_] = x[i_] - vc * tmp[i_]; } } } return result; } if (!isupper & trans == 1) { // // L^T*x = b // for (i = n - 1; i >= 0; i--) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = a[i, i] * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; // // update the rest of right part // if (i > 0) { for (i_ = 0; i_ <= i - 1; i_++) { tmp[i_] = sa * a[i, i_]; } for (i_ = 0; i_ <= i - 1; i_++) { x[i_] = x[i_] - vc * tmp[i_]; } } } return result; } if (isupper & trans == 2) { // // U^H*x = b // for (i = 0; i <= n - 1; i++) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = AP.Math.Conj(a[i, i]) * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; // // update the rest of right part // if (i < n - 1) { for (i_ = i + 1; i_ <= n - 1; i_++) { tmp[i_] = sa * AP.Math.Conj(a[i, i_]); } for (i_ = i + 1; i_ <= n - 1; i_++) { x[i_] = x[i_] - vc * tmp[i_]; } } } return result; } if (!isupper & trans == 2) { // // L^T*x = b // for (i = n - 1; i >= 0; i--) { // // Task is reduced to alpha*x[i] = beta // if (isunit) { alpha = sa; } else { alpha = AP.Math.Conj(a[i, i]) * sa; } beta = x[i]; // // solve alpha*x[i] = beta // result = cbasicsolveandupdate(alpha, beta, lnmax, nrmb, maxgrowth, ref nrmx, ref vc); if (!result) { return result; } x[i] = vc; // // update the rest of right part // if (i > 0) { for (i_ = 0; i_ <= i - 1; i_++) { tmp[i_] = sa * AP.Math.Conj(a[i, i_]); } for (i_ = 0; i_ <= i - 1; i_++) { x[i_] = x[i_] - vc * tmp[i_]; } } } return result; } result = false; return result; } /************************************************************************* complex basic solver-updater for reduced linear system alpha*x[i] = beta solves this equation and updates it in overlfow-safe manner (keeping track of relative growth of solution). Parameters: Alpha - alpha Beta - beta LnMax - precomputed Ln(MaxRealNumber) BNorm - inf-norm of b (right part of original system) MaxGrowth- maximum growth of norm(x) relative to norm(b) XNorm - inf-norm of other components of X (which are already processed) it is updated by CBasicSolveAndUpdate. X - solution -- ALGLIB routine -- 26.01.2009 Bochkanov Sergey *************************************************************************/ private static bool cbasicsolveandupdate(AP.Complex alpha, AP.Complex beta, double lnmax, double bnorm, double maxgrowth, ref double xnorm, ref AP.Complex x) { bool result = new bool(); double v = 0; result = false; if (alpha == 0) { return result; } if (beta != 0) { // // alpha*x[i]=beta // v = Math.Log(AP.Math.AbsComplex(beta)) - Math.Log(AP.Math.AbsComplex(alpha)); if ((double)(v) > (double)(lnmax)) { return result; } x = beta / alpha; } else { // // alpha*x[i]=0 // x = 0; } // // update NrmX, test growth limit // xnorm = Math.Max(xnorm, AP.Math.AbsComplex(x)); if ((double)(xnorm) > (double)(maxgrowth * bnorm)) { return result; } result = true; return result; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osuTK; using osuTK.Graphics; namespace osu.Game.Screens.Edit.Timing { public class ControlPointTable : TableContainer { private const float horizontal_inset = 20; private const float row_height = 25; private const int text_size = 14; private readonly FillFlowContainer backgroundFlow; [Resolved] private Bindable<ControlPointGroup> selectedGroup { get; set; } public ControlPointTable() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Padding = new MarginPadding { Horizontal = horizontal_inset }; RowSize = new Dimension(GridSizeMode.Absolute, row_height); AddInternal(backgroundFlow = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Depth = 1f, Padding = new MarginPadding { Horizontal = -horizontal_inset }, Margin = new MarginPadding { Top = row_height } }); } public IEnumerable<ControlPointGroup> ControlGroups { set { Content = null; backgroundFlow.Clear(); if (value?.Any() != true) return; foreach (var group in value) { backgroundFlow.Add(new RowBackground(group)); } Columns = createHeaders(); Content = value.Select((g, i) => createContent(i, g)).ToArray().ToRectangular(); } } private TableColumn[] createHeaders() { var columns = new List<TableColumn> { new TableColumn(string.Empty, Anchor.Centre, new Dimension(GridSizeMode.AutoSize)), new TableColumn("Time", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)), new TableColumn("Attributes", Anchor.Centre), }; return columns.ToArray(); } private Drawable[] createContent(int index, ControlPointGroup group) => new Drawable[] { new OsuSpriteText { Text = $"#{index + 1}", Font = OsuFont.GetFont(size: text_size, weight: FontWeight.Bold), Margin = new MarginPadding(10) }, new OsuSpriteText { Text = $"{group.Time:n0}ms", Font = OsuFont.GetFont(size: text_size, weight: FontWeight.Bold) }, new ControlGroupAttributes(group), }; private class ControlGroupAttributes : CompositeDrawable { private readonly IBindableList<ControlPoint> controlPoints; private readonly FillFlowContainer fill; public ControlGroupAttributes(ControlPointGroup group) { InternalChild = fill = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Padding = new MarginPadding(10), Spacing = new Vector2(2) }; controlPoints = group.ControlPoints.GetBoundCopy(); controlPoints.ItemsAdded += _ => createChildren(); controlPoints.ItemsRemoved += _ => createChildren(); createChildren(); } private void createChildren() { fill.ChildrenEnumerable = controlPoints.Select(createAttribute).Where(c => c != null); } private Drawable createAttribute(ControlPoint controlPoint) { switch (controlPoint) { case TimingControlPoint timing: return new RowAttribute("timing", () => $"{60000 / timing.BeatLength:n1}bpm {timing.TimeSignature}"); case DifficultyControlPoint difficulty: return new RowAttribute("difficulty", () => $"{difficulty.SpeedMultiplier:n2}x"); case EffectControlPoint effect: return new RowAttribute("effect", () => $"{(effect.KiaiMode ? "Kiai " : "")}{(effect.OmitFirstBarLine ? "NoBarLine " : "")}"); case SampleControlPoint sample: return new RowAttribute("sample", () => $"{sample.SampleBank} {sample.SampleVolume}%"); } return null; } } protected override Drawable CreateHeader(int index, TableColumn column) => new HeaderText(column?.Header ?? string.Empty); private class HeaderText : OsuSpriteText { public HeaderText(string text) { Text = text.ToUpper(); Font = OsuFont.GetFont(size: 12, weight: FontWeight.Black); } } public class RowBackground : OsuClickableContainer { private readonly ControlPointGroup controlGroup; private const int fade_duration = 100; private readonly Box hoveredBackground; [Resolved] private Bindable<ControlPointGroup> selectedGroup { get; set; } public RowBackground(ControlPointGroup controlGroup) { this.controlGroup = controlGroup; RelativeSizeAxes = Axes.X; Height = 25; AlwaysPresent = true; CornerRadius = 3; Masking = true; Children = new Drawable[] { hoveredBackground = new Box { RelativeSizeAxes = Axes.Both, Alpha = 0, }, }; Action = () => selectedGroup.Value = controlGroup; } private Color4 colourHover; private Color4 colourSelected; [BackgroundDependencyLoader] private void load(OsuColour colours) { hoveredBackground.Colour = colourHover = colours.BlueDarker; colourSelected = colours.YellowDarker; } protected override void LoadComplete() { base.LoadComplete(); selectedGroup.BindValueChanged(group => { Selected = controlGroup == group.NewValue; }, true); } private bool selected; protected bool Selected { get => selected; set { if (value == selected) return; selected = value; updateState(); } } protected override bool OnHover(HoverEvent e) { updateState(); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { updateState(); base.OnHoverLost(e); } private void updateState() { hoveredBackground.FadeColour(selected ? colourSelected : colourHover, 450, Easing.OutQuint); if (selected || IsHovered) hoveredBackground.FadeIn(fade_duration, Easing.OutQuint); else hoveredBackground.FadeOut(fade_duration, Easing.OutQuint); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Threading; using System.Diagnostics; using System.Collections; using System.Threading.Tasks; namespace System.Net { // LazyAsyncResult - Base class for all IAsyncResult classes // that want to take advantage of lazy allocated event handles. internal class LazyAsyncResult : IAsyncResult { private const int c_HighBit = unchecked((int)0x80000000); private const int c_ForceAsyncCount = 50; // This is to avoid user mistakes when they queue another async op from a callback the completes sync. [ThreadStatic] private static ThreadContext s_ThreadContext; private static ThreadContext CurrentThreadContext { get { ThreadContext threadContext = s_ThreadContext; if (threadContext == null) { threadContext = new ThreadContext(); s_ThreadContext = threadContext; } return threadContext; } } private class ThreadContext { internal int m_NestedIOCount; } #if DEBUG internal object _DebugAsyncChain = null; // Optionally used to track chains of async calls. private bool _ProtectState; // Used by ContextAwareResult to prevent some calls. #endif // // class members // private object _asyncObject; // Caller's async object. private object _asyncState; // Caller's state object. private AsyncCallback _asyncCallback; // Caller's callback method. private object _result; // Final IO result to be returned byt the End*() method. private int _errorCode; // Win32 error code for Win32 IO async calls (that want to throw). private int _intCompleted; // Sign bit indicates synchronous completion if set. // Remaining bits count the number of InvokeCallbak() calls. private bool _endCalled; // True if the user called the End*() method. private bool _userEvent; // True if the event has been (or is about to be) handed to the user private object _event; // Lazy allocated event to be returned in the IAsyncResult for the client to wait on. internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack) { _asyncObject = myObject; _asyncState = myState; _asyncCallback = myCallBack; _result = DBNull.Value; GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::.ctor()"); } // Allows creating a pre-completed result with less interlockeds. Beware! Constructor calls the callback. // If a derived class ever uses this and overloads Cleanup, this may need to change. internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack, object result) { GlobalLog.Assert(result != DBNull.Value, "LazyAsyncResult#{0}::.ctor()|Result can't be set to DBNull - it's a special internal value.", Logging.HashString(this)); _asyncObject = myObject; _asyncState = myState; _asyncCallback = myCallBack; _result = result; _intCompleted = 1; if (_asyncCallback != null) { GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::Complete() invoking callback"); _asyncCallback(this); } else { GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::Complete() no callback to invoke"); } GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::.ctor() (pre-completed)"); } // Interface method to return the original async object. internal object AsyncObject { get { return _asyncObject; } } // Interface method to return the caller's state object. public object AsyncState { get { return _asyncState; } } protected AsyncCallback AsyncCallback { get { return _asyncCallback; } set { _asyncCallback = value; } } // Interface property to return a WaitHandle that can be waited on for I/O completion. // This property implements lazy event creation. // If this is used, the event cannot be disposed because it is under the control of the // application. Internal should use InternalWaitForCompletion instead - never AsyncWaitHandle. public WaitHandle AsyncWaitHandle { get { GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::get_AsyncWaitHandle()"); #if DEBUG // Can't be called when state is protected. if (_ProtectState) { throw new InvalidOperationException("get_AsyncWaitHandle called in protected state"); } #endif ManualResetEvent asyncEvent; // Indicates that the user has seen the event; it can't be disposed. _userEvent = true; // The user has access to this object. Lock-in CompletedSynchronously. if (_intCompleted == 0) { Interlocked.CompareExchange(ref _intCompleted, c_HighBit, 0); } // Because InternalWaitForCompletion() tries to dispose this event, it's // possible for m_Event to become null immediately after being set, but only if // IsCompleted has become true. Therefore it's possible for this property // to give different (set) events to different callers when IsCompleted is true. asyncEvent = (ManualResetEvent)_event; while (asyncEvent == null) { LazilyCreateEvent(out asyncEvent); } GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::get_AsyncWaitHandle() m_Event:" + Logging.HashString(_event)); return asyncEvent; } } // Returns true if this call created the event. // May return with a null handle. That means it thought it got one, but it was disposed in the mean time. private bool LazilyCreateEvent(out ManualResetEvent waitHandle) { waitHandle = new ManualResetEvent(false); try { if (Interlocked.CompareExchange(ref _event, waitHandle, null) == null) { if (InternalPeekCompleted) { waitHandle.Set(); } return true; } else { waitHandle.Dispose(); waitHandle = (ManualResetEvent)_event; // There's a chance here that m_Event became null. But the only way is if another thread completed // in InternalWaitForCompletion and disposed it. If we're in InternalWaitForCompletion, we now know // IsCompleted is set, so we can avoid the wait when waitHandle comes back null. AsyncWaitHandle // will try again in this case. return false; } } catch { // This should be very rare, but doing this will reduce the chance of deadlock. _event = null; if (waitHandle != null) waitHandle.Dispose(); throw; } } // This allows ContextAwareResult to not let anyone trigger the CompletedSynchronously tripwire while the context is being captured. [Conditional("DEBUG")] protected void DebugProtectState(bool protect) { #if DEBUG _ProtectState = protect; #endif } // Interface property, returning synchronous completion status. public bool CompletedSynchronously { get { GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::get_CompletedSynchronously()"); #if DEBUG // Can't be called when state is protected. if (_ProtectState) { throw new InvalidOperationException("get_CompletedSynchronously called in protected state"); } #endif // If this returns greater than zero, it means it was incremented by InvokeCallback before anyone ever saw it. int result = _intCompleted; if (result == 0) { result = Interlocked.CompareExchange(ref _intCompleted, c_HighBit, 0); } GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::get_CompletedSynchronously() returns: " + ((result > 0) ? "true" : "false")); return result > 0; } } // Interface property, returning completion status. public bool IsCompleted { get { GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::get_IsCompleted()"); #if DEBUG // Can't be called when state is protected. if (_ProtectState) { throw new InvalidOperationException("get_IsCompleted called in protected state"); } #endif // Verify low bits to see if it's been incremented. If it hasn't, set the high bit // to show that it's been looked at. int result = _intCompleted; if (result == 0) { result = Interlocked.CompareExchange(ref _intCompleted, c_HighBit, 0); } return (result & ~c_HighBit) != 0; } } // Use to see if something's completed without fixing CompletedSynchronously. internal bool InternalPeekCompleted { get { return (_intCompleted & ~c_HighBit) != 0; } } // Internal property for setting the IO result. internal object Result { get { return _result == DBNull.Value ? null : _result; } set { // Ideally this should never be called, since setting // the result object really makes sense when the IO completes. // // But if the result was set here (as a preemptive error or for some other reason), // then the "result" parameter passed to InvokeCallback() will be ignored. // It's an error to call after the result has been completed or with DBNull. GlobalLog.Assert(value != DBNull.Value, "LazyAsyncResult#{0}::set_Result()|Result can't be set to DBNull - it's a special internal value.", Logging.HashString(this)); GlobalLog.Assert(!InternalPeekCompleted, "LazyAsyncResult#{0}::set_Result()|Called on completed result.", Logging.HashString(this)); _result = value; } } internal bool EndCalled { get { return _endCalled; } set { _endCalled = value; } } // Internal property for setting the Win32 IO async error code. internal int ErrorCode { get { return _errorCode; } set { _errorCode = value; } } // A method for completing the IO with a result and invoking the user's callback. // Used by derived classes to pass context into an overridden Complete(). Useful // for determining the 'winning' thread in case several may simultaneously call // the equivalent of InvokeCallback(). protected void ProtectedInvokeCallback(object result, IntPtr userToken) { GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::ProtectedInvokeCallback() result = " + (result is Exception ? ((Exception)result).Message : result == null ? "<null>" : result.ToString()) + ", userToken:" + userToken.ToString()); // Critical to disallow DBNull here - it could result in a stuck spinlock in WaitForCompletion. if (result == DBNull.Value) { throw new ArgumentNullException("result"); } #if DEBUG // Always safe to ask for the state now. _ProtectState = false; #endif if ((_intCompleted & ~c_HighBit) == 0 && (Interlocked.Increment(ref _intCompleted) & ~c_HighBit) == 1) { // DBNull.Value is used to guarantee that the first caller wins, // even if the result was set to null. if (_result == DBNull.Value) _result = result; ManualResetEvent asyncEvent = (ManualResetEvent)_event; if (asyncEvent != null) { try { asyncEvent.Set(); } catch (ObjectDisposedException) { // Simply ignore this exception - There is apparently a rare race condition // where the event is disposed before the completion method is called. } } Complete(userToken); } } // A method for completing the IO with a result and invoking the user's callback. internal void InvokeCallback(object result) { ProtectedInvokeCallback(result, IntPtr.Zero); } // A method for completing the IO without a result and invoking the user's callback. internal void InvokeCallback() { ProtectedInvokeCallback(null, IntPtr.Zero); } // // MUST NOT BE CALLED DIRECTLY // A protected method that does callback job and it is guaranteed to be called exactly once. // A derived overriding method must call the base class somewhere or the completion is lost. // protected virtual void Complete(IntPtr userToken) { bool offloaded = false; ThreadContext threadContext = CurrentThreadContext; try { ++threadContext.m_NestedIOCount; if (_asyncCallback != null) { GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::Complete() invoking callback"); if (threadContext.m_NestedIOCount >= c_ForceAsyncCount) { GlobalLog.Print("LazyAsyncResult::Complete *** OFFLOADED the user callback ***"); Task.Factory.StartNew( s => WorkerThreadComplete(s), null, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); offloaded = true; } else { _asyncCallback(this); } } else { GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::Complete() no callback to invoke"); } } finally { --threadContext.m_NestedIOCount; // Never call this method unless interlocked m_IntCompleted check has succeeded (like in this case) if (!offloaded) { Cleanup(); } } } // Only called in the above method private void WorkerThreadComplete(object state) { try { _asyncCallback(this); } finally { Cleanup(); } } // Custom instance cleanup method. // Derived types override this method to release unmanaged resources associated with an IO request. protected virtual void Cleanup() { } internal object InternalWaitForCompletion() { return WaitForCompletion(true); } private object WaitForCompletion(bool snap) { ManualResetEvent waitHandle = null; bool createdByMe = false; bool complete = snap ? IsCompleted : InternalPeekCompleted; if (!complete) { // Not done yet, so wait: waitHandle = (ManualResetEvent)_event; if (waitHandle == null) { createdByMe = LazilyCreateEvent(out waitHandle); } } if (waitHandle != null) { try { GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::InternalWaitForCompletion() Waiting for completion m_Event#" + Logging.HashString(waitHandle)); waitHandle.WaitOne(Timeout.Infinite); } catch (ObjectDisposedException) { // This can occur if this method is called from two different threads. // This possibility is the trade-off for not locking. } finally { // We also want to dispose the event although we can't unless we did wait on it here. if (createdByMe && !_userEvent) { // Does m_UserEvent need to be volatile (or m_Event set via Interlocked) in order // to avoid giving a user a disposed event? ManualResetEvent oldEvent = (ManualResetEvent)_event; _event = null; if (!_userEvent) { oldEvent.Dispose(); } } } } // A race condition exists because InvokeCallback sets m_IntCompleted before m_Result (so that m_Result // can benefit from the synchronization of m_IntCompleted). That means you can get here before m_Result got // set (although rarely - once every eight hours of stress). Handle that case with a spin-lock. SpinWait sw = new SpinWait(); while (_result == DBNull.Value) { sw.SpinOnce(); } GlobalLog.Print("LazyAsyncResult#" + Logging.HashString(this) + "::InternalWaitForCompletion() done: " + (_result is Exception ? ((Exception)_result).Message : _result == null ? "<null>" : _result.ToString())); return _result; } // A general interface that is called to release unmanaged resources associated with the class. // It completes the result but doesn't do any of the notifications. internal void InternalCleanup() { if ((_intCompleted & ~c_HighBit) == 0 && (Interlocked.Increment(ref _intCompleted) & ~c_HighBit) == 1) { // Set no result so that just in case there are waiters, they don't hang in the spin lock. _result = null; Cleanup(); } } } }