context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Web; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web; using Umbraco.ModelsBuilder; using Umbraco.ModelsBuilder.Umbraco; [assembly: PureLiveAssembly] [assembly:ModelsBuilderAssembly(PureLive = true, SourceHash = "d185df4029cb33e8")] [assembly:System.Reflection.AssemblyVersion("0.0.0.1")] // FILE: models.generated.cs //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder v3.0.5.96 // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Umbraco.Web.PublishedContentModels { /// <summary>Blog Post</summary> [PublishedContentModel("BlogPost")] public partial class BlogPost : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "BlogPost"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public BlogPost(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<BlogPost, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public Newtonsoft.Json.Linq.JToken Content { get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("content"); } } ///<summary> /// Introduction ///</summary> [ImplementPropertyType("introduction")] public string Introduction { get { return this.GetPropertyValue<string>("introduction"); } } } /// <summary>Blog Post Repository</summary> [PublishedContentModel("BlogPostRepository")] public partial class BlogPostRepository : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "BlogPostRepository"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public BlogPostRepository(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<BlogPostRepository, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Hide in bottom navigation? ///</summary> [ImplementPropertyType("umbracoNaviHide")] public bool UmbracoNaviHide { get { return this.GetPropertyValue<bool>("umbracoNaviHide"); } } } /// <summary>Home</summary> [PublishedContentModel("Home")] public partial class Home : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "Home"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public Home(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Home, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public Newtonsoft.Json.Linq.JToken Content { get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("content"); } } ///<summary> /// Site Description ///</summary> [ImplementPropertyType("siteDescription")] public string SiteDescription { get { return this.GetPropertyValue<string>("siteDescription"); } } ///<summary> /// Site Logo ///</summary> [ImplementPropertyType("siteLogo")] public object SiteLogo { get { return this.GetPropertyValue("siteLogo"); } } ///<summary> /// Site Title ///</summary> [ImplementPropertyType("siteTitle")] public string SiteTitle { get { return this.GetPropertyValue<string>("siteTitle"); } } } /// <summary>Landing Page</summary> [PublishedContentModel("LandingPage")] public partial class LandingPage : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "LandingPage"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public LandingPage(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<LandingPage, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public Newtonsoft.Json.Linq.JToken Content { get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("content"); } } ///<summary> /// Hide in bottom navigation? ///</summary> [ImplementPropertyType("umbracoNaviHide")] public bool UmbracoNaviHide { get { return this.GetPropertyValue<bool>("umbracoNaviHide"); } } } /// <summary>Text Page</summary> [PublishedContentModel("TextPage")] public partial class TextPage : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "TextPage"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public TextPage(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<TextPage, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public Newtonsoft.Json.Linq.JToken Content { get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("content"); } } } /// <summary>Folder</summary> [PublishedContentModel("Folder")] public partial class Folder : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "Folder"; public new const PublishedItemType ModelItemType = PublishedItemType.Media; #pragma warning restore 0109 public Folder(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Folder, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Contents: ///</summary> [ImplementPropertyType("contents")] public object Contents { get { return this.GetPropertyValue("contents"); } } } /// <summary>Image</summary> [PublishedContentModel("Image")] public partial class Image : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "Image"; public new const PublishedItemType ModelItemType = PublishedItemType.Media; #pragma warning restore 0109 public Image(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Image, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Size ///</summary> [ImplementPropertyType("umbracoBytes")] public string UmbracoBytes { get { return this.GetPropertyValue<string>("umbracoBytes"); } } ///<summary> /// Type ///</summary> [ImplementPropertyType("umbracoExtension")] public string UmbracoExtension { get { return this.GetPropertyValue<string>("umbracoExtension"); } } ///<summary> /// Upload image ///</summary> [ImplementPropertyType("umbracoFile")] public Umbraco.Web.Models.ImageCropDataSet UmbracoFile { get { return this.GetPropertyValue<Umbraco.Web.Models.ImageCropDataSet>("umbracoFile"); } } ///<summary> /// Height ///</summary> [ImplementPropertyType("umbracoHeight")] public string UmbracoHeight { get { return this.GetPropertyValue<string>("umbracoHeight"); } } ///<summary> /// Width ///</summary> [ImplementPropertyType("umbracoWidth")] public string UmbracoWidth { get { return this.GetPropertyValue<string>("umbracoWidth"); } } } /// <summary>File</summary> [PublishedContentModel("File")] public partial class File : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "File"; public new const PublishedItemType ModelItemType = PublishedItemType.Media; #pragma warning restore 0109 public File(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<File, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Size ///</summary> [ImplementPropertyType("umbracoBytes")] public string UmbracoBytes { get { return this.GetPropertyValue<string>("umbracoBytes"); } } ///<summary> /// Type ///</summary> [ImplementPropertyType("umbracoExtension")] public string UmbracoExtension { get { return this.GetPropertyValue<string>("umbracoExtension"); } } ///<summary> /// Upload file ///</summary> [ImplementPropertyType("umbracoFile")] public object UmbracoFile { get { return this.GetPropertyValue("umbracoFile"); } } } /// <summary>Member</summary> [PublishedContentModel("Member")] public partial class Member : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "Member"; public new const PublishedItemType ModelItemType = PublishedItemType.Member; #pragma warning restore 0109 public Member(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Member, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Is Approved ///</summary> [ImplementPropertyType("umbracoMemberApproved")] public bool UmbracoMemberApproved { get { return this.GetPropertyValue<bool>("umbracoMemberApproved"); } } ///<summary> /// Comments ///</summary> [ImplementPropertyType("umbracoMemberComments")] public string UmbracoMemberComments { get { return this.GetPropertyValue<string>("umbracoMemberComments"); } } ///<summary> /// Failed Password Attempts ///</summary> [ImplementPropertyType("umbracoMemberFailedPasswordAttempts")] public string UmbracoMemberFailedPasswordAttempts { get { return this.GetPropertyValue<string>("umbracoMemberFailedPasswordAttempts"); } } ///<summary> /// Last Lockout Date ///</summary> [ImplementPropertyType("umbracoMemberLastLockoutDate")] public string UmbracoMemberLastLockoutDate { get { return this.GetPropertyValue<string>("umbracoMemberLastLockoutDate"); } } ///<summary> /// Last Login Date ///</summary> [ImplementPropertyType("umbracoMemberLastLogin")] public string UmbracoMemberLastLogin { get { return this.GetPropertyValue<string>("umbracoMemberLastLogin"); } } ///<summary> /// Last Password Change Date ///</summary> [ImplementPropertyType("umbracoMemberLastPasswordChangeDate")] public string UmbracoMemberLastPasswordChangeDate { get { return this.GetPropertyValue<string>("umbracoMemberLastPasswordChangeDate"); } } ///<summary> /// Is Locked Out ///</summary> [ImplementPropertyType("umbracoMemberLockedOut")] public bool UmbracoMemberLockedOut { get { return this.GetPropertyValue<bool>("umbracoMemberLockedOut"); } } ///<summary> /// Password Answer ///</summary> [ImplementPropertyType("umbracoMemberPasswordRetrievalAnswer")] public string UmbracoMemberPasswordRetrievalAnswer { get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalAnswer"); } } ///<summary> /// Password Question ///</summary> [ImplementPropertyType("umbracoMemberPasswordRetrievalQuestion")] public string UmbracoMemberPasswordRetrievalQuestion { get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalQuestion"); } } } } // EOF
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace MyWebApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Avatar.Chat { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ChatModule")] public class ChatModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int DEBUG_CHANNEL = 2147483647; private bool m_enabled = true; private int m_saydistance = 20; private int m_shoutdistance = 100; private int m_whisperdistance = 10; internal object m_syncy = new object(); internal IConfig m_config; #region ISharedRegionModule Members public virtual void Initialise(IConfigSource config) { m_config = config.Configs["Chat"]; if (m_config != null) { if (!m_config.GetBoolean("enabled", true)) { m_log.Info("[CHAT]: plugin disabled by configuration"); m_enabled = false; return; } } m_whisperdistance = config.Configs["Chat"].GetInt("whisper_distance", m_whisperdistance); m_saydistance = config.Configs["Chat"].GetInt("say_distance", m_saydistance); m_shoutdistance = config.Configs["Chat"].GetInt("shout_distance", m_shoutdistance); } public virtual void AddRegion(Scene scene) { if (!m_enabled) return; scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnChatFromWorld += OnChatFromWorld; scene.EventManager.OnChatBroadcast += OnChatBroadcast; m_log.InfoFormat("[CHAT]: Initialized for {0} w:{1} s:{2} S:{3}", scene.RegionInfo.RegionName, m_whisperdistance, m_saydistance, m_shoutdistance); } public virtual void RegionLoaded(Scene scene) { if (!m_enabled) return; ISimulatorFeaturesModule featuresModule = scene.RequestModuleInterface<ISimulatorFeaturesModule>(); if (featuresModule != null) featuresModule.OnSimulatorFeaturesRequest += OnSimulatorFeaturesRequest; } public virtual void RemoveRegion(Scene scene) { if (!m_enabled) return; scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnChatFromWorld -= OnChatFromWorld; scene.EventManager.OnChatBroadcast -= OnChatBroadcast; } public virtual void Close() { } public virtual void PostInitialise() { } public Type ReplaceableInterface { get { return null; } } public virtual string Name { get { return "ChatModule"; } } #endregion public virtual void OnNewClient(IClientAPI client) { client.OnChatFromClient += OnChatFromClient; } protected OSChatMessage FixPositionOfChatMessage(OSChatMessage c) { ScenePresence avatar; Scene scene = (Scene)c.Scene; if ((avatar = scene.GetScenePresence(c.Sender.AgentId)) != null) c.Position = avatar.AbsolutePosition; return c; } public virtual void OnChatFromClient(Object sender, OSChatMessage c) { c = FixPositionOfChatMessage(c); // redistribute to interested subscribers Scene scene = (Scene)c.Scene; scene.EventManager.TriggerOnChatFromClient(sender, c); // early return if not on public or debug channel if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; // sanity check: if (c.Sender == null) { m_log.ErrorFormat("[CHAT]: OnChatFromClient from {0} has empty Sender field!", sender); return; } DeliverChatToAvatars(ChatSourceType.Agent, c); } public virtual void OnChatFromWorld(Object sender, OSChatMessage c) { // early return if not on public or debug channel if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; DeliverChatToAvatars(ChatSourceType.Object, c); } protected virtual void DeliverChatToAvatars(ChatSourceType sourceType, OSChatMessage c) { string fromName = c.From; UUID fromID = UUID.Zero; UUID ownerID = UUID.Zero; UUID targetID = c.TargetUUID; string message = c.Message; Scene scene = (Scene)c.Scene; Vector3 fromPos = c.Position; Vector3 regionPos = new Vector3(scene.RegionInfo.WorldLocX, scene.RegionInfo.WorldLocY, 0); if (c.Channel == DEBUG_CHANNEL) c.Type = ChatTypeEnum.DebugChannel; switch (sourceType) { case ChatSourceType.Agent: ScenePresence avatar = scene.GetScenePresence(c.Sender.AgentId); fromPos = avatar.AbsolutePosition; fromName = avatar.Name; fromID = c.Sender.AgentId; ownerID = c.Sender.AgentId; break; case ChatSourceType.Object: fromID = c.SenderUUID; if (c.SenderObject != null && c.SenderObject is SceneObjectPart) ownerID = ((SceneObjectPart)c.SenderObject).OwnerID; break; } // TODO: iterate over message if (message.Length >= 1000) // libomv limit message = message.Substring(0, 1000); // m_log.DebugFormat( // "[CHAT]: DCTA: fromID {0} fromName {1}, region{2}, cType {3}, sType {4}, targetID {5}", // fromID, fromName, scene.RegionInfo.RegionName, c.Type, sourceType, targetID); HashSet<UUID> receiverIDs = new HashSet<UUID>(); if (targetID == UUID.Zero) { // This should use ForEachClient, but clients don't have a position. // If camera is moved into client, then camera position can be used scene.ForEachScenePresence( delegate(ScenePresence presence) { if (TrySendChatMessage( presence, fromPos, regionPos, fromID, ownerID, fromName, c.Type, message, sourceType, false)) receiverIDs.Add(presence.UUID); } ); } else { // This is a send to a specific client eg from llRegionSayTo // no need to check distance etc, jand send is as say ScenePresence presence = scene.GetScenePresence(targetID); if (presence != null && !presence.IsChildAgent) { if (TrySendChatMessage( presence, fromPos, regionPos, fromID, ownerID, fromName, ChatTypeEnum.Say, message, sourceType, true)) receiverIDs.Add(presence.UUID); } } scene.EventManager.TriggerOnChatToClients( fromID, receiverIDs, message, c.Type, fromPos, fromName, sourceType, ChatAudibleLevel.Fully); } static private Vector3 CenterOfRegion = new Vector3(128, 128, 30); public virtual void OnChatBroadcast(Object sender, OSChatMessage c) { if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; ChatTypeEnum cType = c.Type; if (c.Channel == DEBUG_CHANNEL) cType = ChatTypeEnum.DebugChannel; if (cType == ChatTypeEnum.Region) cType = ChatTypeEnum.Say; if (c.Message.Length > 1100) c.Message = c.Message.Substring(0, 1000); // broadcast chat works by redistributing every incoming chat // message to each avatar in the scene. string fromName = c.From; UUID fromID = UUID.Zero; UUID ownerID = UUID.Zero; ChatSourceType sourceType = ChatSourceType.Object; if (null != c.Sender) { ScenePresence avatar = (c.Scene as Scene).GetScenePresence(c.Sender.AgentId); fromID = c.Sender.AgentId; fromName = avatar.Name; ownerID = c.Sender.AgentId; sourceType = ChatSourceType.Agent; } else if (c.SenderUUID != UUID.Zero) { fromID = c.SenderUUID; ownerID = ((SceneObjectPart)c.SenderObject).OwnerID; } // m_log.DebugFormat("[CHAT] Broadcast: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, cType, sourceType); HashSet<UUID> receiverIDs = new HashSet<UUID>(); ((Scene)c.Scene).ForEachRootClient( delegate(IClientAPI client) { // don't forward SayOwner chat from objects to // non-owner agents if ((c.Type == ChatTypeEnum.Owner) && (null != c.SenderObject) && (((SceneObjectPart)c.SenderObject).OwnerID != client.AgentId)) return; client.SendChatMessage( c.Message, (byte)cType, CenterOfRegion, fromName, fromID, ownerID, (byte)sourceType, (byte)ChatAudibleLevel.Fully); receiverIDs.Add(client.AgentId); }); (c.Scene as Scene).EventManager.TriggerOnChatToClients( fromID, receiverIDs, c.Message, cType, CenterOfRegion, fromName, sourceType, ChatAudibleLevel.Fully); } /// <summary> /// Try to send a message to the given presence /// </summary> /// <param name="presence">The receiver</param> /// <param name="fromPos"></param> /// <param name="regionPos">/param> /// <param name="fromAgentID"></param> /// <param name='ownerID'> /// Owner of the message. For at least some messages from objects, this has to be correctly filled with the owner's UUID. /// This is the case for script error messages in viewer 3 since LLViewer change EXT-7762 /// </param> /// <param name="fromName"></param> /// <param name="type"></param> /// <param name="message"></param> /// <param name="src"></param> /// <returns>true if the message was sent to the receiver, false if it was not sent due to failing a /// precondition</returns> protected virtual bool TrySendChatMessage( ScenePresence presence, Vector3 fromPos, Vector3 regionPos, UUID fromAgentID, UUID ownerID, string fromName, ChatTypeEnum type, string message, ChatSourceType src, bool ignoreDistance) { if (presence.LifecycleState != ScenePresenceState.Running) return false; if (!ignoreDistance) { Vector3 fromRegionPos = fromPos + regionPos; Vector3 toRegionPos = presence.AbsolutePosition + new Vector3(presence.Scene.RegionInfo.WorldLocX, presence.Scene.RegionInfo.WorldLocY, 0); int dis = (int)Util.GetDistanceTo(toRegionPos, fromRegionPos); if (type == ChatTypeEnum.Whisper && dis > m_whisperdistance || type == ChatTypeEnum.Say && dis > m_saydistance || type == ChatTypeEnum.Shout && dis > m_shoutdistance) { return false; } } // TODO: should change so the message is sent through the avatar rather than direct to the ClientView presence.ControllingClient.SendChatMessage( message, (byte) type, fromPos, fromName, fromAgentID, ownerID, (byte)src, (byte)ChatAudibleLevel.Fully); return true; } #region SimulatorFeaturesRequest static OSDInteger m_SayRange, m_WhisperRange, m_ShoutRange; private void OnSimulatorFeaturesRequest(UUID agentID, ref OSDMap features) { OSD extras = new OSDMap(); if (features.ContainsKey("OpenSimExtras")) extras = features["OpenSimExtras"]; else features["OpenSimExtras"] = extras; if (m_SayRange == null) { // Do this only once m_SayRange = new OSDInteger(m_saydistance); m_WhisperRange = new OSDInteger(m_whisperdistance); m_ShoutRange = new OSDInteger(m_shoutdistance); } ((OSDMap)extras)["say-range"] = m_SayRange; ((OSDMap)extras)["whisper-range"] = m_WhisperRange; ((OSDMap)extras)["shout-range"] = m_ShoutRange; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; using NuGet; using NuGet.VisualStudio; using NuGet.VisualStudio.Resources; namespace NuGetConsole.Host.PowerShell.Implementation { internal abstract class PowerShellHost : IHost, IPathExpansion, IDisposable { private static readonly object _lockObject = new object(); private readonly string _name; private readonly IRunspaceManager _runspaceManager; private readonly IPackageSourceProvider _packageSourceProvider; private readonly ISolutionManager _solutionManager; private readonly IVsPackageManagerFactory _packageManagerFactory; private string _targetDir; private bool _updateWorkingDirectoryPending; private IConsole _activeConsole; private Runspace _runspace; private NuGetPSHost _nugetHost; // indicates whether this host has been initialized. // null = not initilized, true = initialized successfully, false = initialized unsuccessfully private bool? _initialized; // store the current command typed so far private ComplexCommand _complexCommand; protected PowerShellHost(string name, IRunspaceManager runspaceManager) { _runspaceManager = runspaceManager; // TODO: Take these as ctor arguments _packageSourceProvider = ServiceLocator.GetInstance<IPackageSourceProvider>(); _solutionManager = ServiceLocator.GetInstance<ISolutionManager>(); _packageManagerFactory = ServiceLocator.GetInstance<IVsPackageManagerFactory>(); _name = name; IsCommandEnabled = true; } protected Pipeline ExecutingPipeline { get; set; } /// <summary> /// The host is associated with a particular console on a per-command basis. /// This gets set every time a command is executed on this host. /// </summary> protected IConsole ActiveConsole { get { return _activeConsole; } set { _activeConsole = value; if (_nugetHost != null) { _nugetHost.ActiveConsole = value; } } } public bool IsCommandEnabled { get; private set; } protected Runspace Runspace { get { Debug.Assert(_initialized != null); return _runspace; } } private ComplexCommand ComplexCommand { get { if (_complexCommand == null) { _complexCommand = new ComplexCommand((allLines, lastLine) => { Collection<PSParseError> errors; PSParser.Tokenize(allLines, out errors); // If there is a parse error token whose END is past input END, consider // it a multi-line command. if (errors.Count > 0) { if (errors.Any(e => (e.Token.Start + e.Token.Length) >= allLines.Length)) { return false; } } return true; }); } return _complexCommand; } } public string Prompt { get { return ComplexCommand.IsComplete ? EvaluatePrompt() : ">> "; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private string EvaluatePrompt() { string prompt = "PM>"; try { PSObject output = this.Runspace.Invoke("prompt", null, outputResults: false).FirstOrDefault(); if (output != null) { string result = output.BaseObject.ToString(); if (!String.IsNullOrEmpty(result)) { prompt = result; } } } catch (Exception ex) { ExceptionHelper.WriteToActivityLog(ex); } return prompt; } /// <summary> /// Doing all necessary initialization works before the console accepts user inputs /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void Initialize(IConsole console) { ActiveConsole = console; if (_initialized.HasValue) { if (_initialized.Value && console.ShowDisclaimerHeader) { DisplayDisclaimerAndHelpText(); } } else { try { Tuple<Runspace, NuGetPSHost> tuple = _runspaceManager.GetRunspace(console, _name); _runspace = tuple.Item1; _nugetHost = tuple.Item2; _initialized = true; // when initializing host from the dialog, we don't want to execute existing init scripts in the solution, if any. if (console.ShowDisclaimerHeader) { DisplayDisclaimerAndHelpText(); } _solutionManager.SolutionOpened += (o, e) => { UpdateWorkingDirectory(); ExecuteInitScripts(); }; UpdateWorkingDirectory(); ExecuteInitScripts(); _solutionManager.SolutionClosed += (o, e) => UpdateWorkingDirectory(); } catch (Exception ex) { // catch all exception as we don't want it to crash VS _initialized = false; IsCommandEnabled = false; ReportError(ex); ExceptionHelper.WriteToActivityLog(ex); } } } private void UpdateWorkingDirectory() { string targetDir; if (_solutionManager.IsSolutionOpen) { targetDir = "'" + _solutionManager.SolutionDirectory + "'"; } else { // if there is no solution open, we set the active directory to be user profile folder targetDir = "$Env:USERPROFILE"; } if (Runspace.RunspaceAvailability == RunspaceAvailability.Available) { Runspace.ChangePSDirectory(targetDir); } else { // If we are in the middle of executing some other scripts, which triggerred the solution to be opened/closed, then we // can't execute Set-Location here because of reentrancy policy. So we save the location and change it later when the // executing command finishes running. _targetDir = targetDir; _updateWorkingDirectoryPending = true; } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want execution of init scripts to crash our console.")] private void ExecuteInitScripts() { if (!String.IsNullOrEmpty(_solutionManager.SolutionDirectory)) { try { var packageManager = (VsPackageManager)_packageManagerFactory.CreatePackageManager(); var localRepository = packageManager.LocalRepository; // invoke init.ps1 files in the order of package dependency. // if A -> B, we invoke B's init.ps1 before A's. var sorter = new PackageSorter(); var sortedPackages = sorter.GetPackagesByDependencyOrder(localRepository); foreach (var package in sortedPackages) { string installPath = packageManager.PathResolver.GetInstallPath(package); AddPathToEnvironment(Path.Combine(installPath, "tools")); Runspace.ExecuteScript(installPath, "tools\\init.ps1", package); } } catch (Exception ex) { // if execution of Init scripts fails, do not let it crash our console ReportError(ex); ExceptionHelper.WriteToActivityLog(ex); } } } private static void AddPathToEnvironment(string path) { if (Directory.Exists(path)) { string environmentPath = Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Process); environmentPath = environmentPath + ";" + path; Environment.SetEnvironmentVariable("path", environmentPath, EnvironmentVariableTarget.Process); } } protected abstract bool ExecuteHost(string fullCommand, string command, params object[] inputs); public bool Execute(IConsole console, string command, params object[] inputs) { if (console == null) { throw new ArgumentNullException("console"); } if (command == null) { throw new ArgumentNullException("command"); } _updateWorkingDirectoryPending = false; ActiveConsole = console; string fullCommand; if (ComplexCommand.AddLine(command, out fullCommand) && !string.IsNullOrEmpty(fullCommand)) { return ExecuteHost(fullCommand, command, inputs); } return false; // constructing multi-line command } protected void OnExecuteCommandEnd() { if (_updateWorkingDirectoryPending == true) { Runspace.ChangePSDirectory(_targetDir); _updateWorkingDirectoryPending = false; _targetDir = null; } } public void Abort() { if (ExecutingPipeline != null) { ExecutingPipeline.StopAsync(); } ComplexCommand.Clear(); } protected void SetSyncModeOnHost(bool isSync) { if (_nugetHost != null) { PSPropertyInfo property = _nugetHost.PrivateData.Properties["IsSyncMode"]; if (property == null) { property = new PSNoteProperty("IsSyncMode", isSync); _nugetHost.PrivateData.Properties.Add(property); } else { property.Value = isSync; } } } public void SetDefaultRunspace() { if (Runspace.DefaultRunspace == null) { lock (_lockObject) { if (Runspace.DefaultRunspace == null) { // Set this runspace as DefaultRunspace so I can script DTE events. // // WARNING: MSDN says this is unsafe. The runspace must not be shared across // threads. I need this to be able to use ScriptBlock for DTE events. The // ScriptBlock event handlers execute on DefaultRunspace. Runspace.DefaultRunspace = Runspace; } } } } private void DisplayDisclaimerAndHelpText() { WriteLine(VsResources.Console_DisclaimerText); WriteLine(); WriteLine(String.Format(CultureInfo.CurrentCulture, Resources.PowerShellHostTitle, _nugetHost.Version.ToString())); WriteLine(); WriteLine(VsResources.Console_HelpText); WriteLine(); } protected void ReportError(ErrorRecord record) { WriteErrorLine(Runspace.ExtractErrorFromErrorRecord(record)); } protected void ReportError(Exception exception) { WriteErrorLine((exception.InnerException ?? exception).Message); } private void WriteErrorLine(string message) { if (ActiveConsole != null) { ActiveConsole.Write(message + Environment.NewLine, System.Windows.Media.Colors.Red, null); } } private void WriteLine(string message = "") { if (ActiveConsole != null) { ActiveConsole.WriteLine(message); } } public string ActivePackageSource { get { var activePackageSource = _packageSourceProvider.ActivePackageSource; return activePackageSource == null ? null : activePackageSource.Name; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } _packageSourceProvider.ActivePackageSource = _packageSourceProvider.GetPackageSources().FirstOrDefault( ps => ps.Name.Equals(value, StringComparison.OrdinalIgnoreCase)); } } public string[] GetPackageSources() { return _packageSourceProvider.GetPackageSources().Select(ps => ps.Name).ToArray(); } public string DefaultProject { get { Debug.Assert(_solutionManager != null); return _solutionManager.DefaultProjectName; } set { Debug.Assert(_solutionManager != null); _solutionManager.DefaultProjectName = value; } } public string[] GetAvailableProjects() { Debug.Assert(_solutionManager != null); var projectSafeNames = (_solutionManager.GetProjects().Select(p => _solutionManager.GetProjectSafeName(p))).ToArray(); return projectSafeNames; } #region ITabExpansion public string[] GetExpansions(string line, string lastWord) { var query = from s in Runspace.Invoke( "$__pc_args=@(); $input|%{$__pc_args+=$_}; TabExpansion $__pc_args[0] $__pc_args[1]; Remove-Variable __pc_args -Scope 0", new string[] { line, lastWord }, outputResults: false) select (s == null ? null : s.ToString()); return query.ToArray(); } #endregion #region IPathExpansion public SimpleExpansion GetPathExpansions(string line) { PSObject expansion = Runspace.Invoke( "$input|%{$__pc_args=$_}; _TabExpansionPath $__pc_args; Remove-Variable __pc_args -Scope 0", new object[] { line }, outputResults: false).FirstOrDefault(); if (expansion != null) { int replaceStart = (int)expansion.Properties["ReplaceStart"].Value; IList<string> paths = ((IEnumerable<object>)expansion.Properties["Paths"].Value).Select(o => o.ToString()).ToList(); return new SimpleExpansion(replaceStart, line.Length - replaceStart, paths); } return null; } #endregion #region IDisposable public void Dispose() { if (_runspace != null) { _runspace.Dispose(); } } #endregion } }
using System; using System.Collections.Generic; using System.Reflection; namespace GenericSharingTest { public delegate int IntVoidDelegate (); public class ClassA {} public class ClassB {} public class ClassC {} public class GenExc<T> : Exception {} public class NonGen { public static int field = 123; public static void doThrow () { throw new GenExc<ClassA> (); } } public class GenBi<S,T> { public static int field = 123; public static float floatField = 1.0f; public static int staticMethod (int x) { return x + field; } public static void staticVoidMethod (int x) { field = x; } public static float staticFloatMethod () { return floatField; } public static long staticLongMethod (long x) { return x + field; } public static GenStruct<T> staticValueMethod (int x) { return new GenStruct<T> (x); } } public struct GenStruct<T> { public static int staticField; public int field; public int dummy1; public int dummy2; public int dummy3; public GenStruct (int f) { field = f; dummy1 = dummy2 = dummy3 = 0; } public int method (int x) { return x + field; } } public interface IGen<T> { T[] iMethod (); void voidIMethod (int x); long longIMethod (long x); float floatIMethod (); GenStruct<T> valueIMethod (int x); } public class IGenImpl<T> : IGen<T> { public int field; public T[] iMethod () { return new T[3]; } public void voidIMethod (int x) { field = x; } public long longIMethod (long x) { return x + 1; } public float floatIMethod () { return 1.0f; } public GenStruct<T> valueIMethod (int x) { return new GenStruct<T> (x); } } public class GenA<T> { public static T[] arr; static GenA () { arr = new T [3]; } public GenA () {} public GenA<T> newGen () { return new GenA<T> (); } public GenA<int> newGenInt () { return new GenA<int> (); } public int getGenField () { return GenB<ClassA>.field; } public int getNonGenField () { return NonGen.field; } public int getGenStructStaticField () { return GenStruct<T>.staticField; } public T[] getArr () { return arr; } public T[] newArr () { return new T [3]; } public GenA<T>[] newSelfArr () { return new GenA<T> [3]; } public GenB<GenB<T>>[] newArrNested () { /* GenB<GenB<T>>[] arr = null; for (int i = 0; i < 10000000; ++i) arr = new GenB<GenB<T>> [3]; */ return new GenB<GenB<T>> [3]; } public int hash (T obj) { return obj.GetHashCode (); } public T ident (T obj) { return obj; } public T cast (Object obj) { return (T)obj; } public GenStruct<T> structCast (Object obj) { return (GenStruct<T>)obj; } public Type ldtokenT () { return typeof (T); } public Type ldtokenIGenT () { return typeof (IGen<T>); } public Type ldtokenGenAIGenT () { return typeof (GenA<IGen<T>>); } public Type ldtokenGenB () { return typeof (GenB<>); } public GenStruct<T>? makeNullable (Object obj) { return (GenStruct<T>?)obj; } public object unmakeNullable (GenStruct<T>? obj) { return (object)obj; } public void except () { try { NonGen.doThrow (); } catch (GenExc<T>) { //Console.WriteLine("exception thrown"); } } public static void staticExcept () { try { NonGen.doThrow (); } catch (GenExc<T>) { Console.WriteLine("exception thrown and caught"); } } public static int staticField = 54321; public static int staticMethod () { return staticField; } public static int staticMethodCaller () { return staticMethod (); } public static float staticFloatField = 1.0f; public static float staticFloatMethod () { return staticFloatField; } public static int staticBiCaller (int x) { return GenBi<int,T>.staticMethod (x); } public static void staticBiVoidCaller (int x) { GenBi<int,T>.staticVoidMethod (x); } public static float staticBiFloatCaller () { return GenBi<int,T>.staticFloatMethod (); } public static GenStruct<T> staticBiValueCaller (int x) { return GenBi<int,T>.staticValueMethod (x); } public static int staticSharedBiCaller (int x) { return GenBi<T,T>.staticMethod (x); } public static void staticSharedBiVoidCaller (int x) { GenBi<T,T>.staticVoidMethod (x); } public static float staticSharedBiFloatCaller () { return GenBi<T,T>.staticFloatMethod (); } public static GenStruct<T> staticSharedBiValueCaller (int x) { return GenBi<T,T>.staticValueMethod (x); } public static long staticBiLongCaller (long x) { return GenBi<int, T>.staticLongMethod (x); } public int structCaller (int x) { GenStruct<GenA<T>> gs = new GenStruct<GenA<T>> (123); return gs.method (x); } public T[] callInterface (IGen<T> ig) { return ig.iMethod (); } public void callVoidInterface (IGen<T> ig, int x) { ig.voidIMethod (x); } public long callLongInterface (IGen<T> ig, long x) { return ig.longIMethod (x); } public float callFloatInterface (IGen<T> ig) { return ig.floatIMethod (); } public GenStruct<T> callValueInterface (IGen<T> ig, int x) { return ig.valueIMethod (x); } } public class GenB<T> { public static int field = 123; } public class GenC<T> { public static int field ; static GenC () { field = 1234; } } public class StaticTest<T> { static int stat; public StaticTest (int x) { stat = x; } public int getStat () { return stat; } public int getOtherStat () { return StaticTest<Object>.stat; } public int getGenCStat () { return GenC<T>.field; } } public class GenADeriv<T> : GenA<T> { public static int otherField = 123; } public class GenABDeriv<T> : GenA<GenB<T>> { public T[] newDerivArr () { return new T [3]; } } public class NonGenUser<T> where T : NonGen { public int getNonGenField () { return NonGen.field; } } public class AccessTest<T> { private static int field = 123; public int getOtherField () { return AccessTest<int>.field; } } public class VirtualTest<T> { public virtual T[] newArr () { return new T [3]; } } public class VirtualTestDeriv<T> : VirtualTest<T> { public override T[] newArr () { return new T [4]; } } public class VirtualTestCaller<T> { public T[] doCall (VirtualTest<T> vt) { return vt.newArr (); } } public class MyCons<T> { public T car; public MyCons<T> cdr; public static void printCar (T _car) { Console.WriteLine ("car " + _car.ToString () /* + " cdr " + _cdr.ToString () */); } public MyCons (T _car, MyCons<T> _cdr) { //printCar (_car); car = _car; cdr = _cdr; } public static MyCons<T> returnList (MyCons<T> l) { return l; } public static MyCons<T> returnCdr (MyCons<T> cons) { return returnList(cons.cdr); } } public class MyPair<N,M> { public N n; public M m; public MyPair (N _n, M _m) { n = _n; m = _m; } } public class MyDict<N,M> { public MyPair<N,M> p; public MyDict (N n, M m) { p = new MyPair<N,M> (n, m); } } public class RGCTXTest<T> { public GenA<T>[] newAArr () { return new GenA<T> [3]; } } public class RGCTXTestSubA<T> : RGCTXTest<T> { public GenB<T>[] newBArr () { return new GenB<T> [3]; } } public class RGCTXTestSubB<T> : RGCTXTest<T> { public GenC<T>[] newCArr () { return new GenC<T> [3]; } } public class RGCTXTestSubASub : RGCTXTestSubA<ClassA> { } public class RGCTXTestSubASubSub<T> : RGCTXTestSubASub { public GenC<T>[] newCArr () { return new GenC<T> [3]; } } public class main { delegate void ActionDelegate (); static bool haveError = false; static void error (string message) { haveError = true; Console.WriteLine (message); } static void typeCheck (String method, Object obj, Type t) { if (obj.GetType () != t) error ("object from " + method + " should have type " + t.ToString () + " but has type " + obj.GetType ().ToString ()); } static int callStaticMethod<T> () { return GenA<T>.staticMethod (); } static void checkException<T> (String method, ActionDelegate action) where T : Exception { try { try { action (); } catch (T) { return; } } catch (Exception exc) { error ("method " + method + " should have thrown " + typeof (T).ToString () + " but did throw " + exc); } } public static void work<T> (T obj, bool mustCatch) { EqualityComparer<T> comp = EqualityComparer<T>.Default; GenA<T> ga = new GenA<T> (); typeCheck ("newGen", ga.newGen (), typeof (GenA<T>)); typeCheck ("newGenInt", ga.newGenInt (), typeof (GenA<int>)); typeCheck ("getArr", ga.getArr (), typeof (T[])); typeCheck ("newArr", ga.newArr (), typeof (T[])); typeCheck ("newSelfArr", ga.newSelfArr (), typeof (GenA<T>[])); //ga.newArrNested (); typeCheck ("newArrNested", ga.newArrNested (), typeof (GenB<GenB<T>>[])); if (ga.getGenField () != 123) error ("getGenField"); if (ga.getNonGenField () != 123) error ("getNonGenField"); GenStruct<T>.staticField = 321; if (ga.getGenStructStaticField () != 321) error ("getGenStructStaticField"); GenStruct<T>.staticField = -1; ga.hash (obj); if (!comp.Equals (ga.ident (obj), obj)) error ("ident"); if (!comp.Equals (ga.cast (obj), obj)) error ("cast"); if (typeof (T).IsValueType) { checkException<NullReferenceException> ("cast null value", delegate { ga.cast (null); }); } else { if (ga.cast (null) != null) error ("cast null"); } GenStruct<T> genstructt = new GenStruct<T> (453); if (ga.structCast ((object)genstructt).field != 453) error ("structCast"); checkException<NullReferenceException> ("structCast null", delegate { ga.structCast (null); }); if (ga.makeNullable ((object)genstructt).Value.field != 453) error ("makeNullable"); if (ga.makeNullable (null) != null) error ("makeNullable null"); if (ga.ldtokenT () != typeof (T)) error ("ldtokenT"); if (ga.ldtokenIGenT () != typeof (IGen<T>)) error ("ldtokenIGenT"); if (ga.ldtokenGenAIGenT () != typeof (GenA<IGen<T>>)) error ("ldtokenGenAIGenT"); if (ga.ldtokenGenB () != typeof (GenB<>)) error ("ldtokenGenB"); if (callStaticMethod<T> () != 54321) error ("staticMethod"); GenBi<int,T>.field = 123; if (GenA<T>.staticBiCaller (123) != 246) error ("staticBiCaller"); GenA<T>.staticBiVoidCaller (1234); if (GenBi<int,T>.field != 1234) error ("staticBiVoidCaller"); if (GenA<T>.staticBiFloatCaller () != 1.0f) error ("staticBiFloatCaller"); if (GenA<T>.staticBiLongCaller (123) != 123 + 1234) error ("staticBiLongCaller"); GenStruct<T> gs = GenA<T>.staticBiValueCaller (987); if (gs.field != 987) error ("staticBiValueCaller"); GenBi<T,T>.field = 123; if (GenA<T>.staticSharedBiCaller (123) != 246) error ("staticSharedBiCaller"); GenA<T>.staticSharedBiVoidCaller (1234); if (GenBi<T,T>.field != 1234) error ("staticSharedBiVoidCaller"); if (GenA<T>.staticSharedBiFloatCaller () != 1.0f) error ("staticSharedBiFloatCaller"); GenStruct<T> gss = GenA<T>.staticSharedBiValueCaller (987); if (gss.field != 987) error ("staticSharedBiValueCaller"); IntVoidDelegate ivdel = new IntVoidDelegate (GenA<T>.staticMethod); if (ivdel () != 54321) error ("staticMethod delegate"); Type gatype = typeof (GenA<T>); MethodInfo staticMethodInfo = gatype.GetMethod ("staticMethod"); if ((Convert.ToInt32 (staticMethodInfo.Invoke (null, null))) != 54321) error ("staticMethod reflection"); if (GenA<T>.staticMethodCaller () != 54321) error ("staticMethodCaller"); if (GenA<T>.staticFloatMethod () != 1.0) error ("staticFloatMethod"); if (ga.structCaller (234) != 357) error ("structCaller"); IGenImpl<T> igi = new IGenImpl<T> (); typeCheck ("callInterface", ga.callInterface (igi), typeof (T[])); if (ga.callLongInterface (igi, 345) != 346) error ("callLongInterface"); GenStruct<T> gst = ga.callValueInterface (igi, 543); if (gst.field != 543) error ("callValueInterface"); ga.callVoidInterface (igi, 654); if (igi.field != 654) error ("callVoidInterface"); if (ga.callFloatInterface (igi) != 1.0f) error ("callFloatInterface"); new GenADeriv<T> (); if (mustCatch) { checkException<GenExc<ClassA>> ("except", delegate { ga.except (); }); checkException<GenExc<ClassA>> ("staticExcept", delegate { GenA<T>.staticExcept (); }); } else { ga.except (); GenA<T>.staticExcept (); } MyDict<T, ClassB> dtb = new MyDict<T, ClassB> (obj, new ClassB ()); typeCheck ("MyPair", dtb.p, typeof (MyPair<T, ClassB>)); GenABDeriv<T> gabd = new GenABDeriv<T> (); typeCheck ("GenABDeriv.newArr", gabd.newArr (), typeof (GenB<T>[])); typeCheck ("GenABDeriv.newDerivArr", gabd.newDerivArr (), typeof (T[])); RGCTXTest<T> rt = new RGCTXTest<T> (); RGCTXTestSubA<T> rtsa = new RGCTXTestSubA<T> (); RGCTXTestSubB<T> rtsb = new RGCTXTestSubB<T> (); RGCTXTestSubASub rtsas = new RGCTXTestSubASub (); RGCTXTestSubASubSub<T> rtsass = new RGCTXTestSubASubSub<T> (); typeCheck ("rtsass.newCArr", rtsass.newCArr (), typeof (GenC<T>[])); typeCheck ("rgsa.newBArr", rtsa.newBArr (), typeof (GenB<T>[])); typeCheck ("rg.newAArr", rt.newAArr (), typeof (GenA<T>[])); typeCheck ("rgsb.newCArr", rtsb.newCArr (), typeof (GenC<T>[])); /* repeat all for each class */ typeCheck ("rtsass.newCArr", rtsass.newCArr (), typeof (GenC<T>[])); typeCheck ("rtsass.newBArr", rtsass.newBArr (), typeof (GenB<ClassA>[])); typeCheck ("rtsass.newAArr", rtsass.newAArr (), typeof (GenA<ClassA>[])); typeCheck ("rtsas.newBArr", rtsas.newBArr (), typeof (GenB<ClassA>[])); typeCheck ("rtsas.newAArr", rtsas.newAArr (), typeof (GenA<ClassA>[])); typeCheck ("rtsa.newBArr", rtsa.newBArr (), typeof (GenB<T>[])); typeCheck ("rtsa.newAArr", rtsa.newAArr (), typeof (GenA<T>[])); typeCheck ("rtsb.newCArr", rtsb.newCArr (), typeof (GenC<T>[])); typeCheck ("rtsb.newAArr", rtsb.newAArr (), typeof (GenA<T>[])); typeCheck ("rt.newAArr", rt.newAArr (), typeof (GenA<T>[])); } public static void virtualTest<T> (VirtualTest<T> vt, int len) { VirtualTestCaller<T> vtc = new VirtualTestCaller<T> (); T[] arr = vtc.doCall (vt); typeCheck ("virtualTest", arr, typeof (T[])); if (arr.Length != len) error ("virtualTest length"); } public static void listTest () { MyCons<string> ls = new MyCons<string> ("abc", null); MyCons<string> cdr = MyCons<string>.returnCdr (ls); if (cdr != null) error ("cdr is not null"); } public static int Main () { work<ClassA> (new ClassA (), false); work<ClassB> (new ClassB (), true); work<ClassB> (new ClassB (), true); work<ClassC> (new ClassC (), true); work<GenA<ClassA>> (new GenA<ClassA> (), true); work<int[]> (new int[3], true); work<int> (123, true); work<int?> (123, true); work<GenStruct<ClassA>?> (new GenStruct<ClassA> (123), true); work<GenStruct<ClassA>?> (null, true); StaticTest<ClassA> sa = new StaticTest<ClassA> (1234); StaticTest<ClassB> sb = new StaticTest<ClassB> (2345); if (sa.getStat () != 1234) error ("getStat"); if (sb.getStat () != 2345) error ("getStat"); if (sa.getOtherStat () != 0) error ("getOtherStat"); if (sa.getGenCStat () != 1234) error ("getGenCStat A"); if (sb.getGenCStat () != 1234) error ("getGenCStat B"); NonGenUser<NonGen> ngu = new NonGenUser<NonGen> (); if (ngu.getNonGenField () != 123) error ("getNonGenField"); AccessTest<ClassA> ata = new AccessTest<ClassA> (); if (ata.getOtherField () != 123) error ("getOtherField"); VirtualTest<ClassA> vta = new VirtualTest<ClassA> (); VirtualTest<ClassB> vtb = new VirtualTestDeriv<ClassB> (); virtualTest<ClassA> (vta, 3); virtualTest<ClassB> (vtb, 4); listTest (); if (haveError) return 1; return 0; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace StacksOfWax.AttributeRoutingApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Linq; using VaultAtlas.DataModel; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace VaultAtlas.UI.VaultExplorer { public class ArtistExplorer : UserControl, IComparer { private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.ListView listView1; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private CheckBox checkBox1; private CheckBox checkBox2; private System.ComponentModel.Container components = null; public ArtistExplorer() { InitializeComponent(); this.Load +=new EventHandler(ArtistExplorer_Load); } /// <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() { this.textBox1 = new System.Windows.Forms.TextBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.button1 = new System.Windows.Forms.Button(); this.listView1 = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.checkBox2 = new System.Windows.Forms.CheckBox(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(6, 16); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(238, 20); this.textBox1.TabIndex = 0; this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // groupBox1 // this.groupBox1.Controls.Add(this.textBox1); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top; this.groupBox1.Location = new System.Drawing.Point(3, 3); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(250, 45); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "Search for an artist"; // // button1 // this.button1.Location = new System.Drawing.Point(133, 301); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(120, 22); this.button1.TabIndex = 0; this.button1.Text = "&Add new artist ..."; this.button1.Click += new System.EventHandler(this.button1_Click); // // listView1 // this.listView1.AutoArrange = false; this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2}); this.listView1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.listView1.FullRowSelect = true; this.listView1.GridLines = true; this.listView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.listView1.Location = new System.Drawing.Point(3, 64); this.listView1.MultiSelect = false; this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size(250, 184); this.listView1.Sorting = System.Windows.Forms.SortOrder.Ascending; this.listView1.TabIndex = 5; this.listView1.UseCompatibleStateImageBehavior = false; this.listView1.View = System.Windows.Forms.View.Details; this.listView1.DoubleClick += new System.EventHandler(this.listView1_DoubleClick); this.listView1.SelectedIndexChanged += new System.EventHandler(this.UpdateArtistFilter); // // columnHeader1 // this.columnHeader1.Text = "Name"; this.columnHeader1.Width = 150; // // columnHeader2 // this.columnHeader2.Text = "# shows"; // // checkBox1 // this.checkBox1.Location = new System.Drawing.Point(9, 254); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(191, 25); this.checkBox1.TabIndex = 0; this.checkBox1.Text = "&Display entries by selected artists only"; this.checkBox1.CheckedChanged += new System.EventHandler(this.UpdateArtistFilter); // // checkBox2 // this.checkBox2.Location = new System.Drawing.Point(9, 276); this.checkBox2.Name = "checkBox2"; this.checkBox2.Size = new System.Drawing.Size(191, 19); this.checkBox2.TabIndex = 1; this.checkBox2.Text = "Sort by show count"; this.checkBox2.CheckedChanged += new System.EventHandler(this.checkBox2_CheckedChanged); // // ArtistExplorer // this.ClientSize = new System.Drawing.Size(256, 331); this.Controls.Add(this.checkBox1); this.Controls.Add(this.checkBox2); this.Controls.Add(this.button1); this.Controls.Add(this.listView1); this.Controls.Add(this.groupBox1); this.Name = "ArtistExplorer"; this.Padding = new System.Windows.Forms.Padding(3); this.Text = "Artists"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private void textBox1_TextChanged(object sender, System.EventArgs e) { string prefix = this.textBox1.Text.ToLower(); foreach(ListViewItem item in this.listView1.Items) if (item.Text.ToLower().StartsWith(prefix)) { item.Selected = true; return; } } private void button1_Click(object sender, System.EventArgs e) { VaultAtlasApplication.RequestEnterArtist( "" ); } public event EventHandler SelectedArtistChanged; public Artist SelectedArtist { get { return this.listView1.SelectedItems.Count > 0 ? this.listView1.SelectedItems[0].Tag as Artist : null; } } private void treeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { if (SelectedArtistChanged != null && e.Node != null) this.SelectedArtistChanged(this, new EventArgs()); this.UpdateArtistFilter(sender,e); } private void Artist_DisplayNameChanged(object sender, EventArgs e) { Artist artist = (Artist) sender; foreach(ListViewItem item in this.listView1.Items) if (item.Tag == artist) item.Text = artist.DisplayName; } private void UpdateArtistFilter(object sender, System.EventArgs e) { if (this.SelectedArtist != null) VaultAtlasApplication.Model.ShowView.Filter.SelectedArtist = this.checkBox1.Checked ? this.SelectedArtist : null; } private void listView1_DoubleClick(object sender, System.EventArgs e) { if (this.SelectedArtist != null) { DialogArtist dialog = new DialogArtist( this.SelectedArtist ); dialog.ShowDialog(); } } private void ArtistExplorer_Load(object sender, EventArgs e) { this.FillListView(); } private void FillListView() { this.listView1.BeginUpdate(); this.listView1.Items.Clear(); /* TODO QUANTUM foreach(Artist art in VaultAtlasApplication.Model.Artists) { this.listView1.Items.Add( new ListViewItem( new string[]{ art.DisplayName, "0" } )).Tag = art; art.DisplayNameChanged +=new EventHandler(Artist_DisplayNameChanged); } */ this.listView1.EndUpdate(); } private void Model_ShowAdded(object sender, ShowEventArgs e) { this.RecalculateShowCount( this.GetItemForArtist( e.Show.Artist )); } private IComparer comparerSave; private void checkBox2_CheckedChanged(object sender, System.EventArgs e) { this.listView1.BeginUpdate(); if ( this.checkBox2.Checked ) { this.comparerSave = this.listView1.ListViewItemSorter; this.listView1.ListViewItemSorter = this; } else { this.listView1.ListViewItemSorter = this.comparerSave; } this.listView1.EndUpdate(); } #region IComparer Member public int Compare(object x, object y) { return Int32.Parse( ((ListViewItem)y).SubItems[1].Text ).CompareTo( Int32.Parse( ((ListViewItem)x).SubItems[1].Text ) ); } #endregion private void Model_ShowChanging(object sender, ShowEventArgs e) { /* TODO QUANTUM string artist = e.Show.GetOriginalValue( "Artist" ).ToString(); string artistNew = e.Show.ArtistSortName; if ( !artist.Equals( artistNew )) { ListViewItem lvi = this.GetItemForArtist( VaultAtlasApplication.Model.Artists[ artist ] ); ListViewItem lviNew = this.GetItemForArtist( VaultAtlasApplication.Model.Artists[ artistNew ] ); this.RecalculateShowCount( lvi ); this.RecalculateShowCount( lviNew ); } */ } private void RecalculateShowCount( ListViewItem lvi ) { lvi.SubItems[1].Text = ((Artist)lvi.Tag).GetShowCount().ToString(); } private ListViewItem GetItemForArtist( Artist art ) { return listView1.Items.Cast<ListViewItem>().FirstOrDefault(lvi => lvi.Tag == art); } } }
// // Copyright 2012 Hakan Kjellerstrand // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Linq; using Google.OrTools.ConstraintSolver; public class HidatoTable { /* * Build closeness pairs for consecutive numbers. * * Build set of allowed pairs such that two consecutive numbers touch * each other in the grid. * * Returns: * A list of pairs for allowed consecutive position of numbers. * * Args: * rows: the number of rows in the grid * cols: the number of columns in the grid */ public static IntTupleSet BuildPairs(int rows, int cols) { int[] ix = { -1, 0, 1 }; var result_tmp = (from x in Enumerable.Range(0, rows) from y in Enumerable.Range(0, cols) from dx in ix from dy in ix where x + dx >= 0 && x + dx < rows && y + dy >= 0 && y + dy < cols && (dx != 0 || dy != 0) select new int[]{x * cols + y, (x + dx) * cols + (y + dy)}) .ToArray(); // Convert to len x 2 matrix int len = result_tmp.Length; IntTupleSet result = new IntTupleSet(2); foreach (int[] r in result_tmp) { result.Insert(r); } return result; } /** * * Hidato puzzle in Google CP Solver. * * http://www.hidato.com/ * """ * Puzzles start semi-filled with numbered tiles. * The first and last numbers are circled. * Connect the numbers together to win. Consecutive * number must touch horizontally, vertically, or * diagonally. * """ * * This is a port of the Python model hidato_table.py * made by Laurent Perron (using AllowedAssignments), * based on my (much slower) model hidato.py. * */ private static void Solve(int model = 1) { Solver solver = new Solver("HidatoTable"); // // models, a 0 indicates an open cell which number is not yet known. // int[,] puzzle = null; if (model == 1) { // Simple problem // Solution 1: // 6 7 9 // 5 2 8 // 1 4 3 int[,] puzzle1 = { { 6, 0, 9 }, { 0, 2, 8 }, { 1, 0, 0 } }; puzzle = puzzle1; } else if (model == 2) { int[,] puzzle2 = { { 0, 44, 41, 0, 0, 0, 0 }, { 0, 43, 0, 28, 29, 0, 0 }, { 0, 1, 0, 0, 0, 33, 0 }, { 0, 2, 25, 4, 34, 0, 36 }, { 49, 16, 0, 23, 0, 0, 0 }, { 0, 19, 0, 0, 12, 7, 0 }, { 0, 0, 0, 14, 0, 0, 0 } }; puzzle = puzzle2; } else if (model == 3) { // Problems from the book: // Gyora Bededek: "Hidato: 2000 Pure Logic Puzzles" // Problem 1 (Practice) int[,] puzzle3 = { { 0, 0, 20, 0, 0 }, { 0, 0, 0, 16, 18 }, { 22, 0, 15, 0, 0 }, { 23, 0, 1, 14, 11 }, { 0, 25, 0, 0, 12 } }; puzzle = puzzle3; } else if (model == 4) { // problem 2 (Practice) int[,] puzzle4 = { { 0, 0, 0, 0, 14 }, { 0, 18, 12, 0, 0 }, { 0, 0, 17, 4, 5 }, { 0, 0, 7, 0, 0 }, { 9, 8, 25, 1, 0 } }; puzzle = puzzle4; } else if (model == 5) { // problem 3 (Beginner) int[,] puzzle5 = { { 0, 26, 0, 0, 0, 18 }, { 0, 0, 27, 0, 0, 19 }, { 31, 23, 0, 0, 14, 0 }, { 0, 33, 8, 0, 15, 1 }, { 0, 0, 0, 5, 0, 0 }, { 35, 36, 0, 10, 0, 0 } }; puzzle = puzzle5; } else if (model == 6) { // Problem 15 (Intermediate) int[,] puzzle6 = { { 64, 0, 0, 0, 0, 0, 0, 0 }, { 1, 63, 0, 59, 15, 57, 53, 0 }, { 0, 4, 0, 14, 0, 0, 0, 0 }, { 3, 0, 11, 0, 20, 19, 0, 50 }, { 0, 0, 0, 0, 22, 0, 48, 40 }, { 9, 0, 0, 32, 23, 0, 0, 41 }, { 27, 0, 0, 0, 36, 0, 46, 0 }, { 28, 30, 0, 35, 0, 0, 0, 0 } }; puzzle = puzzle6; } int r = puzzle.GetLength(0); int c = puzzle.GetLength(1); Console.WriteLine(); Console.WriteLine("----- Solving problem {0} -----", model); Console.WriteLine(); PrintMatrix(puzzle); // // Decision variables // IntVar[] positions = solver.MakeIntVarArray(r * c, 0, r * c - 1, "p"); // // Constraints // solver.Add(positions.AllDifferent()); // // Fill in the clues // for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (puzzle[i, j] > 0) { solver.Add(positions[puzzle[i, j] - 1] == i * c + j); } } } // Consecutive numbers much touch each other in the grid. // We use an allowed assignment constraint to model it. IntTupleSet close_tuples = BuildPairs(r, c); for (int k = 1; k < r * c - 1; k++) { IntVar[] tmp = new IntVar[] { positions[k], positions[k + 1] }; solver.Add(tmp.AllowedAssignments(close_tuples)); } // // Search // DecisionBuilder db = solver.MakePhase(positions, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); int num_solution = 0; while (solver.NextSolution()) { num_solution++; PrintOneSolution(positions, r, c, num_solution); } Console.WriteLine("\nSolutions: " + solver.Solutions()); Console.WriteLine("WallTime: " + solver.WallTime() + "ms "); Console.WriteLine("Failures: " + solver.Failures()); Console.WriteLine("Branches: " + solver.Branches()); solver.EndSearch(); } // Print the current solution public static void PrintOneSolution(IntVar[] positions, int rows, int cols, int num_solution) { Console.WriteLine("Solution {0}", num_solution); // Create empty board int[,] board = new int[rows, cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { board[i, j] = 0; } } // Fill board with solution value for (int k = 0; k < rows * cols; k++) { int position = (int)positions[k].Value(); board[position / cols, position % cols] = k + 1; } PrintMatrix(board); } // Pretty print of the matrix public static void PrintMatrix(int[,] game) { int rows = game.GetLength(0); int cols = game.GetLength(1); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (game[i, j] == 0) { Console.Write(" ."); } else { Console.Write(" {0,2}", game[i, j]); } } Console.WriteLine(); } Console.WriteLine(); } public static void Main(String[] args) { int model = 1; if (args.Length > 0) { model = Convert.ToInt32(args[0]); Solve(model); } else { for (int m = 1; m <= 6; m++) { Solve(m); } } } }
using System; using System.IO; namespace ICSharpCode.SharpZipLib.Tar { /// <summary> /// The TarOutputStream writes a UNIX tar archive as an OutputStream. /// Methods are provided to put entries, and then write their contents /// by writing to this stream using write(). /// </summary> /// public public class TarOutputStream : Stream { #region Constructors /// <summary> /// Construct TarOutputStream using default block factor /// </summary> /// <param name="outputStream">stream to write to</param> public TarOutputStream(Stream outputStream) : this(outputStream, TarBuffer.DefaultBlockFactor) { } /// <summary> /// Construct TarOutputStream with user specified block factor /// </summary> /// <param name="outputStream">stream to write to</param> /// <param name="blockFactor">blocking factor</param> public TarOutputStream(Stream outputStream, int blockFactor) { if (outputStream == null) { throw new ArgumentNullException(nameof(outputStream)); } this.outputStream = outputStream; buffer = TarBuffer.CreateOutputTarBuffer(outputStream, blockFactor); assemblyBuffer = new byte[TarBuffer.BlockSize]; blockBuffer = new byte[TarBuffer.BlockSize]; } #endregion /// <summary> /// Gets or sets a flag indicating ownership of underlying stream. /// When the flag is true <see cref="Stream.Dispose()" /> will close the underlying stream also. /// </summary> /// <remarks>The default value is true.</remarks> public bool IsStreamOwner { get { return buffer.IsStreamOwner; } set { buffer.IsStreamOwner = value; } } /// <summary> /// true if the stream supports reading; otherwise, false. /// </summary> public override bool CanRead { get { return outputStream.CanRead; } } /// <summary> /// true if the stream supports seeking; otherwise, false. /// </summary> public override bool CanSeek { get { return outputStream.CanSeek; } } /// <summary> /// true if stream supports writing; otherwise, false. /// </summary> public override bool CanWrite { get { return outputStream.CanWrite; } } /// <summary> /// length of stream in bytes /// </summary> public override long Length { get { return outputStream.Length; } } /// <summary> /// gets or sets the position within the current stream. /// </summary> public override long Position { get { return outputStream.Position; } set { outputStream.Position = value; } } /// <summary> /// set the position within the current stream /// </summary> /// <param name="offset">The offset relative to the <paramref name="origin"/> to seek to</param> /// <param name="origin">The <see cref="SeekOrigin"/> to seek from.</param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { return outputStream.Seek(offset, origin); } /// <summary> /// Set the length of the current stream /// </summary> /// <param name="value">The new stream length.</param> public override void SetLength(long value) { outputStream.SetLength(value); } /// <summary> /// Read a byte from the stream and advance the position within the stream /// by one byte or returns -1 if at the end of the stream. /// </summary> /// <returns>The byte value or -1 if at end of stream</returns> public override int ReadByte() { return outputStream.ReadByte(); } /// <summary> /// read bytes from the current stream and advance the position within the /// stream by the number of bytes read. /// </summary> /// <param name="buffer">The buffer to store read bytes in.</param> /// <param name="offset">The index into the buffer to being storing bytes at.</param> /// <param name="count">The desired number of bytes to read.</param> /// <returns>The total number of bytes read, or zero if at the end of the stream. /// The number of bytes may be less than the <paramref name="count">count</paramref> /// requested if data is not avialable.</returns> public override int Read(byte[] buffer, int offset, int count) { return outputStream.Read(buffer, offset, count); } /// <summary> /// All buffered data is written to destination /// </summary> public override void Flush() { outputStream.Flush(); } /// <summary> /// Ends the TAR archive without closing the underlying OutputStream. /// The result is that the EOF block of nulls is written. /// </summary> public void Finish() { if (IsEntryOpen) { CloseEntry(); } WriteEofBlock(); } /// <summary> /// Ends the TAR archive and closes the underlying OutputStream. /// </summary> /// <remarks>This means that Finish() is called followed by calling the /// TarBuffer's Close().</remarks> protected override void Dispose(bool disposing) { if (!isClosed) { isClosed = true; Finish(); buffer.Close(); } } /// <summary> /// Get the record size being used by this stream's TarBuffer. /// </summary> public int RecordSize { get { return buffer.RecordSize; } } /// <summary> /// Get the record size being used by this stream's TarBuffer. /// </summary> /// <returns> /// The TarBuffer record size. /// </returns> [Obsolete("Use RecordSize property instead")] public int GetRecordSize() { return buffer.RecordSize; } /// <summary> /// Get a value indicating wether an entry is open, requiring more data to be written. /// </summary> bool IsEntryOpen { get { return (currBytes < currSize); } } /// <summary> /// Put an entry on the output stream. This writes the entry's /// header and positions the output stream for writing /// the contents of the entry. Once this method is called, the /// stream is ready for calls to write() to write the entry's /// contents. Once the contents are written, closeEntry() /// <B>MUST</B> be called to ensure that all buffered data /// is completely written to the output stream. /// </summary> /// <param name="entry"> /// The TarEntry to be written to the archive. /// </param> public void PutNextEntry(TarEntry entry) { if (entry == null) { throw new ArgumentNullException(nameof(entry)); } if (entry.TarHeader.Name.Length > TarHeader.NAMELEN) { var longHeader = new TarHeader(); longHeader.TypeFlag = TarHeader.LF_GNU_LONGNAME; longHeader.Name = longHeader.Name + "././@LongLink"; longHeader.Mode = 420;//644 by default longHeader.UserId = entry.UserId; longHeader.GroupId = entry.GroupId; longHeader.GroupName = entry.GroupName; longHeader.UserName = entry.UserName; longHeader.LinkName = ""; longHeader.Size = entry.TarHeader.Name.Length + 1; // Plus one to avoid dropping last char longHeader.WriteHeader(blockBuffer); buffer.WriteBlock(blockBuffer); // Add special long filename header block int nameCharIndex = 0; while (nameCharIndex < entry.TarHeader.Name.Length + 1 /* we've allocated one for the null char, now we must make sure it gets written out */) { Array.Clear(blockBuffer, 0, blockBuffer.Length); TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, TarBuffer.BlockSize); // This func handles OK the extra char out of string length nameCharIndex += TarBuffer.BlockSize; buffer.WriteBlock(blockBuffer); } } entry.WriteEntryHeader(blockBuffer); buffer.WriteBlock(blockBuffer); currBytes = 0; currSize = entry.IsDirectory ? 0 : entry.Size; } /// <summary> /// Close an entry. This method MUST be called for all file /// entries that contain data. The reason is that we must /// buffer data written to the stream in order to satisfy /// the buffer's block based writes. Thus, there may be /// data fragments still being assembled that must be written /// to the output stream before this entry is closed and the /// next entry written. /// </summary> public void CloseEntry() { if (assemblyBufferLength > 0) { Array.Clear(assemblyBuffer, assemblyBufferLength, assemblyBuffer.Length - assemblyBufferLength); buffer.WriteBlock(assemblyBuffer); currBytes += assemblyBufferLength; assemblyBufferLength = 0; } if (currBytes < currSize) { string errorText = string.Format( "Entry closed at '{0}' before the '{1}' bytes specified in the header were written", currBytes, currSize); throw new TarException(errorText); } } /// <summary> /// Writes a byte to the current tar archive entry. /// This method simply calls Write(byte[], int, int). /// </summary> /// <param name="value"> /// The byte to be written. /// </param> public override void WriteByte(byte value) { Write(new byte[] { value }, 0, 1); } /// <summary> /// Writes bytes to the current tar archive entry. This method /// is aware of the current entry and will throw an exception if /// you attempt to write bytes past the length specified for the /// current entry. The method is also (painfully) aware of the /// record buffering required by TarBuffer, and manages buffers /// that are not a multiple of recordsize in length, including /// assembling records from small buffers. /// </summary> /// <param name = "buffer"> /// The buffer to write to the archive. /// </param> /// <param name = "offset"> /// The offset in the buffer from which to get bytes. /// </param> /// <param name = "count"> /// The number of bytes to write. /// </param> public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), "Cannot be negative"); } if (buffer.Length - offset < count) { throw new ArgumentException("offset and count combination is invalid"); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), "Cannot be negative"); } if ((currBytes + count) > currSize) { string errorText = string.Format("request to write '{0}' bytes exceeds size in header of '{1}' bytes", count, this.currSize); throw new ArgumentOutOfRangeException(nameof(count), errorText); } // // We have to deal with assembly!!! // The programmer can be writing little 32 byte chunks for all // we know, and we must assemble complete blocks for writing. // TODO REVIEW Maybe this should be in TarBuffer? Could that help to // eliminate some of the buffer copying. // if (assemblyBufferLength > 0) { if ((assemblyBufferLength + count) >= blockBuffer.Length) { int aLen = blockBuffer.Length - assemblyBufferLength; Array.Copy(assemblyBuffer, 0, blockBuffer, 0, assemblyBufferLength); Array.Copy(buffer, offset, blockBuffer, assemblyBufferLength, aLen); this.buffer.WriteBlock(blockBuffer); currBytes += blockBuffer.Length; offset += aLen; count -= aLen; assemblyBufferLength = 0; } else { Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count); offset += count; assemblyBufferLength += count; count -= count; } } // // When we get here we have EITHER: // o An empty "assembly" buffer. // o No bytes to write (count == 0) // while (count > 0) { if (count < blockBuffer.Length) { Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count); assemblyBufferLength += count; break; } this.buffer.WriteBlock(buffer, offset); int bufferLength = blockBuffer.Length; currBytes += bufferLength; count -= bufferLength; offset += bufferLength; } } /// <summary> /// Write an EOF (end of archive) block to the tar archive. /// The end of the archive is indicated by two blocks consisting entirely of zero bytes. /// </summary> void WriteEofBlock() { Array.Clear(blockBuffer, 0, blockBuffer.Length); buffer.WriteBlock(blockBuffer); buffer.WriteBlock(blockBuffer); } #region Instance Fields /// <summary> /// bytes written for this entry so far /// </summary> long currBytes; /// <summary> /// current 'Assembly' buffer length /// </summary> int assemblyBufferLength; /// <summary> /// Flag indicating wether this instance has been closed or not. /// </summary> bool isClosed; /// <summary> /// Size for the current entry /// </summary> protected long currSize; /// <summary> /// single block working buffer /// </summary> protected byte[] blockBuffer; /// <summary> /// 'Assembly' buffer used to assemble data before writing /// </summary> protected byte[] assemblyBuffer; /// <summary> /// TarBuffer used to provide correct blocking factor /// </summary> protected TarBuffer buffer; /// <summary> /// the destination stream for the archive contents /// </summary> protected Stream outputStream; #endregion } }
using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using FieldsConsumer = Lucene.Net.Codecs.FieldsConsumer; using FixedBitSet = Lucene.Net.Util.FixedBitSet; using OffsetAttribute = Lucene.Net.Analysis.TokenAttributes.OffsetAttribute; using PayloadAttribute = Lucene.Net.Analysis.TokenAttributes.PayloadAttribute; using PostingsConsumer = Lucene.Net.Codecs.PostingsConsumer; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using TermsConsumer = Lucene.Net.Codecs.TermsConsumer; using TermStats = Lucene.Net.Codecs.TermStats; // TODO: break into separate freq and prox writers as // codecs; make separate container (tii/tis/skip/*) that can // be configured as any number of files 1..N internal sealed class FreqProxTermsWriterPerField : TermsHashConsumerPerField, IComparable<FreqProxTermsWriterPerField> { internal readonly FreqProxTermsWriter parent; internal readonly TermsHashPerField termsHashPerField; internal readonly FieldInfo fieldInfo; internal readonly DocumentsWriterPerThread.DocState docState; internal readonly FieldInvertState fieldState; private bool hasFreq; private bool hasProx; private bool hasOffsets; internal IPayloadAttribute payloadAttribute; internal IOffsetAttribute offsetAttribute; public FreqProxTermsWriterPerField(TermsHashPerField termsHashPerField, FreqProxTermsWriter parent, FieldInfo fieldInfo) { this.termsHashPerField = termsHashPerField; this.parent = parent; this.fieldInfo = fieldInfo; docState = termsHashPerField.docState; fieldState = termsHashPerField.fieldState; SetIndexOptions(fieldInfo.IndexOptions); } internal override int StreamCount { get { if (!hasProx) { return 1; } else { return 2; } } } internal override void Finish() { if (hasPayloads) { fieldInfo.SetStorePayloads(); } } internal bool hasPayloads; [ExceptionToNetNumericConvention] internal override void SkippingLongTerm() { } public int CompareTo(FreqProxTermsWriterPerField other) { return fieldInfo.Name.CompareToOrdinal(other.fieldInfo.Name); } // Called after flush internal void Reset() { // Record, up front, whether our in-RAM format will be // with or without term freqs: SetIndexOptions(fieldInfo.IndexOptions); payloadAttribute = null; } private void SetIndexOptions(IndexOptions indexOptions) { if (indexOptions == IndexOptions.NONE) { // field could later be updated with indexed=true, so set everything on hasFreq = hasProx = hasOffsets = true; } else { hasFreq = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0; hasProx = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; hasOffsets = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; } } internal override bool Start(IIndexableField[] fields, int count) { for (int i = 0; i < count; i++) { if (fields[i].IndexableFieldType.IsIndexed) { return true; } } return false; } internal override void Start(IIndexableField f) { if (fieldState.AttributeSource.HasAttribute<IPayloadAttribute>()) { payloadAttribute = fieldState.AttributeSource.GetAttribute<IPayloadAttribute>(); } else { payloadAttribute = null; } if (hasOffsets) { offsetAttribute = fieldState.AttributeSource.AddAttribute<IOffsetAttribute>(); } else { offsetAttribute = null; } } internal void WriteProx(int termID, int proxCode) { //System.out.println("writeProx termID=" + termID + " proxCode=" + proxCode); Debug.Assert(hasProx); BytesRef payload; if (payloadAttribute == null) { payload = null; } else { payload = payloadAttribute.Payload; } if (payload != null && payload.Length > 0) { termsHashPerField.WriteVInt32(1, (proxCode << 1) | 1); termsHashPerField.WriteVInt32(1, payload.Length); termsHashPerField.WriteBytes(1, payload.Bytes, payload.Offset, payload.Length); hasPayloads = true; } else { termsHashPerField.WriteVInt32(1, proxCode << 1); } FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; postings.lastPositions[termID] = fieldState.Position; } internal void WriteOffsets(int termID, int offsetAccum) { Debug.Assert(hasOffsets); int startOffset = offsetAccum + offsetAttribute.StartOffset; int endOffset = offsetAccum + offsetAttribute.EndOffset; FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; Debug.Assert(startOffset - postings.lastOffsets[termID] >= 0); termsHashPerField.WriteVInt32(1, startOffset - postings.lastOffsets[termID]); termsHashPerField.WriteVInt32(1, endOffset - startOffset); postings.lastOffsets[termID] = startOffset; } internal override void NewTerm(int termID) { // First time we're seeing this term since the last // flush Debug.Assert(docState.TestPoint("FreqProxTermsWriterPerField.newTerm start")); FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; postings.lastDocIDs[termID] = docState.docID; if (!hasFreq) { postings.lastDocCodes[termID] = docState.docID; } else { postings.lastDocCodes[termID] = docState.docID << 1; postings.termFreqs[termID] = 1; if (hasProx) { WriteProx(termID, fieldState.Position); if (hasOffsets) { WriteOffsets(termID, fieldState.Offset); } } else { Debug.Assert(!hasOffsets); } } fieldState.MaxTermFrequency = Math.Max(1, fieldState.MaxTermFrequency); fieldState.UniqueTermCount++; } internal override void AddTerm(int termID) { Debug.Assert(docState.TestPoint("FreqProxTermsWriterPerField.addTerm start")); FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; Debug.Assert(!hasFreq || postings.termFreqs[termID] > 0); if (!hasFreq) { Debug.Assert(postings.termFreqs == null); if (docState.docID != postings.lastDocIDs[termID]) { Debug.Assert(docState.docID > postings.lastDocIDs[termID]); termsHashPerField.WriteVInt32(0, postings.lastDocCodes[termID]); postings.lastDocCodes[termID] = docState.docID - postings.lastDocIDs[termID]; postings.lastDocIDs[termID] = docState.docID; fieldState.UniqueTermCount++; } } else if (docState.docID != postings.lastDocIDs[termID]) { Debug.Assert(docState.docID > postings.lastDocIDs[termID], "id: " + docState.docID + " postings ID: " + postings.lastDocIDs[termID] + " termID: " + termID); // Term not yet seen in the current doc but previously // seen in other doc(s) since the last flush // Now that we know doc freq for previous doc, // write it & lastDocCode if (1 == postings.termFreqs[termID]) { termsHashPerField.WriteVInt32(0, postings.lastDocCodes[termID] | 1); } else { termsHashPerField.WriteVInt32(0, postings.lastDocCodes[termID]); termsHashPerField.WriteVInt32(0, postings.termFreqs[termID]); } postings.termFreqs[termID] = 1; fieldState.MaxTermFrequency = Math.Max(1, fieldState.MaxTermFrequency); postings.lastDocCodes[termID] = (docState.docID - postings.lastDocIDs[termID]) << 1; postings.lastDocIDs[termID] = docState.docID; if (hasProx) { WriteProx(termID, fieldState.Position); if (hasOffsets) { postings.lastOffsets[termID] = 0; WriteOffsets(termID, fieldState.Offset); } } else { Debug.Assert(!hasOffsets); } fieldState.UniqueTermCount++; } else { fieldState.MaxTermFrequency = Math.Max(fieldState.MaxTermFrequency, ++postings.termFreqs[termID]); if (hasProx) { WriteProx(termID, fieldState.Position - postings.lastPositions[termID]); } if (hasOffsets) { WriteOffsets(termID, fieldState.Offset); } } } internal override ParallelPostingsArray CreatePostingsArray(int size) { return new FreqProxPostingsArray(size, hasFreq, hasProx, hasOffsets); } internal sealed class FreqProxPostingsArray : ParallelPostingsArray { public FreqProxPostingsArray(int size, bool writeFreqs, bool writeProx, bool writeOffsets) : base(size) { if (writeFreqs) { termFreqs = new int[size]; } lastDocIDs = new int[size]; lastDocCodes = new int[size]; if (writeProx) { lastPositions = new int[size]; if (writeOffsets) { lastOffsets = new int[size]; } } else { Debug.Assert(!writeOffsets); } //System.out.println("PA init freqs=" + writeFreqs + " pos=" + writeProx + " offs=" + writeOffsets); } internal int[] termFreqs; // # times this term occurs in the current doc internal int[] lastDocIDs; // Last docID where this term occurred internal int[] lastDocCodes; // Code for prior doc internal int[] lastPositions; // Last position where this term occurred internal int[] lastOffsets; // Last endOffset where this term occurred internal override ParallelPostingsArray NewInstance(int size) { return new FreqProxPostingsArray(size, termFreqs != null, lastPositions != null, lastOffsets != null); } internal override void CopyTo(ParallelPostingsArray toArray, int numToCopy) { Debug.Assert(toArray is FreqProxPostingsArray); FreqProxPostingsArray to = (FreqProxPostingsArray)toArray; base.CopyTo(toArray, numToCopy); Array.Copy(lastDocIDs, 0, to.lastDocIDs, 0, numToCopy); Array.Copy(lastDocCodes, 0, to.lastDocCodes, 0, numToCopy); if (lastPositions != null) { Debug.Assert(to.lastPositions != null); Array.Copy(lastPositions, 0, to.lastPositions, 0, numToCopy); } if (lastOffsets != null) { Debug.Assert(to.lastOffsets != null); Array.Copy(lastOffsets, 0, to.lastOffsets, 0, numToCopy); } if (termFreqs != null) { Debug.Assert(to.termFreqs != null); Array.Copy(termFreqs, 0, to.termFreqs, 0, numToCopy); } } internal override int BytesPerPosting() { int bytes = ParallelPostingsArray.BYTES_PER_POSTING + 2 * RamUsageEstimator.NUM_BYTES_INT32; if (lastPositions != null) { bytes += RamUsageEstimator.NUM_BYTES_INT32; } if (lastOffsets != null) { bytes += RamUsageEstimator.NUM_BYTES_INT32; } if (termFreqs != null) { bytes += RamUsageEstimator.NUM_BYTES_INT32; } return bytes; } } [MethodImpl(MethodImplOptions.NoInlining)] public void Abort() { } internal BytesRef payload; /// <summary> /// Walk through all unique text tokens (Posting /// instances) found in this field and serialize them /// into a single RAM segment. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal void Flush(string fieldName, FieldsConsumer consumer, SegmentWriteState state) { if (!fieldInfo.IsIndexed) { return; // nothing to flush, don't bother the codec with the unindexed field } TermsConsumer termsConsumer = consumer.AddField(fieldInfo); IComparer<BytesRef> termComp = termsConsumer.Comparer; // CONFUSING: this.indexOptions holds the index options // that were current when we first saw this field. But // it's possible this has changed, eg when other // documents are indexed that cause a "downgrade" of the // IndexOptions. So we must decode the in-RAM buffer // according to this.indexOptions, but then write the // new segment to the directory according to // currentFieldIndexOptions: IndexOptions currentFieldIndexOptions = fieldInfo.IndexOptions; Debug.Assert(currentFieldIndexOptions != IndexOptions.NONE); bool writeTermFreq = currentFieldIndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0; bool writePositions = currentFieldIndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; bool writeOffsets = currentFieldIndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; bool readTermFreq = this.hasFreq; bool readPositions = this.hasProx; bool readOffsets = this.hasOffsets; //System.out.println("flush readTF=" + readTermFreq + " readPos=" + readPositions + " readOffs=" + readOffsets); // Make sure FieldInfo.update is working correctly!: Debug.Assert(!writeTermFreq || readTermFreq); Debug.Assert(!writePositions || readPositions); Debug.Assert(!writeOffsets || readOffsets); Debug.Assert(!writeOffsets || writePositions); IDictionary<Term, int?> segDeletes; if (state.SegUpdates != null && state.SegUpdates.terms.Count > 0) { segDeletes = state.SegUpdates.terms; } else { segDeletes = null; } int[] termIDs = termsHashPerField.SortPostings(termComp); int numTerms = termsHashPerField.bytesHash.Count; BytesRef text = new BytesRef(); FreqProxPostingsArray postings = (FreqProxPostingsArray)termsHashPerField.postingsArray; ByteSliceReader freq = new ByteSliceReader(); ByteSliceReader prox = new ByteSliceReader(); FixedBitSet visitedDocs = new FixedBitSet(state.SegmentInfo.DocCount); long sumTotalTermFreq = 0; long sumDocFreq = 0; Term protoTerm = new Term(fieldName); for (int i = 0; i < numTerms; i++) { int termID = termIDs[i]; // Get BytesRef int textStart = postings.textStarts[termID]; termsHashPerField.bytePool.SetBytesRef(text, textStart); termsHashPerField.InitReader(freq, termID, 0); if (readPositions || readOffsets) { termsHashPerField.InitReader(prox, termID, 1); } // TODO: really TermsHashPerField should take over most // of this loop, including merge sort of terms from // multiple threads and interacting with the // TermsConsumer, only calling out to us (passing us the // DocsConsumer) to handle delivery of docs/positions PostingsConsumer postingsConsumer = termsConsumer.StartTerm(text); int? delDocLimit; if (segDeletes != null) { protoTerm.Bytes = text; int? docIDUpto; segDeletes.TryGetValue(protoTerm, out docIDUpto); if (docIDUpto != null) { delDocLimit = docIDUpto; } else { delDocLimit = 0; } } else { delDocLimit = 0; } // Now termStates has numToMerge FieldMergeStates // which all share the same term. Now we must // interleave the docID streams. int docFreq = 0; long totalTermFreq = 0; int docID = 0; while (true) { //System.out.println(" cycle"); int termFreq; if (freq.Eof()) { if (postings.lastDocCodes[termID] != -1) { // Return last doc docID = postings.lastDocIDs[termID]; if (readTermFreq) { termFreq = postings.termFreqs[termID]; } else { termFreq = -1; } postings.lastDocCodes[termID] = -1; } else { // EOF break; } } else { int code = freq.ReadVInt32(); if (!readTermFreq) { docID += code; termFreq = -1; } else { docID += (int)((uint)code >> 1); if ((code & 1) != 0) { termFreq = 1; } else { termFreq = freq.ReadVInt32(); } } Debug.Assert(docID != postings.lastDocIDs[termID]); } docFreq++; Debug.Assert(docID < state.SegmentInfo.DocCount, "doc=" + docID + " maxDoc=" + state.SegmentInfo.DocCount); // NOTE: we could check here if the docID was // deleted, and skip it. However, this is somewhat // dangerous because it can yield non-deterministic // behavior since we may see the docID before we see // the term that caused it to be deleted. this // would mean some (but not all) of its postings may // make it into the index, which'd alter the docFreq // for those terms. We could fix this by doing two // passes, ie first sweep marks all del docs, and // 2nd sweep does the real flush, but I suspect // that'd add too much time to flush. visitedDocs.Set(docID); postingsConsumer.StartDoc(docID, writeTermFreq ? termFreq : -1); if (docID < delDocLimit) { // Mark it deleted. TODO: we could also skip // writing its postings; this would be // deterministic (just for this Term's docs). // TODO: can we do this reach-around in a cleaner way???? if (state.LiveDocs == null) { state.LiveDocs = docState.docWriter.codec.LiveDocsFormat.NewLiveDocs(state.SegmentInfo.DocCount); } if (state.LiveDocs.Get(docID)) { state.DelCountOnFlush++; state.LiveDocs.Clear(docID); } } totalTermFreq += termFreq; // Carefully copy over the prox + payload info, // changing the format to match Lucene's segment // format. if (readPositions || readOffsets) { // we did record positions (& maybe payload) and/or offsets int position = 0; int offset = 0; for (int j = 0; j < termFreq; j++) { BytesRef thisPayload; if (readPositions) { int code = prox.ReadVInt32(); position += (int)((uint)code >> 1); if ((code & 1) != 0) { // this position has a payload int payloadLength = prox.ReadVInt32(); if (payload == null) { payload = new BytesRef(); payload.Bytes = new byte[payloadLength]; } else if (payload.Bytes.Length < payloadLength) { payload.Grow(payloadLength); } prox.ReadBytes(payload.Bytes, 0, payloadLength); payload.Length = payloadLength; thisPayload = payload; } else { thisPayload = null; } if (readOffsets) { int startOffset = offset + prox.ReadVInt32(); int endOffset = startOffset + prox.ReadVInt32(); if (writePositions) { if (writeOffsets) { Debug.Assert(startOffset >= 0 && endOffset >= startOffset, "startOffset=" + startOffset + ",endOffset=" + endOffset + ",offset=" + offset); postingsConsumer.AddPosition(position, thisPayload, startOffset, endOffset); } else { postingsConsumer.AddPosition(position, thisPayload, -1, -1); } } offset = startOffset; } else if (writePositions) { postingsConsumer.AddPosition(position, thisPayload, -1, -1); } } } } postingsConsumer.FinishDoc(); } termsConsumer.FinishTerm(text, new TermStats(docFreq, writeTermFreq ? totalTermFreq : -1)); sumTotalTermFreq += totalTermFreq; sumDocFreq += docFreq; } termsConsumer.Finish(writeTermFreq ? sumTotalTermFreq : -1, sumDocFreq, visitedDocs.Cardinality()); } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System.Collections.Generic; using System.Xml; /// <summary> /// Represents the DelveDocument. /// </summary> public sealed class DelveDocument : InsightValue { private double rank; private string author; private string created; private string lastModifiedTime; private string defaultEncodingURL; private string fileType; private string title; private string lastEditor; private string documentId; private string previewURL; /// <summary> /// Gets the Rank /// </summary> public double Rank { get { return this.rank; } set { this.SetFieldValue<double>(ref this.rank, value); } } /// <summary> /// Gets the Author /// </summary> public string Author { get { return this.author; } set { this.SetFieldValue<string>(ref this.author, value); } } /// <summary> /// Gets the Created /// </summary> public string Created { get { return this.created; } set { this.SetFieldValue<string>(ref this.created, value); } } /// <summary> /// Gets the LastModifiedTime /// </summary> public string LastModifiedTime { get { return this.lastModifiedTime; } set { this.SetFieldValue<string>(ref this.lastModifiedTime, value); } } /// <summary> /// Gets the DefaultEncodingURL /// </summary> public string DefaultEncodingURL { get { return this.defaultEncodingURL; } set { this.SetFieldValue<string>(ref this.defaultEncodingURL, value); } } /// <summary> /// Gets the FileType /// </summary> public string FileType { get { return this.fileType; } set { this.SetFieldValue<string>(ref this.fileType, value); } } /// <summary> /// Gets the Title /// </summary> public string Title { get { return this.title; } set { this.SetFieldValue<string>(ref this.title, value); } } /// <summary> /// Gets the DocumentId /// </summary> public string DocumentId { get { return this.documentId; } set { this.SetFieldValue<string>(ref this.documentId, value); } } /// <summary> /// Gets the PreviewURL /// </summary> public string PreviewURL { get { return this.previewURL; } set { this.SetFieldValue<string>(ref this.previewURL, value); } } /// <summary> /// Gets the LastEditor /// </summary> public string LastEditor { get { return this.lastEditor; } set { this.SetFieldValue<string>(ref this.lastEditor, value); } } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">XML reader</param> /// <returns>Whether the element was read</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.InsightSource: this.InsightSource = reader.ReadElementValue<string>(); break; case XmlElementNames.UpdatedUtcTicks: this.UpdatedUtcTicks = reader.ReadElementValue<long>(); break; case XmlElementNames.Rank: this.Rank = reader.ReadElementValue<double>(); break; case XmlElementNames.Author: this.Author = reader.ReadElementValue(); break; case XmlElementNames.Created: this.Created = reader.ReadElementValue(); break; case XmlElementNames.LastModifiedTime: this.LastModifiedTime = reader.ReadElementValue(); break; case XmlElementNames.DefaultEncodingURL: this.DefaultEncodingURL = reader.ReadElementValue(); break; case XmlElementNames.FileType: this.FileType = reader.ReadElementValue(); break; case XmlElementNames.Title: this.Title = reader.ReadElementValue(); break; case XmlElementNames.DocumentId: this.DocumentId = reader.ReadElementValue(); break; case XmlElementNames.PreviewURL: this.PreviewURL = reader.ReadElementValue(); break; case XmlElementNames.LastEditor: this.LastEditor = reader.ReadElementValue(); break; default: return false; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net.Http { public partial class ByteArrayContent : System.Net.Http.HttpContent { public ByteArrayContent(byte[] content) { } public ByteArrayContent(byte[] content, int offset, int count) { } protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; } protected internal override bool TryComputeLength(out long length) { throw null; } } public enum ClientCertificateOption { Automatic = 1, Manual = 0, } public abstract partial class DelegatingHandler : System.Net.Http.HttpMessageHandler { protected DelegatingHandler() { } protected DelegatingHandler(System.Net.Http.HttpMessageHandler innerHandler) { } public System.Net.Http.HttpMessageHandler InnerHandler { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class FormUrlEncodedContent : System.Net.Http.ByteArrayContent { public FormUrlEncodedContent(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, string>> nameValueCollection) : base(default(byte[])) { } } public partial class HttpClient : System.Net.Http.HttpMessageInvoker { public HttpClient() : base(default(System.Net.Http.HttpMessageHandler)) { } public HttpClient(System.Net.Http.HttpMessageHandler handler) : base(default(System.Net.Http.HttpMessageHandler)) { } public HttpClient(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) : base(default(System.Net.Http.HttpMessageHandler)) { } public System.Uri BaseAddress { get { throw null; } set { } } public System.Net.Http.Headers.HttpRequestHeaders DefaultRequestHeaders { get { throw null; } } public long MaxResponseContentBufferSize { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public void CancelPendingRequests() { } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> DeleteAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { throw null; } protected override void Dispose(bool disposing) { } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(string requestUri, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> GetAsync(System.Uri requestUri, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(string requestUri) { throw null; } public System.Threading.Tasks.Task<byte[]> GetByteArrayAsync(System.Uri requestUri) { throw null; } public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(string requestUri) { throw null; } public System.Threading.Tasks.Task<System.IO.Stream> GetStreamAsync(System.Uri requestUri) { throw null; } public System.Threading.Tasks.Task<string> GetStringAsync(string requestUri) { throw null; } public System.Threading.Tasks.Task<string> GetStringAsync(System.Uri requestUri) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(string requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsync(System.Uri requestUri, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption) { throw null; } public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class HttpClientHandler : System.Net.Http.HttpMessageHandler { public HttpClientHandler() { } public bool AllowAutoRedirect { get { throw null; } set { } } public System.Net.DecompressionMethods AutomaticDecompression { get { throw null; } set { } } public bool CheckCertificateRevocationList { get { throw null; } set { } } public System.Net.Http.ClientCertificateOption ClientCertificateOptions { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } } public System.Net.CookieContainer CookieContainer { get { throw null; } set { } } public System.Net.ICredentials Credentials { get { throw null; } set { } } public System.Net.ICredentials DefaultProxyCredentials { get { throw null; } set { } } public int MaxAutomaticRedirections { get { throw null; } set { } } public int MaxConnectionsPerServer { get { throw null; } set { } } public long MaxRequestContentBufferSize { get { throw null; } set { } } public int MaxResponseHeadersLength { get { throw null; } set { } } public bool PreAuthenticate { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } } public System.Net.IWebProxy Proxy { get { throw null; } set { } } public System.Func<System.Net.Http.HttpRequestMessage, System.Security.Cryptography.X509Certificates.X509Certificate2, System.Security.Cryptography.X509Certificates.X509Chain, System.Net.Security.SslPolicyErrors, bool> ServerCertificateCustomValidationCallback { get { throw null; } set { } } public System.Security.Authentication.SslProtocols SslProtocols { get { throw null; } set { } } public virtual bool SupportsAutomaticDecompression { get { throw null; } } public virtual bool SupportsProxy { get { throw null; } } public virtual bool SupportsRedirectConfiguration { get { throw null; } } public bool UseCookies { get { throw null; } set { } } public bool UseDefaultCredentials { get { throw null; } set { } } public bool UseProxy { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected internal override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; } } public enum HttpCompletionOption { ResponseContentRead = 0, ResponseHeadersRead = 1, } public abstract partial class HttpContent : System.IDisposable { protected HttpContent() { } public System.Net.Http.Headers.HttpContentHeaders Headers { get { throw null; } } public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream) { throw null; } public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; } protected virtual System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public System.Threading.Tasks.Task LoadIntoBufferAsync() { throw null; } public System.Threading.Tasks.Task LoadIntoBufferAsync(long maxBufferSize) { throw null; } public System.Threading.Tasks.Task<byte[]> ReadAsByteArrayAsync() { throw null; } public System.Threading.Tasks.Task<System.IO.Stream> ReadAsStreamAsync() { throw null; } public System.Threading.Tasks.Task<string> ReadAsStringAsync() { throw null; } protected abstract System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context); protected internal abstract bool TryComputeLength(out long length); } public abstract partial class HttpMessageHandler : System.IDisposable { protected HttpMessageHandler() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } protected internal abstract System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken); } public partial class HttpMessageInvoker : System.IDisposable { public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler) { } public HttpMessageInvoker(System.Net.Http.HttpMessageHandler handler, bool disposeHandler) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class HttpMethod : System.IEquatable<System.Net.Http.HttpMethod> { public HttpMethod(string method) { } public static System.Net.Http.HttpMethod Delete { get { throw null; } } public static System.Net.Http.HttpMethod Get { get { throw null; } } public static System.Net.Http.HttpMethod Head { get { throw null; } } public string Method { get { throw null; } } public static System.Net.Http.HttpMethod Options { get { throw null; } } public static System.Net.Http.HttpMethod Post { get { throw null; } } public static System.Net.Http.HttpMethod Put { get { throw null; } } public static System.Net.Http.HttpMethod Trace { get { throw null; } } public bool Equals(System.Net.Http.HttpMethod other) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { throw null; } public static bool operator !=(System.Net.Http.HttpMethod left, System.Net.Http.HttpMethod right) { throw null; } public override string ToString() { throw null; } } public partial class HttpRequestException : System.Exception { public HttpRequestException() { } public HttpRequestException(string message) { } public HttpRequestException(string message, System.Exception inner) { } } public partial class HttpRequestMessage : System.IDisposable { public HttpRequestMessage() { } public HttpRequestMessage(System.Net.Http.HttpMethod method, string requestUri) { } public HttpRequestMessage(System.Net.Http.HttpMethod method, System.Uri requestUri) { } public System.Net.Http.HttpContent Content { get { throw null; } set { } } public System.Net.Http.Headers.HttpRequestHeaders Headers { get { throw null; } } public System.Net.Http.HttpMethod Method { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } } public System.Uri RequestUri { get { throw null; } set { } } public System.Version Version { get { throw null; } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public override string ToString() { throw null; } } public partial class HttpResponseMessage : System.IDisposable { public HttpResponseMessage() { } public HttpResponseMessage(System.Net.HttpStatusCode statusCode) { } public System.Net.Http.HttpContent Content { get { throw null; } set { } } public System.Net.Http.Headers.HttpResponseHeaders Headers { get { throw null; } } public bool IsSuccessStatusCode { get { throw null; } } public string ReasonPhrase { get { throw null; } set { } } public System.Net.Http.HttpRequestMessage RequestMessage { get { throw null; } set { } } public System.Net.HttpStatusCode StatusCode { get { throw null; } set { } } public System.Version Version { get { throw null; } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public System.Net.Http.HttpResponseMessage EnsureSuccessStatusCode() { throw null; } public override string ToString() { throw null; } } public abstract partial class MessageProcessingHandler : System.Net.Http.DelegatingHandler { protected MessageProcessingHandler() { } protected MessageProcessingHandler(System.Net.Http.HttpMessageHandler innerHandler) { } protected abstract System.Net.Http.HttpRequestMessage ProcessRequest(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken); protected abstract System.Net.Http.HttpResponseMessage ProcessResponse(System.Net.Http.HttpResponseMessage response, System.Threading.CancellationToken cancellationToken); protected internal sealed override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class MultipartContent : System.Net.Http.HttpContent, System.Collections.Generic.IEnumerable<System.Net.Http.HttpContent>, System.Collections.IEnumerable { public MultipartContent() { } public MultipartContent(string subtype) { } public MultipartContent(string subtype, string boundary) { } public virtual void Add(System.Net.Http.HttpContent content) { } protected override void Dispose(bool disposing) { } public System.Collections.Generic.IEnumerator<System.Net.Http.HttpContent> GetEnumerator() { throw null; } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } protected internal override bool TryComputeLength(out long length) { throw null; } } public partial class MultipartFormDataContent : System.Net.Http.MultipartContent { public MultipartFormDataContent() { } public MultipartFormDataContent(string boundary) { } public override void Add(System.Net.Http.HttpContent content) { } public void Add(System.Net.Http.HttpContent content, string name) { } public void Add(System.Net.Http.HttpContent content, string name, string fileName) { } } public partial class StreamContent : System.Net.Http.HttpContent { public StreamContent(System.IO.Stream content) { } public StreamContent(System.IO.Stream content, int bufferSize) { } protected override System.Threading.Tasks.Task<System.IO.Stream> CreateContentReadStreamAsync() { throw null; } protected override void Dispose(bool disposing) { } protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { throw null; } protected internal override bool TryComputeLength(out long length) { throw null; } } public partial class StringContent : System.Net.Http.ByteArrayContent { public StringContent(string content) : base(default(byte[])) { } public StringContent(string content, System.Text.Encoding encoding) : base(default(byte[])) { } public StringContent(string content, System.Text.Encoding encoding, string mediaType) : base(default(byte[])) { } } } namespace System.Net.Http.Headers { public partial class AuthenticationHeaderValue : System.ICloneable { public AuthenticationHeaderValue(string scheme) { } public AuthenticationHeaderValue(string scheme, string parameter) { } public string Parameter { get { throw null; } } public string Scheme { get { throw null; } } public override bool Equals(object obj) { throw null; } object System.ICloneable.Clone() { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.AuthenticationHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.AuthenticationHeaderValue parsedValue) { throw null; } } public partial class CacheControlHeaderValue : System.ICloneable { public CacheControlHeaderValue() { } public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Extensions { get { throw null; } } public System.Nullable<System.TimeSpan> MaxAge { get { throw null; } set { } } public bool MaxStale { get { throw null; } set { } } public System.Nullable<System.TimeSpan> MaxStaleLimit { get { throw null; } set { } } public System.Nullable<System.TimeSpan> MinFresh { get { throw null; } set { } } public bool MustRevalidate { get { throw null; } set { } } public bool NoCache { get { throw null; } set { } } public System.Collections.Generic.ICollection<string> NoCacheHeaders { get { throw null; } } public bool NoStore { get { throw null; } set { } } public bool NoTransform { get { throw null; } set { } } public bool OnlyIfCached { get { throw null; } set { } } public bool Private { get { throw null; } set { } } public System.Collections.Generic.ICollection<string> PrivateHeaders { get { throw null; } } public bool ProxyRevalidate { get { throw null; } set { } } public bool Public { get { throw null; } set { } } public System.Nullable<System.TimeSpan> SharedMaxAge { get { throw null; } set { } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.CacheControlHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.CacheControlHeaderValue parsedValue) { throw null; } } public partial class ContentDispositionHeaderValue : System.ICloneable { protected ContentDispositionHeaderValue(System.Net.Http.Headers.ContentDispositionHeaderValue source) { } public ContentDispositionHeaderValue(string dispositionType) { } public System.Nullable<System.DateTimeOffset> CreationDate { get { throw null; } set { } } public string DispositionType { get { throw null; } set { } } public string FileName { get { throw null; } set { } } public string FileNameStar { get { throw null; } set { } } public System.Nullable<System.DateTimeOffset> ModificationDate { get { throw null; } set { } } public string Name { get { throw null; } set { } } public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } } public System.Nullable<System.DateTimeOffset> ReadDate { get { throw null; } set { } } public System.Nullable<long> Size { get { throw null; } set { } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.ContentDispositionHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.ContentDispositionHeaderValue parsedValue) { throw null; } } public partial class ContentRangeHeaderValue : System.ICloneable { public ContentRangeHeaderValue(long length) { } public ContentRangeHeaderValue(long from, long to) { } public ContentRangeHeaderValue(long from, long to, long length) { } public System.Nullable<long> From { get { throw null; } } public bool HasLength { get { throw null; } } public bool HasRange { get { throw null; } } public System.Nullable<long> Length { get { throw null; } } public System.Nullable<long> To { get { throw null; } } public string Unit { get { throw null; } set { } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.ContentRangeHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.ContentRangeHeaderValue parsedValue) { throw null; } } public partial class EntityTagHeaderValue : System.ICloneable { public EntityTagHeaderValue(string tag) { } public EntityTagHeaderValue(string tag, bool isWeak) { } public static System.Net.Http.Headers.EntityTagHeaderValue Any { get { throw null; } } public bool IsWeak { get { throw null; } } public string Tag { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.EntityTagHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.EntityTagHeaderValue parsedValue) { throw null; } } public sealed partial class HttpContentHeaders : System.Net.Http.Headers.HttpHeaders { internal HttpContentHeaders() { } public System.Collections.Generic.ICollection<string> Allow { get { throw null; } } public System.Net.Http.Headers.ContentDispositionHeaderValue ContentDisposition { get { throw null; } set { } } public System.Collections.Generic.ICollection<string> ContentEncoding { get { throw null; } } public System.Collections.Generic.ICollection<string> ContentLanguage { get { throw null; } } public System.Nullable<long> ContentLength { get { throw null; } set { } } public System.Uri ContentLocation { get { throw null; } set { } } public byte[] ContentMD5 { get { throw null; } set { } } public System.Net.Http.Headers.ContentRangeHeaderValue ContentRange { get { throw null; } set { } } public System.Net.Http.Headers.MediaTypeHeaderValue ContentType { get { throw null; } set { } } public System.Nullable<System.DateTimeOffset> Expires { get { throw null; } set { } } public System.Nullable<System.DateTimeOffset> LastModified { get { throw null; } set { } } } public abstract partial class HttpHeaders : System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>>, System.Collections.IEnumerable { protected HttpHeaders() { } public void Add(string name, System.Collections.Generic.IEnumerable<string> values) { } public void Add(string name, string value) { } public void Clear() { } public bool Contains(string name) { throw null; } public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.IEnumerable<string>>> GetEnumerator() { throw null; } public System.Collections.Generic.IEnumerable<string> GetValues(string name) { throw null; } public bool Remove(string name) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public override string ToString() { throw null; } public bool TryAddWithoutValidation(string name, System.Collections.Generic.IEnumerable<string> values) { throw null; } public bool TryAddWithoutValidation(string name, string value) { throw null; } public bool TryGetValues(string name, out System.Collections.Generic.IEnumerable<string> values) { throw null; } } public sealed partial class HttpHeaderValueCollection<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable where T : class { internal HttpHeaderValueCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public void Add(T item) { } public void Clear() { } public bool Contains(T item) { throw null; } public void CopyTo(T[] array, int arrayIndex) { } public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; } public void ParseAdd(string input) { } public bool Remove(T item) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public override string ToString() { throw null; } public bool TryParseAdd(string input) { throw null; } } public sealed partial class HttpRequestHeaders : System.Net.Http.Headers.HttpHeaders { internal HttpRequestHeaders() { } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.MediaTypeWithQualityHeaderValue> Accept { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptCharset { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptEncoding { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.StringWithQualityHeaderValue> AcceptLanguage { get { throw null; } } public System.Net.Http.Headers.AuthenticationHeaderValue Authorization { get { throw null; } set { } } public System.Net.Http.Headers.CacheControlHeaderValue CacheControl { get { throw null; } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<string> Connection { get { throw null; } } public System.Nullable<bool> ConnectionClose { get { throw null; } set { } } public System.Nullable<System.DateTimeOffset> Date { get { throw null; } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueWithParametersHeaderValue> Expect { get { throw null; } } public System.Nullable<bool> ExpectContinue { get { throw null; } set { } } public string From { get { throw null; } set { } } public string Host { get { throw null; } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue> IfMatch { get { throw null; } } public System.Nullable<System.DateTimeOffset> IfModifiedSince { get { throw null; } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.EntityTagHeaderValue> IfNoneMatch { get { throw null; } } public System.Net.Http.Headers.RangeConditionHeaderValue IfRange { get { throw null; } set { } } public System.Nullable<System.DateTimeOffset> IfUnmodifiedSince { get { throw null; } set { } } public System.Nullable<int> MaxForwards { get { throw null; } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue> Pragma { get { throw null; } } public System.Net.Http.Headers.AuthenticationHeaderValue ProxyAuthorization { get { throw null; } set { } } public System.Net.Http.Headers.RangeHeaderValue Range { get { throw null; } set { } } public System.Uri Referrer { get { throw null; } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingWithQualityHeaderValue> TE { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<string> Trailer { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue> TransferEncoding { get { throw null; } } public System.Nullable<bool> TransferEncodingChunked { get { throw null; } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue> Upgrade { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> UserAgent { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue> Via { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue> Warning { get { throw null; } } } public sealed partial class HttpResponseHeaders : System.Net.Http.Headers.HttpHeaders { internal HttpResponseHeaders() { } public System.Net.Http.Headers.HttpHeaderValueCollection<string> AcceptRanges { get { throw null; } } public System.Nullable<System.TimeSpan> Age { get { throw null; } set { } } public System.Net.Http.Headers.CacheControlHeaderValue CacheControl { get { throw null; } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<string> Connection { get { throw null; } } public System.Nullable<bool> ConnectionClose { get { throw null; } set { } } public System.Nullable<System.DateTimeOffset> Date { get { throw null; } set { } } public System.Net.Http.Headers.EntityTagHeaderValue ETag { get { throw null; } set { } } public System.Uri Location { get { throw null; } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.NameValueHeaderValue> Pragma { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue> ProxyAuthenticate { get { throw null; } } public System.Net.Http.Headers.RetryConditionHeaderValue RetryAfter { get { throw null; } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> Server { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<string> Trailer { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.TransferCodingHeaderValue> TransferEncoding { get { throw null; } } public System.Nullable<bool> TransferEncodingChunked { get { throw null; } set { } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductHeaderValue> Upgrade { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<string> Vary { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ViaHeaderValue> Via { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.WarningHeaderValue> Warning { get { throw null; } } public System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.AuthenticationHeaderValue> WwwAuthenticate { get { throw null; } } } public partial class MediaTypeHeaderValue : System.ICloneable { protected MediaTypeHeaderValue(System.Net.Http.Headers.MediaTypeHeaderValue source) { } public MediaTypeHeaderValue(string mediaType) { } public string CharSet { get { throw null; } set { } } public string MediaType { get { throw null; } set { } } public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.MediaTypeHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeHeaderValue parsedValue) { throw null; } } public sealed partial class MediaTypeWithQualityHeaderValue : System.Net.Http.Headers.MediaTypeHeaderValue, System.ICloneable { public MediaTypeWithQualityHeaderValue(string mediaType) : base(default(System.Net.Http.Headers.MediaTypeHeaderValue)) { } public MediaTypeWithQualityHeaderValue(string mediaType, double quality) : base(default(System.Net.Http.Headers.MediaTypeHeaderValue)) { } public System.Nullable<double> Quality { get { throw null; } set { } } object System.ICloneable.Clone() { throw null; } public static new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue Parse(string input) { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.MediaTypeWithQualityHeaderValue parsedValue) { throw null; } } public partial class NameValueHeaderValue : System.ICloneable { protected NameValueHeaderValue(System.Net.Http.Headers.NameValueHeaderValue source) { } public NameValueHeaderValue(string name) { } public NameValueHeaderValue(string name, string value) { } public string Name { get { throw null; } } public string Value { get { throw null; } set { } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.NameValueHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.NameValueHeaderValue parsedValue) { throw null; } } public partial class NameValueWithParametersHeaderValue : System.Net.Http.Headers.NameValueHeaderValue, System.ICloneable { protected NameValueWithParametersHeaderValue(System.Net.Http.Headers.NameValueWithParametersHeaderValue source) : base(default(string)) { } public NameValueWithParametersHeaderValue(string name) : base(default(string)) { } public NameValueWithParametersHeaderValue(string name, string value) : base(default(string)) { } public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static new System.Net.Http.Headers.NameValueWithParametersHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.NameValueWithParametersHeaderValue parsedValue) { throw null; } } public partial class ProductHeaderValue : System.ICloneable { public ProductHeaderValue(string name) { } public ProductHeaderValue(string name, string version) { } public string Name { get { throw null; } } public string Version { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.ProductHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.ProductHeaderValue parsedValue) { throw null; } } public partial class ProductInfoHeaderValue : System.ICloneable { public ProductInfoHeaderValue(System.Net.Http.Headers.ProductHeaderValue product) { } public ProductInfoHeaderValue(string comment) { } public ProductInfoHeaderValue(string productName, string productVersion) { } public string Comment { get { throw null; } } public System.Net.Http.Headers.ProductHeaderValue Product { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.ProductInfoHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.ProductInfoHeaderValue parsedValue) { throw null; } } public partial class RangeConditionHeaderValue : System.ICloneable { public RangeConditionHeaderValue(System.DateTimeOffset date) { } public RangeConditionHeaderValue(System.Net.Http.Headers.EntityTagHeaderValue entityTag) { } public RangeConditionHeaderValue(string entityTag) { } public System.Nullable<System.DateTimeOffset> Date { get { throw null; } } public System.Net.Http.Headers.EntityTagHeaderValue EntityTag { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.RangeConditionHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.RangeConditionHeaderValue parsedValue) { throw null; } } public partial class RangeHeaderValue : System.ICloneable { public RangeHeaderValue() { } public RangeHeaderValue(System.Nullable<long> from, System.Nullable<long> to) { } public System.Collections.Generic.ICollection<System.Net.Http.Headers.RangeItemHeaderValue> Ranges { get { throw null; } } public string Unit { get { throw null; } set { } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.RangeHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.RangeHeaderValue parsedValue) { throw null; } } public partial class RangeItemHeaderValue : System.ICloneable { public RangeItemHeaderValue(System.Nullable<long> from, System.Nullable<long> to) { } public System.Nullable<long> From { get { throw null; } } public System.Nullable<long> To { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } public partial class RetryConditionHeaderValue : System.ICloneable { public RetryConditionHeaderValue(System.DateTimeOffset date) { } public RetryConditionHeaderValue(System.TimeSpan delta) { } public System.Nullable<System.DateTimeOffset> Date { get { throw null; } } public System.Nullable<System.TimeSpan> Delta { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.RetryConditionHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.RetryConditionHeaderValue parsedValue) { throw null; } } public partial class StringWithQualityHeaderValue : System.ICloneable { public StringWithQualityHeaderValue(string value) { } public StringWithQualityHeaderValue(string value, double quality) { } public System.Nullable<double> Quality { get { throw null; } } public string Value { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.StringWithQualityHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.StringWithQualityHeaderValue parsedValue) { throw null; } } public partial class TransferCodingHeaderValue : System.ICloneable { protected TransferCodingHeaderValue(System.Net.Http.Headers.TransferCodingHeaderValue source) { } public TransferCodingHeaderValue(string value) { } public System.Collections.Generic.ICollection<System.Net.Http.Headers.NameValueHeaderValue> Parameters { get { throw null; } } public string Value { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.TransferCodingHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingHeaderValue parsedValue) { throw null; } } public sealed partial class TransferCodingWithQualityHeaderValue : System.Net.Http.Headers.TransferCodingHeaderValue, System.ICloneable { public TransferCodingWithQualityHeaderValue(string value) : base(default(System.Net.Http.Headers.TransferCodingHeaderValue)) { } public TransferCodingWithQualityHeaderValue(string value, double quality) : base(default(System.Net.Http.Headers.TransferCodingHeaderValue)) { } public System.Nullable<double> Quality { get { throw null; } set { } } object System.ICloneable.Clone() { throw null; } public static new System.Net.Http.Headers.TransferCodingWithQualityHeaderValue Parse(string input) { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.TransferCodingWithQualityHeaderValue parsedValue) { throw null; } } public partial class ViaHeaderValue : System.ICloneable { public ViaHeaderValue(string protocolVersion, string receivedBy) { } public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName) { } public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName, string comment) { } public string Comment { get { throw null; } } public string ProtocolName { get { throw null; } } public string ProtocolVersion { get { throw null; } } public string ReceivedBy { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.ViaHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.ViaHeaderValue parsedValue) { throw null; } } public partial class WarningHeaderValue : System.ICloneable { public WarningHeaderValue(int code, string agent, string text) { } public WarningHeaderValue(int code, string agent, string text, System.DateTimeOffset date) { } public string Agent { get { throw null; } } public int Code { get { throw null; } } public System.Nullable<System.DateTimeOffset> Date { get { throw null; } } public string Text { get { throw null; } } object System.ICloneable.Clone() { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Net.Http.Headers.WarningHeaderValue Parse(string input) { throw null; } public override string ToString() { throw null; } public static bool TryParse(string input, out System.Net.Http.Headers.WarningHeaderValue parsedValue) { throw null; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudioTools; namespace Microsoft.PythonTools.Intellisense { using AP = AnalysisProtocol; class TaskProviderItem { private readonly string _message; private readonly SourceSpan _rawSpan; private readonly VSTASKPRIORITY _priority; private readonly VSTASKCATEGORY _category; private readonly bool _squiggle; private readonly LocationTracker _spanTranslator; private readonly IServiceProvider _serviceProvider; internal TaskProviderItem( IServiceProvider serviceProvider, string message, SourceSpan rawSpan, VSTASKPRIORITY priority, VSTASKCATEGORY category, bool squiggle, LocationTracker spanTranslator ) { _serviceProvider = serviceProvider; _message = message; _rawSpan = rawSpan; _spanTranslator = spanTranslator; _rawSpan = rawSpan; _priority = priority; _category = category; _squiggle = squiggle; } private string ErrorType { get { switch (_priority) { case VSTASKPRIORITY.TP_HIGH: return PredefinedErrorTypeNames.SyntaxError; case VSTASKPRIORITY.TP_LOW: return PredefinedErrorTypeNames.OtherError; case VSTASKPRIORITY.TP_NORMAL: return PredefinedErrorTypeNames.Warning; default: return string.Empty; } } } #region Conversion Functions public bool IsValid { get { if (!_squiggle || _spanTranslator == null || string.IsNullOrEmpty(ErrorType)) { return false; } return true; } } public void CreateSquiggleSpan(SimpleTagger<ErrorTag> tagger) { SnapshotSpan target = _spanTranslator.TranslateForward( new Span(_rawSpan.Start.Index, _rawSpan.Length) ); var tagSpan = _spanTranslator.TextBuffer.CurrentSnapshot.CreateTrackingSpan( target.Start, target.Length, SpanTrackingMode.EdgeInclusive ); tagger.CreateTagSpan(tagSpan, new ErrorTag(ErrorType, _message)); } public ITextBuffer TextBuffer { get { if (_spanTranslator != null) { return _spanTranslator.TextBuffer; } return null; } } public ErrorTaskItem ToErrorTaskItem(EntryKey key) { return new ErrorTaskItem( _serviceProvider, _rawSpan, _message, (key.Entry != null ? key.Entry.Path : null) ?? string.Empty ) { Priority = _priority, Category = _category }; } #endregion private static ITrackingSpan CreateSpan(ITextSnapshot snapshot, SourceSpan span) { Debug.Assert(span.Start.Index >= 0); var res = new Span( span.Start.Index, Math.Min(span.End.Index - span.Start.Index, Math.Max(snapshot.Length - span.Start.Index, 0)) ); Debug.Assert(res.End <= snapshot.Length); return snapshot.CreateTrackingSpan(res, SpanTrackingMode.EdgeNegative); } } sealed class TaskProviderItemFactory { private readonly LocationTracker _spanTranslator; public TaskProviderItemFactory(LocationTracker spanTranslator) { _spanTranslator = spanTranslator; } #region Factory Functions public TaskProviderItem FromErrorResult(IServiceProvider serviceProvider, AP.Error result, VSTASKPRIORITY priority, VSTASKCATEGORY category) { return new TaskProviderItem( serviceProvider, result.message, GetSpan (result), priority, category, true, _spanTranslator ); } internal static SourceSpan GetSpan(AP.Error result) { return new SourceSpan( new SourceLocation(result.startIndex, result.startLine, result.startColumn), new SourceLocation(result.startIndex + result.length, result.endLine, result.endColumn) ); } internal TaskProviderItem FromUnresolvedImport( IServiceProvider serviceProvider, IPythonInterpreterFactoryWithDatabase factory, string importName, SourceSpan span ) { string message; if (factory != null && !factory.IsCurrent) { message = Strings.UnresolvedModuleTooltipRefreshing.FormatUI(importName); } else { message = Strings.UnresolvedModuleTooltip.FormatUI(importName); } return new TaskProviderItem( serviceProvider, message, span, VSTASKPRIORITY.TP_NORMAL, VSTASKCATEGORY.CAT_BUILDCOMPILE, true, _spanTranslator ); } #endregion } struct EntryKey : IEquatable<EntryKey> { public AnalysisEntry Entry; public string Moniker; public static readonly EntryKey Empty = new EntryKey(null, null); public EntryKey(AnalysisEntry entry, string moniker) { Entry = entry; Moniker = moniker; } public override bool Equals(object obj) { return obj is EntryKey && Equals((EntryKey)obj); } public bool Equals(EntryKey other) { return Entry == other.Entry && Moniker == other.Moniker; } public override int GetHashCode() { return (Entry == null ? 0 : Entry.GetHashCode()) ^ (Moniker ?? string.Empty).GetHashCode(); } } abstract class WorkerMessage { private readonly EntryKey _key; private readonly List<TaskProviderItem> _items; protected WorkerMessage() { _key = EntryKey.Empty; } protected WorkerMessage(EntryKey key, List<TaskProviderItem> items) { _key = key; _items = items; } public abstract bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock); // Factory methods public static WorkerMessage Clear() { return new ClearMessage(EntryKey.Empty); } public static WorkerMessage Clear(AnalysisEntry entry, string moniker) { return new ClearMessage(new EntryKey(entry, moniker)); } public static WorkerMessage Replace(AnalysisEntry entry, string moniker, List<TaskProviderItem> items) { return new ReplaceMessage(new EntryKey(entry, moniker), items); } public static WorkerMessage Append(AnalysisEntry entry, string moniker, List<TaskProviderItem> items) { return new AppendMessage(new EntryKey(entry, moniker), items); } public static WorkerMessage Flush(TaskCompletionSource<TimeSpan> taskSource) { return new FlushMessage(taskSource, DateTime.Now); } public static WorkerMessage Abort() { return new AbortMessage(); } // Message implementations sealed class ReplaceMessage : WorkerMessage { public ReplaceMessage(EntryKey key, List<TaskProviderItem> items) : base(key, items) { } public override bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock) { lock (itemsLock) { items[_key] = _items; return true; } } public override string ToString() { return "Replace " + _key.Moniker + " " + _items.Count + " " + _key.Entry?.Path; } } sealed class AppendMessage : WorkerMessage { public AppendMessage(EntryKey key, List<TaskProviderItem> items) : base(key, items) { } public override bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock) { lock (itemsLock) { List<TaskProviderItem> itemList; if (items.TryGetValue(_key, out itemList)) { itemList.AddRange(_items); } else { items[_key] = _items; } return true; } } public override string ToString() { return "Append " + _key.Moniker + " " + _key.Entry?.Path; } } sealed class ClearMessage : WorkerMessage { public ClearMessage(EntryKey key) : base(key, null) { } public override bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock) { lock (itemsLock) { if (_key.Entry != null) { items.Remove(_key); } else { items.Clear(); } // Always return true to ensure the refresh occurs return true; } } public override string ToString() { return "Clear " + _key.Moniker + " " + _key.Entry?.Path; } } internal sealed class FlushMessage : WorkerMessage { private readonly TaskCompletionSource<TimeSpan> _tcs; private readonly DateTime _start; public FlushMessage(TaskCompletionSource<TimeSpan> taskSource, DateTime start) : base(EntryKey.Empty, null) { _tcs = taskSource; _start = start; } public override bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock) { _tcs.SetResult(DateTime.Now - _start); return false; } } internal sealed class AbortMessage : WorkerMessage { public AbortMessage() : base() { } public override bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock) { throw new OperationCanceledException(); } } } class TaskProvider : IVsTaskProvider, IDisposable { private readonly Dictionary<EntryKey, List<TaskProviderItem>> _items; private readonly Dictionary<EntryKey, HashSet<ITextBuffer>> _errorSources; private readonly object _itemsLock = new object(); private uint _cookie; private readonly IVsTaskList _taskList; private readonly IErrorProviderFactory _errorProvider; protected readonly IServiceProvider _serviceProvider; private Thread _worker; private readonly Queue<WorkerMessage> _workerQueue = new Queue<WorkerMessage>(); private readonly ManualResetEventSlim _workerQueueChanged = new ManualResetEventSlim(); public TaskProvider(IServiceProvider serviceProvider, IVsTaskList taskList, IErrorProviderFactory errorProvider) { _serviceProvider = serviceProvider; _items = new Dictionary<EntryKey, List<TaskProviderItem>>(); _errorSources = new Dictionary<EntryKey, HashSet<ITextBuffer>>(); _taskList = taskList; _errorProvider = errorProvider; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposing) { var worker = _worker; if (worker != null) { Debug.WriteLine(String.Format("Sending abort... {0}", DateTime.Now)); lock (_workerQueue) { _workerQueue.Clear(); _workerQueue.Enqueue(WorkerMessage.Abort()); _workerQueueChanged.Set(); } Debug.WriteLine(String.Format("Waiting for abort... {0}", DateTime.Now)); bool stopped = worker.Join(10000); Debug.WriteLine(String.Format("Done Waiting for abort... {0} {1}", DateTime.Now, stopped)); Debug.Assert(stopped, "Failed to terminate TaskProvider worker thread"); } lock (_itemsLock) { _items.Clear(); } if (_taskList != null) { _taskList.UnregisterTaskProvider(_cookie); } _workerQueueChanged.Dispose(); } } ~TaskProvider() { Dispose(false); } public uint Cookie { get { return _cookie; } } /// <summary> /// Replaces the items for the specified entry. /// </summary> public void ReplaceItems(AnalysisEntry entry, string moniker, List<TaskProviderItem> items) { SendMessage(WorkerMessage.Replace(entry, moniker, items)); } /// <summary> /// Adds items to the specified entry's existing items. /// </summary> public void AddItems(AnalysisEntry entry, string moniker, List<TaskProviderItem> items) { SendMessage(WorkerMessage.Append(entry, moniker, items)); } /// <summary> /// Removes all items from all entries. /// </summary> public void ClearAll() { SendMessage(WorkerMessage.Clear()); } /// <summary> /// Removes all items for the specified entry. /// </summary> public void Clear(AnalysisEntry entry, string moniker) { SendMessage(WorkerMessage.Clear(entry, moniker)); } /// <summary> /// Waits for all messages to clear the queue. This typically takes at /// least one second, since that is the timeout on the worker thread. /// </summary> /// <returns> /// The time between when flush was called and the queue completed. /// </returns> public Task<TimeSpan> FlushAsync() { var tcs = new TaskCompletionSource<TimeSpan>(); SendMessage(WorkerMessage.Flush(tcs)); return tcs.Task; } /// <summary> /// Adds the buffer to be tracked for reporting squiggles and error list entries /// for the given project entry and moniker for the error source. /// </summary> public void AddBufferForErrorSource(AnalysisEntry entry, string moniker, ITextBuffer buffer) { lock (_errorSources) { var key = new EntryKey(entry, moniker); HashSet<ITextBuffer> buffers; if (!_errorSources.TryGetValue(key, out buffers)) { _errorSources[new EntryKey(entry, moniker)] = buffers = new HashSet<ITextBuffer>(); } buffers.Add(buffer); } } /// <summary> /// Removes the buffer from tracking for reporting squiggles and error list entries /// for the given project entry and moniker for the error source. /// </summary> public void RemoveBufferForErrorSource(AnalysisEntry entry, string moniker, ITextBuffer buffer) { lock (_errorSources) { var key = new EntryKey(entry, moniker); HashSet<ITextBuffer> buffers; if (_errorSources.TryGetValue(key, out buffers)) { buffers.Remove(buffer); } } } /// <summary> /// Clears all tracked buffers for the given project entry and moniker for /// the error source. /// </summary> public void ClearErrorSource(AnalysisEntry entry, string moniker) { lock (_errorSources) { _errorSources.Remove(new EntryKey(entry, moniker)); } } #region Internal Worker Thread private void StartWorker() { if (_worker != null) { // Already running Debug.Assert(_worker.IsAlive, "Worker has died without clearing itself"); return; } var t = new Thread(Worker); t.IsBackground = true; t.Name = GetType().Name + " Worker"; t.Start(t); } private void Worker(object param) { for (;;) { var self = (Thread)param; if (Interlocked.CompareExchange(ref _worker, self, null) != null) { // Not us, so abort return; } try { WorkerWorker(); } catch (OperationCanceledException) { Debug.WriteLine(string.Format("Operation cancellled... {0}", DateTime.Now)); } catch (ObjectDisposedException ex) { Trace.TraceError(ex.ToString()); break; } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } ex.ReportUnhandledException(_serviceProvider, GetType()); } finally { var oldWorker = Interlocked.CompareExchange(ref _worker, null, self); Debug.WriteLine(string.Format("Checking worker... {0}", DateTime.Now)); Debug.Assert(oldWorker == self, "Worker was changed while running"); Debug.WriteLine(string.Format("Worker exiting... {0}", DateTime.Now)); } // check for work after clearing out _worker so that we don't race with // StartWorker and end up with no worker. lock (_workerQueue) { if (_workerQueue.Count == 0) { break; } Debug.WriteLine("Spinning to try and become worker again..."); } } } private void WorkerWorker() { var flushMessages = new Queue<WorkerMessage>(); bool changed = false; var lastUpdateTime = DateTime.Now; while (_workerQueueChanged.Wait(1000)) { // Reset event and handle all messages in the queue _workerQueueChanged.Reset(); while (true) { WorkerMessage msg; lock (_workerQueue) { if (_workerQueue.Count == 0) { break; } msg = _workerQueue.Dequeue(); Debug.WriteLine(string.Format("{2} Processing msg... {0} {1}", DateTime.Now, msg, GetType())); } if (msg is WorkerMessage.FlushMessage) { // Keep flush messages until we've exited the loop flushMessages.Enqueue(msg); } else { // Apply the message to our collection changed |= msg.Apply(_items, _itemsLock); } Debug.WriteLine(string.Format("{2} Done processing msg... {0} {1}", DateTime.Now, msg, GetType())); // Every second, we want to force another update if (changed) { var currentTime = DateTime.Now; if ((currentTime - lastUpdateTime).TotalMilliseconds > 1000) { if (Refresh()) { lastUpdateTime = currentTime; changed = false; } } } } Debug.WriteLine(string.Format("Looping to wait... {0}", DateTime.Now)); } // Handle any changes that weren't handled in the loop if (changed) { Debug.WriteLine(string.Format("Refreshing... {0}", DateTime.Now)); Refresh(); } // Notify all the flush messages we received Debug.WriteLine(string.Format("Flushing... {0}", DateTime.Now)); while (flushMessages.Any()) { var msg = flushMessages.Dequeue(); msg.Apply(_items, _itemsLock); } Debug.WriteLine(string.Format("Done flushing... {0}", DateTime.Now)); } private bool Refresh() { if (_taskList == null && _errorProvider == null) { return true; } _serviceProvider.GetUIThread().MustNotBeCalledFromUIThread(); // Allow 1 second to get onto the UI thread for the update // Otherwise abort and we'll try again later var cts = new CancellationTokenSource(1000); try { try { RefreshAsync(cts.Token).Wait(cts.Token); } catch (AggregateException ex) { if (ex.InnerExceptions.Count == 1) { throw ex.InnerException; } throw; } } catch (OperationCanceledException) { return false; } catch (Exception ex) when (!ex.IsCriticalException()) { ex.ReportUnhandledException(_serviceProvider, GetType()); } finally { cts.Dispose(); } return true; } private async Task RefreshAsync(CancellationToken cancellationToken) { var buffers = new HashSet<ITextBuffer>(); var bufferToErrorList = new Dictionary<ITextBuffer, List<TaskProviderItem>>(); if (_errorProvider != null) { lock (_errorSources) { cancellationToken.ThrowIfCancellationRequested(); foreach (var kv in _errorSources) { List<TaskProviderItem> items; buffers.UnionWith(kv.Value); lock (_itemsLock) { if (!_items.TryGetValue(kv.Key, out items)) { continue; } foreach (var item in items) { if (item.IsValid) { List<TaskProviderItem> itemList; if (!bufferToErrorList.TryGetValue(item.TextBuffer, out itemList)) { bufferToErrorList[item.TextBuffer] = itemList = new List<TaskProviderItem>(); } itemList.Add(item); } } } } } } await _serviceProvider.GetUIThread().InvokeAsync(() => { if (_taskList != null) { if (_cookie == 0) { ErrorHandler.ThrowOnFailure(_taskList.RegisterTaskProvider(this, out _cookie)); } try { _taskList.RefreshTasks(_cookie); } catch (InvalidComObjectException) { // DevDiv2 759317 - Watson bug, COM object can go away... } } if (_errorProvider != null) { foreach (var kv in bufferToErrorList) { var tagger = _errorProvider.GetErrorTagger(kv.Key); if (tagger == null) { continue; } if (buffers.Remove(kv.Key)) { tagger.RemoveTagSpans(span => span.Span.TextBuffer == kv.Key); } foreach (var taskProviderItem in kv.Value) { taskProviderItem.CreateSquiggleSpan(tagger); } } if (buffers.Any()) { // Clear tags for any remaining buffers. foreach (var buffer in buffers) { var tagger = _errorProvider.GetErrorTagger(buffer); tagger.RemoveTagSpans(span => span.Span.TextBuffer == buffer); } } } }, cancellationToken); } private void SendMessage(WorkerMessage message) { lock (_workerQueue) { _workerQueue.Enqueue(message); _workerQueueChanged.Set(); } StartWorker(); } #endregion #region IVsTaskProvider Members public int EnumTaskItems(out IVsEnumTaskItems ppenum) { lock (_itemsLock) { ppenum = new TaskEnum(_items .Where(x => x.Key.Entry.Path != null) // don't report REPL window errors in the error list, you can't naviagate to them .SelectMany(kv => kv.Value.Select(i => i.ToErrorTaskItem(kv.Key))) .ToArray() ); } return VSConstants.S_OK; } public int ImageList(out IntPtr phImageList) { // not necessary if we report our category as build compile. phImageList = IntPtr.Zero; return VSConstants.E_NOTIMPL; } public int OnTaskListFinalRelease(IVsTaskList pTaskList) { return VSConstants.S_OK; } public int ReRegistrationKey(out string pbstrKey) { pbstrKey = null; return VSConstants.E_NOTIMPL; } public int SubcategoryList(uint cbstr, string[] rgbstr, out uint pcActual) { pcActual = 0; return VSConstants.S_OK; } #endregion } class TaskEnum : IVsEnumTaskItems { private readonly IEnumerable<ErrorTaskItem> _enumerable; private IEnumerator<ErrorTaskItem> _enumerator; public TaskEnum(IEnumerable<ErrorTaskItem> items) { _enumerable = items; _enumerator = _enumerable.GetEnumerator(); } public int Clone(out IVsEnumTaskItems ppenum) { ppenum = new TaskEnum(_enumerable); return VSConstants.S_OK; } public int Next(uint celt, IVsTaskItem[] rgelt, uint[] pceltFetched = null) { bool fetchedAny = false; if (pceltFetched != null && pceltFetched.Length > 0) { pceltFetched[0] = 0; } for (int i = 0; i < celt && _enumerator.MoveNext(); i++) { if (pceltFetched != null && pceltFetched.Length > 0) { pceltFetched[0] = (uint)i + 1; } rgelt[i] = _enumerator.Current; fetchedAny = true; } return fetchedAny ? VSConstants.S_OK : VSConstants.S_FALSE; } public int Reset() { _enumerator = _enumerable.GetEnumerator(); return VSConstants.S_OK; } public int Skip(uint celt) { while (celt != 0 && _enumerator.MoveNext()) { celt--; } return VSConstants.S_OK; } } class ErrorTaskItem : IVsTaskItem { private readonly IServiceProvider _serviceProvider; public ErrorTaskItem( IServiceProvider serviceProvider, SourceSpan span, string message, string sourceFile ) { _serviceProvider = serviceProvider; Span = span; Message = message; SourceFile = sourceFile; Category = VSTASKCATEGORY.CAT_BUILDCOMPILE; Priority = VSTASKPRIORITY.TP_NORMAL; MessageIsReadOnly = true; IsCheckedIsReadOnly = true; PriorityIsReadOnly = true; } public SourceSpan Span { get; private set; } public string Message { get; set; } public string SourceFile { get; set; } public VSTASKCATEGORY Category { get; set; } public VSTASKPRIORITY Priority { get; set; } public bool CanDelete { get; set; } public bool IsChecked { get; set; } public bool MessageIsReadOnly { get; set; } public bool IsCheckedIsReadOnly { get; set; } public bool PriorityIsReadOnly { get; set; } int IVsTaskItem.CanDelete(out int pfCanDelete) { pfCanDelete = CanDelete ? 1 : 0; return VSConstants.S_OK; } int IVsTaskItem.Category(VSTASKCATEGORY[] pCat) { pCat[0] = Category; return VSConstants.S_OK; } int IVsTaskItem.Column(out int piCol) { if (Span.Start.Line == 1 && Span.Start.Column == 1 && Span.Start.Index != 0) { // we don't have the column number calculated piCol = 0; return VSConstants.E_FAIL; } piCol = Span.Start.Column - 1; return VSConstants.S_OK; } int IVsTaskItem.Document(out string pbstrMkDocument) { pbstrMkDocument = SourceFile; return VSConstants.S_OK; } int IVsTaskItem.HasHelp(out int pfHasHelp) { pfHasHelp = 0; return VSConstants.S_OK; } int IVsTaskItem.ImageListIndex(out int pIndex) { pIndex = 0; return VSConstants.E_NOTIMPL; } int IVsTaskItem.IsReadOnly(VSTASKFIELD field, out int pfReadOnly) { switch (field) { case VSTASKFIELD.FLD_CHECKED: pfReadOnly = IsCheckedIsReadOnly ? 1 : 0; break; case VSTASKFIELD.FLD_DESCRIPTION: pfReadOnly = MessageIsReadOnly ? 1 : 0; break; case VSTASKFIELD.FLD_PRIORITY: pfReadOnly = PriorityIsReadOnly ? 1 : 0; break; case VSTASKFIELD.FLD_BITMAP: case VSTASKFIELD.FLD_CATEGORY: case VSTASKFIELD.FLD_COLUMN: case VSTASKFIELD.FLD_CUSTOM: case VSTASKFIELD.FLD_FILE: case VSTASKFIELD.FLD_LINE: case VSTASKFIELD.FLD_PROVIDERKNOWSORDER: case VSTASKFIELD.FLD_SUBCATEGORY: default: pfReadOnly = 1; break; } return VSConstants.S_OK; } int IVsTaskItem.Line(out int piLine) { if (Span.Start.Line == 1 && Span.Start.Column == 1 && Span.Start.Index != 0) { // we don't have the line number calculated piLine = 0; return VSConstants.E_FAIL; } piLine = Span.Start.Line - 1; return VSConstants.S_OK; } int IVsTaskItem.NavigateTo() { try { if (Span.Start.Line == 1 && Span.Start.Column == 1 && Span.Start.Index != 0) { // we have just an absolute index, use that to naviagte PythonToolsPackage.NavigateTo(_serviceProvider, SourceFile, Guid.Empty, Span.Start.Index); } else { PythonToolsPackage.NavigateTo(_serviceProvider, SourceFile, Guid.Empty, Span.Start.Line - 1, Span.Start.Column - 1); } return VSConstants.S_OK; } catch (DirectoryNotFoundException) { // This may happen when the error was in a file that's located inside a .zip archive. // Let's walk the path and see if it is indeed the case. for (var path = SourceFile; PathUtils.IsValidPath(path); path = Path.GetDirectoryName(path)) { if (!File.Exists(path)) { continue; } var ext = Path.GetExtension(path); if (string.Equals(ext, ".zip", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".egg", StringComparison.OrdinalIgnoreCase)) { MessageBox.Show( "Opening source files contained in .zip archives is not supported", "Cannot open file", MessageBoxButtons.OK, MessageBoxIcon.Information ); return VSConstants.S_FALSE; } } // If it failed for some other reason, let caller handle it. throw; } } int IVsTaskItem.NavigateToHelp() { return VSConstants.E_NOTIMPL; } int IVsTaskItem.OnDeleteTask() { return VSConstants.E_NOTIMPL; } int IVsTaskItem.OnFilterTask(int fVisible) { return VSConstants.E_NOTIMPL; } int IVsTaskItem.SubcategoryIndex(out int pIndex) { pIndex = 0; return VSConstants.E_NOTIMPL; } int IVsTaskItem.get_Checked(out int pfChecked) { pfChecked = IsChecked ? 1 : 0; return VSConstants.S_OK; } int IVsTaskItem.get_Priority(VSTASKPRIORITY[] ptpPriority) { ptpPriority[0] = Priority; return VSConstants.S_OK; } int IVsTaskItem.get_Text(out string pbstrName) { pbstrName = Message; return VSConstants.S_OK; } int IVsTaskItem.put_Checked(int fChecked) { if (IsCheckedIsReadOnly) { return VSConstants.E_NOTIMPL; } IsChecked = (fChecked != 0); return VSConstants.S_OK; } int IVsTaskItem.put_Priority(VSTASKPRIORITY tpPriority) { if (PriorityIsReadOnly) { return VSConstants.E_NOTIMPL; } Priority = tpPriority; return VSConstants.S_OK; } int IVsTaskItem.put_Text(string bstrName) { if (MessageIsReadOnly) { return VSConstants.E_NOTIMPL; } Message = bstrName; return VSConstants.S_OK; } } sealed class ErrorTaskProvider : TaskProvider { internal ErrorTaskProvider(IServiceProvider serviceProvider, IVsTaskList taskList, IErrorProviderFactory errorProvider) : base(serviceProvider, taskList, errorProvider) { } public static object CreateService(IServiceProvider container, Type serviceType) { if (serviceType.IsEquivalentTo(typeof(ErrorTaskProvider))) { var errorList = container.GetService(typeof(SVsErrorList)) as IVsTaskList; var model = container.GetComponentModel(); var errorProvider = model != null ? model.GetService<IErrorProviderFactory>() : null; return new ErrorTaskProvider(container, errorList, errorProvider); } return null; } } sealed class CommentTaskProvider : TaskProvider, IVsTaskListEvents { private volatile Dictionary<string, VSTASKPRIORITY> _tokens; internal CommentTaskProvider(IServiceProvider serviceProvider, IVsTaskList taskList, IErrorProviderFactory errorProvider) : base(serviceProvider, taskList, errorProvider) { RefreshTokens(); } public static object CreateService(IServiceProvider container, Type serviceType) { if (serviceType.IsEquivalentTo(typeof(CommentTaskProvider))) { var errorList = container.GetService(typeof(SVsTaskList)) as IVsTaskList; var model = container.GetComponentModel(); var errorProvider = model != null ? model.GetService<IErrorProviderFactory>() : null; return new CommentTaskProvider(container, errorList, errorProvider); } return null; } public Dictionary<string, VSTASKPRIORITY> Tokens { get { return _tokens; } } public event EventHandler TokensChanged; public int OnCommentTaskInfoChanged() { RefreshTokens(); return VSConstants.S_OK; } // Retrieves token settings as defined by user in Tools -> Options -> Environment -> Task List. private void RefreshTokens() { var taskInfo = (IVsCommentTaskInfo)_serviceProvider.GetService(typeof(SVsTaskList)); if (taskInfo == null) { _tokens = new Dictionary<string, VSTASKPRIORITY>(); return; } IVsEnumCommentTaskTokens enumTokens; ErrorHandler.ThrowOnFailure(taskInfo.EnumTokens(out enumTokens)); var newTokens = new Dictionary<string, VSTASKPRIORITY>(); var token = new IVsCommentTaskToken[1]; uint fetched; string text; var priority = new VSTASKPRIORITY[1]; // DevDiv bug 1135485: EnumCommentTaskTokens.Next returns E_FAIL instead of S_FALSE while (enumTokens.Next(1, token, out fetched) == VSConstants.S_OK && fetched > 0) { ErrorHandler.ThrowOnFailure(token[0].Text(out text)); ErrorHandler.ThrowOnFailure(token[0].Priority(priority)); newTokens[text] = priority[0]; } _tokens = newTokens; var tokensChanged = TokensChanged; if (tokensChanged != null) { tokensChanged(this, EventArgs.Empty); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.SS.Util { using System; using System.Text; using System.Text.RegularExpressions; using NPOI.SS.Formula; using NPOI.SS.UserModel; using System.Globalization; public enum NameType:int { /// <summary> /// Allow accessing the Initial value. /// </summary> None = 0, Cell = 1, NamedRange = 2, Column = 3, Row = 4, BadCellOrNamedRange = -1 } /** * <p>Common conversion functions between Excel style A1, C27 style * cell references, and POI usermodel style row=0, column=0 * style references. Handles sheet-based and sheet-free references * as well, eg "Sheet1!A1" and "$B$72"</p> * * <p>Use <tt>CellReference</tt> when the concept of * relative/absolute does apply (such as a cell reference in a formula). * Use {@link CellAddress} when you want to refer to the location of a cell in a sheet * when the concept of relative/absolute does not apply (such as the anchor location * of a cell comment). * <tt>CellReference</tt>s have a concept of "sheet", while <tt>CellAddress</tt>es do not.</p> */ public class CellReference { /** The character ($) that signifies a row or column value is absolute instead of relative */ private const char ABSOLUTE_REFERENCE_MARKER = '$'; /** The character (!) that Separates sheet names from cell references */ private const char SHEET_NAME_DELIMITER = '!'; /** The character (') used to quote sheet names when they contain special characters */ private const char SPECIAL_NAME_DELIMITER = '\''; /** * Matches a run of one or more letters followed by a run of one or more digits. * Both the letter and number groups are optional. * The run of letters is group 1 and the run of digits is group 2. * Each group may optionally be prefixed with a single '$'. */ //private const string CELL_REF_PATTERN = @"^\$?([A-Za-z]+)\$?([0-9]+)"; //private static final Pattern CELL_REF_PATTERN = Pattern.compile("(\\$?[A-Z]+)?" + "(\\$?[0-9]+)?", Pattern.CASE_INSENSITIVE); private static Regex CELL_REF_PATTERN = new Regex("(\\$?[A-Z]+)?" + "(\\$?[0-9]+)?", RegexOptions.IgnoreCase | RegexOptions.Compiled| RegexOptions.CultureInvariant); /** * Matches references only where row and column are included. * Matches a run of one or more letters followed by a run of one or more digits. * If a reference does not match this pattern, it might match COLUMN_REF_PATTERN or ROW_REF_PATTERN * References may optionally include a single '$' before each group, but these are excluded from the Matcher.group(int). */ //private static final Pattern STRICTLY_CELL_REF_PATTERN = Pattern.compile("\\$?([A-Z]+)" + "\\$?([0-9]+)", Pattern.CASE_INSENSITIVE); private static Regex STRICTLY_CELL_REF_PATTERN = new Regex("^\\$?([A-Z]+)" + "\\$?([0-9]+)$", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant); /** * Matches a run of one or more letters. The run of letters is group 1. * References may optionally include a single '$' before the group, but these are excluded from the Matcher.group(int). */ private static Regex COLUMN_REF_PATTERN = new Regex(@"^\$?([A-Za-z]+)$", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant); /** * Matches a run of one or more letters. The run of numbers is group 1. * References may optionally include a single '$' before the group, but these are excluded from the Matcher.group(int). */ private static Regex ROW_REF_PATTERN = new Regex(@"^\$?([0-9]+)$"); /** * Named range names must start with a letter or underscore. Subsequent characters may include * digits or dot. (They can even end in dot). */ //private static final Pattern NAMED_RANGE_NAME_PATTERN = Pattern.compile("[_A-Z][_.A-Z0-9]*", Pattern.CASE_INSENSITIVE); private static Regex NAMED_RANGE_NAME_PATTERN = new Regex("^[_A-Za-z][_.A-Za-z0-9]*$", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant); //private static string BIFF8_LAST_COLUMN = "IV"; //private static int BIFF8_LAST_COLUMN_TEXT_LEN = BIFF8_LAST_COLUMN.Length; //private static string BIFF8_LAST_ROW = (0x10000).ToString(); //private static int BIFF8_LAST_ROW_TEXT_LEN = BIFF8_LAST_ROW.Length; // FIXME: _sheetName may be null, depending on the entry point. // Perhaps it would be better to declare _sheetName is never null, using an empty string to represent a 2D reference. private String _sheetName; private int _rowIndex; private int _colIndex; private bool _isRowAbs; private bool _isColAbs; /** * Create an cell ref from a string representation. Sheet names containing special characters should be * delimited and escaped as per normal syntax rules for formulas. */ public CellReference(String cellRef) { if (cellRef.EndsWith("#REF!", StringComparison.InvariantCulture)) { throw new ArgumentException("Cell reference invalid: " + cellRef); } CellRefPartsInner parts = SeparateRefParts(cellRef); _sheetName = parts.sheetName;//parts[0]; String colRef = parts.colRef;// parts[1]; //if (colRef.Length < 1) //{ // throw new ArgumentException("Invalid Formula cell reference: '" + cellRef + "'"); //} _isColAbs = (colRef.Length > 0) && colRef[0] == '$'; //_isColAbs = colRef[0] == '$'; if (_isColAbs) { colRef = colRef.Substring(1); } if (colRef.Length == 0) { _colIndex = -1; } else { _colIndex = ConvertColStringToIndex(colRef); } String rowRef = parts.rowRef;// parts[2]; //if (rowRef.Length < 1) //{ // throw new ArgumentException("Invalid Formula cell reference: '" + cellRef + "'"); //} //_isRowAbs = rowRef[0] == '$'; _isRowAbs = (rowRef.Length > 0) && rowRef[0] == '$'; if (_isRowAbs) { rowRef = rowRef.Substring(1); } if (rowRef.Length == 0) { _rowIndex = -1; } else { _rowIndex = int.Parse(rowRef, CultureInfo.InvariantCulture) - 1; // -1 to convert 1-based to zero-based } } public CellReference(ICell cell):this(cell.RowIndex, cell.ColumnIndex, false, false) { } public CellReference(int pRow, int pCol) : this(pRow, pCol, false, false) { } public CellReference(int pRow, short pCol) : this(pRow, pCol & 0xFFFF, false, false) { } public CellReference(int pRow, int pCol, bool pAbsRow, bool pAbsCol) : this(null, pRow, pCol, pAbsRow, pAbsCol) { } public CellReference(String pSheetName, int pRow, int pCol, bool pAbsRow, bool pAbsCol) { // TODO - "-1" is a special value being temporarily used for whole row and whole column area references. // so these Checks are currently N.Q.R. if (pRow < -1) { throw new ArgumentException("row index may not be negative, but had " + pRow); } if (pCol < -1) { throw new ArgumentException("column index may not be negative, but had " + pCol); } _sheetName = pSheetName; _rowIndex = pRow; _colIndex = pCol; _isRowAbs = pAbsRow; _isColAbs = pAbsCol; } public int Row { get { return _rowIndex; } } public short Col { get { return (short)_colIndex; } } public bool IsRowAbsolute { get { return _isRowAbs; } } public bool IsColAbsolute { get { return _isColAbs; } } /** * @return possibly <c>null</c> if this is a 2D reference. Special characters are not * escaped or delimited */ public String SheetName { get { return _sheetName; } } /** * takes in a column reference portion of a CellRef and converts it from * ALPHA-26 number format to 0-based base 10. * 'A' -> 0 * 'Z' -> 25 * 'AA' -> 26 * 'IV' -> 255 * @return zero based column index */ public static int ConvertColStringToIndex(String ref1) { int retval = 0; char[] refs = ref1.ToUpper().ToCharArray(); for (int k = 0; k < refs.Length; k++) { char thechar = refs[k]; if (thechar == ABSOLUTE_REFERENCE_MARKER) { if (k != 0) { throw new ArgumentException("Bad col ref format '" + ref1 + "'"); } continue; } // Character is uppercase letter, find relative value to A retval = (retval * 26) + (thechar - 'A' + 1); } return retval - 1; } public static bool IsPartAbsolute(String part) { return part[0] == ABSOLUTE_REFERENCE_MARKER; } public static NameType ClassifyCellReference(String str, SpreadsheetVersion ssVersion) { int len = str.Length; if (len < 1) { throw new ArgumentException("Empty string not allowed"); } char firstChar = str[0]; switch (firstChar) { case ABSOLUTE_REFERENCE_MARKER: case '.': case '_': break; default: if (!Char.IsLetter(firstChar) && !Char.IsDigit(firstChar)) { throw new ArgumentException("Invalid first char (" + firstChar + ") of cell reference or named range. Letter expected"); } break; } if (!Char.IsDigit(str[len - 1])) { // no digits at end of str return ValidateNamedRangeName(str, ssVersion); } Regex cellRefPatternMatcher = STRICTLY_CELL_REF_PATTERN; if (!cellRefPatternMatcher.IsMatch(str)) { return ValidateNamedRangeName(str, ssVersion); } MatchCollection matches = cellRefPatternMatcher.Matches(str); string lettersGroup = matches[0].Groups[1].Value; string digitsGroup = matches[0].Groups[2].Value; if (CellReferenceIsWithinRange(lettersGroup, digitsGroup, ssVersion)) { // valid cell reference return NameType.Cell; } // If str looks like a cell reference, but is out of (row/col) range, it is a valid // named range name // This behaviour is a little weird. For example, "IW123" is a valid named range name // because the column "IW" is beyond the maximum "IV". Note - this behaviour is version // dependent. In BIFF12, "IW123" is not a valid named range name, but in BIFF8 it is. if (str.IndexOf(ABSOLUTE_REFERENCE_MARKER) >= 0) { // Of course, named range names cannot have '$' return NameType.BadCellOrNamedRange; } return NameType.NamedRange; } private static NameType ValidateNamedRangeName(String str, SpreadsheetVersion ssVersion) { Regex colMatcher = COLUMN_REF_PATTERN; if (colMatcher.IsMatch(str)) { Group colStr = colMatcher.Matches(str)[0].Groups[1]; if (IsColumnWithinRange(colStr.Value, ssVersion)) { return NameType.Column; } } Regex rowMatcher = ROW_REF_PATTERN; if (rowMatcher.IsMatch(str)) { Group rowStr = rowMatcher.Matches(str)[0].Groups[1]; if (IsRowWithinRange(rowStr.Value, ssVersion)) { return NameType.Row; } } if (!NAMED_RANGE_NAME_PATTERN.IsMatch(str)) { return NameType.BadCellOrNamedRange; } return NameType.NamedRange; } /** * Takes in a 0-based base-10 column and returns a ALPHA-26 * representation. * eg column #3 -> D */ public static String ConvertNumToColString(int col) { // Excel counts column A as the 1st column, we // treat it as the 0th one int excelColNum = col + 1; StringBuilder colRef = new StringBuilder(2); int colRemain = excelColNum; while (colRemain > 0) { int thisPart = colRemain % 26; if (thisPart == 0) { thisPart = 26; } colRemain = (colRemain - thisPart) / 26; // The letter A is at 65 char colChar = (char)(thisPart + 64); colRef.Insert(0, colChar); } return colRef.ToString(); } internal class CellRefPartsInner { public String sheetName; public String rowRef; public String colRef; public CellRefPartsInner(String sheetName, String rowRef, String colRef) { this.sheetName = sheetName; this.rowRef = rowRef ?? ""; this.colRef = colRef ?? ""; } } /** * Separates the row from the columns and returns an array of three Strings. The first element * is the sheet name. Only the first element may be null. The second element in is the column * name still in ALPHA-26 number format. The third element is the row. */ private static CellRefPartsInner SeparateRefParts(String reference) { int plingPos = reference.LastIndexOf(SHEET_NAME_DELIMITER); String sheetName = ParseSheetName(reference, plingPos); int start = plingPos + 1; String cell = reference.Substring(plingPos + 1).ToUpper(CultureInfo.InvariantCulture); Match matcher = CELL_REF_PATTERN.Match(cell); if (!matcher.Success) throw new ArgumentException("Invalid CellReference: " + reference); String col = matcher.Groups[1].Value; String row = matcher.Groups[2].Value; CellRefPartsInner cellRefParts = new CellRefPartsInner(sheetName, row, col); return cellRefParts; } private static String ParseSheetName(String reference, int indexOfSheetNameDelimiter) { if (indexOfSheetNameDelimiter < 0) { return null; } bool IsQuoted = reference[0] == SPECIAL_NAME_DELIMITER; if (!IsQuoted) { // sheet names with spaces must be quoted if (reference.IndexOf(' ') == -1) { return reference.Substring(0, indexOfSheetNameDelimiter); } else { throw new ArgumentException("Sheet names containing spaces must be quoted: (" + reference + ")"); } } int lastQuotePos = indexOfSheetNameDelimiter - 1; if (reference[lastQuotePos] != SPECIAL_NAME_DELIMITER) { throw new ArgumentException("Mismatched quotes: (" + reference + ")"); } // TODO - refactor cell reference parsing logic to one place. // Current known incarnations: // FormulaParser.Name // CellReference.ParseSheetName() (here) // AreaReference.SeparateAreaRefs() // SheetNameFormatter.format() (inverse) StringBuilder sb = new StringBuilder(indexOfSheetNameDelimiter); for (int i = 1; i < lastQuotePos; i++) { // Note boundaries - skip outer quotes char ch = reference[i]; if (ch != SPECIAL_NAME_DELIMITER) { sb.Append(ch); continue; } if (i < lastQuotePos) { if (reference[i + 1] == SPECIAL_NAME_DELIMITER) { // two consecutive quotes is the escape sequence for a single one i++; // skip this and keep parsing the special name sb.Append(ch); continue; } } throw new ArgumentException("Bad sheet name quote escaping: (" + reference + ")"); } return sb.ToString(); } /** * Example return values: * <table border="0" cellpAdding="1" cellspacing="0" summary="Example return values"> * <tr><th align='left'>Result</th><th align='left'>Comment</th></tr> * <tr><td>A1</td><td>Cell reference without sheet</td></tr> * <tr><td>Sheet1!A1</td><td>Standard sheet name</td></tr> * <tr><td>'O''Brien''s Sales'!A1'</td><td>Sheet name with special characters</td></tr> * </table> * @return the text representation of this cell reference as it would appear in a formula. */ public String FormatAsString() { StringBuilder sb = new StringBuilder(32); if (_sheetName != null) { SheetNameFormatter.AppendFormat(sb, _sheetName); sb.Append(SHEET_NAME_DELIMITER); } AppendCellReference(sb); return sb.ToString(); } public override String ToString() { StringBuilder sb = new StringBuilder(64); sb.Append(this.GetType().Name).Append(" ["); sb.Append(FormatAsString()); sb.Append("]"); return sb.ToString(); } /** * Returns the three parts of the cell reference, the * Sheet name (or null if none supplied), the 1 based * row number, and the A based column letter. * This will not include any markers for absolute * references, so use {@link #formatAsString()} * to properly turn references into strings. */ public String[] CellRefParts { get { return new String[] { _sheetName, (_rowIndex+1).ToString(CultureInfo.InvariantCulture), ConvertNumToColString(_colIndex) }; } } /** * Appends cell reference with '$' markers for absolute values as required. * Sheet name is not included. */ /* package */ public void AppendCellReference(StringBuilder sb) { if (_colIndex != -1) { if (_isColAbs) { sb.Append(ABSOLUTE_REFERENCE_MARKER); } sb.Append(ConvertNumToColString(_colIndex)); } if (_rowIndex != -1) { if (_isRowAbs) { sb.Append(ABSOLUTE_REFERENCE_MARKER); } sb.Append(_rowIndex + 1); } } /** * Used to decide whether a name of the form "[A-Z]*[0-9]*" that appears in a formula can be * interpreted as a cell reference. Names of that form can be also used for sheets and/or * named ranges, and in those circumstances, the question of whether the potential cell * reference is valid (in range) becomes important. * <p/> * Note - that the maximum sheet size varies across Excel versions: * <p/> * <blockquote><table border="0" cellpadding="1" cellspacing="0" * summary="Notable cases."> * <tr><th>Version </th><th>File Format </th> * <th>Last Column </th><th>Last Row</th></tr> * <tr><td>97-2003</td><td>BIFF8</td><td>"IV" (2^8)</td><td>65536 (2^14)</td></tr> * <tr><td>2007</td><td>BIFF12</td><td>"XFD" (2^14)</td><td>1048576 (2^20)</td></tr> * </table></blockquote> * POI currently targets BIFF8 (Excel 97-2003), so the following behaviour can be observed for * this method: * <blockquote><table border="0" cellpadding="1" cellspacing="0" * summary="Notable cases."> * <tr><th>Input </th> * <th>Result </th></tr> * <tr><td>"A", "1"</td><td>true</td></tr> * <tr><td>"a", "111"</td><td>true</td></tr> * <tr><td>"A", "65536"</td><td>true</td></tr> * <tr><td>"A", "65537"</td><td>false</td></tr> * <tr><td>"iv", "1"</td><td>true</td></tr> * <tr><td>"IW", "1"</td><td>false</td></tr> * <tr><td>"AAA", "1"</td><td>false</td></tr> * <tr><td>"a", "111"</td><td>true</td></tr> * <tr><td>"Sheet", "1"</td><td>false</td></tr> * </table></blockquote> * * @param colStr a string of only letter characters * @param rowStr a string of only digit characters * @return <c>true</c> if the row and col parameters are within range of a BIFF8 spreadsheet. */ public static bool CellReferenceIsWithinRange(String colStr, String rowStr, SpreadsheetVersion ssVersion) { if (!IsColumnWithinRange(colStr, ssVersion)) { return false; } return IsRowWithinRange(rowStr, ssVersion); } /** * @deprecated 3.15 beta 2. Use {@link #isColumnWithinRange}. */ [Obsolete("deprecated 3.15 beta 2. Use {@link #isColumnWithinRange}.")] public static bool IsColumnWithnRange(String colStr, SpreadsheetVersion ssVersion) { return IsColumnWithinRange(colStr, ssVersion); } public static bool IsRowWithinRange(String rowStr, SpreadsheetVersion ssVersion) { int rowNum = int.Parse(rowStr) - 1; return 0 <= rowNum && rowNum <= ssVersion.LastRowIndex; } [Obsolete("deprecated 3.15 beta 2. Use {@link #isRowWithinRange}")] public static bool isRowWithnRange(String rowStr, SpreadsheetVersion ssVersion) { return IsRowWithinRange(rowStr, ssVersion); } public static bool IsColumnWithinRange(String colStr, SpreadsheetVersion ssVersion) { String lastCol = ssVersion.LastColumnName; int lastColLength = lastCol.Length; int numberOfLetters = colStr.Length; if (numberOfLetters > lastColLength) { // "Sheet1" case etc return false; // that was easy } if (numberOfLetters == lastColLength) { //if (colStr.ToUpper().CompareTo(lastCol) > 0) if (string.Compare(colStr.ToUpper(), lastCol, StringComparison.Ordinal) > 0) { return false; } } else { // apparent column name has less chars than max // no need to check range } return true; } public override bool Equals(Object o) { if (object.ReferenceEquals(this, o)) return true; if (!(o is CellReference)) { return false; } CellReference cr = (CellReference)o; return _rowIndex == cr._rowIndex && _colIndex == cr._colIndex && _isRowAbs == cr._isRowAbs && _isColAbs == cr._isColAbs && ((_sheetName == null) ? (cr._sheetName == null) : _sheetName.Equals(cr._sheetName)); } public override int GetHashCode () { int result = 17; result = 31 * result + _rowIndex; result = 31 * result + _colIndex; result = 31 * result + (_isRowAbs ? 1 : 0); result = 31 * result + (_isColAbs ? 1 : 0); result = 31 * result + (_sheetName == null ? 0 : _sheetName.GetHashCode()); return result; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type float with 4 columns and 2 rows. /// </summary> [Serializable] [DataContract(Namespace = "mat")] [StructLayout(LayoutKind.Sequential)] public struct mat4x2 : IReadOnlyList<float>, IEquatable<mat4x2> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> [DataMember] public float m00; /// <summary> /// Column 0, Rows 1 /// </summary> [DataMember] public float m01; /// <summary> /// Column 1, Rows 0 /// </summary> [DataMember] public float m10; /// <summary> /// Column 1, Rows 1 /// </summary> [DataMember] public float m11; /// <summary> /// Column 2, Rows 0 /// </summary> [DataMember] public float m20; /// <summary> /// Column 2, Rows 1 /// </summary> [DataMember] public float m21; /// <summary> /// Column 3, Rows 0 /// </summary> [DataMember] public float m30; /// <summary> /// Column 3, Rows 1 /// </summary> [DataMember] public float m31; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public mat4x2(float m00, float m01, float m10, float m11, float m20, float m21, float m30, float m31) { this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; this.m20 = m20; this.m21 = m21; this.m30 = m30; this.m31 = m31; } /// <summary> /// Constructs this matrix from a mat2. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(mat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0f; this.m21 = 0f; this.m30 = 0f; this.m31 = 0f; } /// <summary> /// Constructs this matrix from a mat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(mat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0f; this.m31 = 0f; } /// <summary> /// Constructs this matrix from a mat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(mat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a mat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(mat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0f; this.m21 = 0f; this.m30 = 0f; this.m31 = 0f; } /// <summary> /// Constructs this matrix from a mat3. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(mat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0f; this.m31 = 0f; } /// <summary> /// Constructs this matrix from a mat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(mat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a mat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(mat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0f; this.m21 = 0f; this.m30 = 0f; this.m31 = 0f; } /// <summary> /// Constructs this matrix from a mat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(mat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0f; this.m31 = 0f; } /// <summary> /// Constructs this matrix from a mat4. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(mat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(vec2 c0, vec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = 0f; this.m21 = 0f; this.m30 = 0f; this.m31 = 0f; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(vec2 c0, vec2 c1, vec2 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = c2.x; this.m21 = c2.y; this.m30 = 0f; this.m31 = 0f; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public mat4x2(vec2 c0, vec2 c1, vec2 c2, vec2 c3) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = c2.x; this.m21 = c2.y; this.m30 = c3.x; this.m31 = c3.y; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public float[,] Values => new[,] { { m00, m01 }, { m10, m11 }, { m20, m21 }, { m30, m31 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public float[] Values1D => new[] { m00, m01, m10, m11, m20, m21, m30, m31 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public vec2 Column0 { get { return new vec2(m00, m01); } set { m00 = value.x; m01 = value.y; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public vec2 Column1 { get { return new vec2(m10, m11); } set { m10 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the column nr 2 /// </summary> public vec2 Column2 { get { return new vec2(m20, m21); } set { m20 = value.x; m21 = value.y; } } /// <summary> /// Gets or sets the column nr 3 /// </summary> public vec2 Column3 { get { return new vec2(m30, m31); } set { m30 = value.x; m31 = value.y; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public vec4 Row0 { get { return new vec4(m00, m10, m20, m30); } set { m00 = value.x; m10 = value.y; m20 = value.z; m30 = value.w; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public vec4 Row1 { get { return new vec4(m01, m11, m21, m31); } set { m01 = value.x; m11 = value.y; m21 = value.z; m31 = value.w; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static mat4x2 Zero { get; } = new mat4x2(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f); /// <summary> /// Predefined all-ones matrix /// </summary> public static mat4x2 Ones { get; } = new mat4x2(1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f); /// <summary> /// Predefined identity matrix /// </summary> public static mat4x2 Identity { get; } = new mat4x2(1f, 0f, 0f, 1f, 0f, 0f, 0f, 0f); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static mat4x2 AllMaxValue { get; } = new mat4x2(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static mat4x2 DiagonalMaxValue { get; } = new mat4x2(float.MaxValue, 0f, 0f, float.MaxValue, 0f, 0f, 0f, 0f); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static mat4x2 AllMinValue { get; } = new mat4x2(float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static mat4x2 DiagonalMinValue { get; } = new mat4x2(float.MinValue, 0f, 0f, float.MinValue, 0f, 0f, 0f, 0f); /// <summary> /// Predefined all-Epsilon matrix /// </summary> public static mat4x2 AllEpsilon { get; } = new mat4x2(float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon); /// <summary> /// Predefined diagonal-Epsilon matrix /// </summary> public static mat4x2 DiagonalEpsilon { get; } = new mat4x2(float.Epsilon, 0f, 0f, float.Epsilon, 0f, 0f, 0f, 0f); /// <summary> /// Predefined all-NaN matrix /// </summary> public static mat4x2 AllNaN { get; } = new mat4x2(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN); /// <summary> /// Predefined diagonal-NaN matrix /// </summary> public static mat4x2 DiagonalNaN { get; } = new mat4x2(float.NaN, 0f, 0f, float.NaN, 0f, 0f, 0f, 0f); /// <summary> /// Predefined all-NegativeInfinity matrix /// </summary> public static mat4x2 AllNegativeInfinity { get; } = new mat4x2(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); /// <summary> /// Predefined diagonal-NegativeInfinity matrix /// </summary> public static mat4x2 DiagonalNegativeInfinity { get; } = new mat4x2(float.NegativeInfinity, 0f, 0f, float.NegativeInfinity, 0f, 0f, 0f, 0f); /// <summary> /// Predefined all-PositiveInfinity matrix /// </summary> public static mat4x2 AllPositiveInfinity { get; } = new mat4x2(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); /// <summary> /// Predefined diagonal-PositiveInfinity matrix /// </summary> public static mat4x2 DiagonalPositiveInfinity { get; } = new mat4x2(float.PositiveInfinity, 0f, 0f, float.PositiveInfinity, 0f, 0f, 0f, 0f); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<float> GetEnumerator() { yield return m00; yield return m01; yield return m10; yield return m11; yield return m20; yield return m21; yield return m30; yield return m31; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (4 x 2 = 8). /// </summary> public int Count => 8; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public float this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m10; case 3: return m11; case 4: return m20; case 5: return m21; case 6: return m30; case 7: return m31; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m10 = value; break; case 3: this.m11 = value; break; case 4: this.m20 = value; break; case 5: this.m21 = value; break; case 6: this.m30 = value; break; case 7: this.m31 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public float this[int col, int row] { get { return this[col * 2 + row]; } set { this[col * 2 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(mat4x2 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))) && ((m20.Equals(rhs.m20) && m21.Equals(rhs.m21)) && (m30.Equals(rhs.m30) && m31.Equals(rhs.m31)))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is mat4x2 && Equals((mat4x2) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(mat4x2 lhs, mat4x2 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(mat4x2 lhs, mat4x2 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode()) * 397) ^ m30.GetHashCode()) * 397) ^ m31.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public mat2x4 Transposed => new mat2x4(m00, m10, m20, m30, m01, m11, m21, m31); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public float MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m10), m11), m20), m21), m30), m31); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public float MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m10), m11), m20), m21), m30), m31); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public float LengthSqr => (((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31))); /// <summary> /// Returns the sum of all fields. /// </summary> public float Sum => (((m00 + m01) + (m10 + m11)) + ((m20 + m21) + (m30 + m31))); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public float Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m10) + Math.Abs(m11))) + ((Math.Abs(m20) + Math.Abs(m21)) + (Math.Abs(m30) + Math.Abs(m31)))); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public float NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m20)), Math.Abs(m21)), Math.Abs(m30)), Math.Abs(m31)); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))) + ((Math.Pow((double)Math.Abs(m20), p) + Math.Pow((double)Math.Abs(m21), p)) + (Math.Pow((double)Math.Abs(m30), p) + Math.Pow((double)Math.Abs(m31), p)))), 1 / p); /// <summary> /// Executes a matrix-matrix-multiplication mat4x2 * mat2x4 -> mat2. /// </summary> public static mat2 operator*(mat4x2 lhs, mat2x4 rhs) => new mat2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13))); /// <summary> /// Executes a matrix-matrix-multiplication mat4x2 * mat3x4 -> mat3x2. /// </summary> public static mat3x2 operator*(mat4x2 lhs, mat3x4 rhs) => new mat3x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13)), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + (lhs.m20 * rhs.m22 + lhs.m30 * rhs.m23)), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + (lhs.m21 * rhs.m22 + lhs.m31 * rhs.m23))); /// <summary> /// Executes a matrix-matrix-multiplication mat4x2 * mat4 -> mat4x2. /// </summary> public static mat4x2 operator*(mat4x2 lhs, mat4 rhs) => new mat4x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13)), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + (lhs.m20 * rhs.m22 + lhs.m30 * rhs.m23)), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + (lhs.m21 * rhs.m22 + lhs.m31 * rhs.m23)), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + (lhs.m20 * rhs.m32 + lhs.m30 * rhs.m33)), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + (lhs.m21 * rhs.m32 + lhs.m31 * rhs.m33))); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static vec2 operator*(mat4x2 m, vec4 v) => new vec2(((m.m00 * v.x + m.m10 * v.y) + (m.m20 * v.z + m.m30 * v.w)), ((m.m01 * v.x + m.m11 * v.y) + (m.m21 * v.z + m.m31 * v.w))); /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static mat4x2 CompMul(mat4x2 A, mat4x2 B) => new mat4x2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11, A.m20 * B.m20, A.m21 * B.m21, A.m30 * B.m30, A.m31 * B.m31); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static mat4x2 CompDiv(mat4x2 A, mat4x2 B) => new mat4x2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11, A.m20 / B.m20, A.m21 / B.m21, A.m30 / B.m30, A.m31 / B.m31); /// <summary> /// Executes a component-wise + (add). /// </summary> public static mat4x2 CompAdd(mat4x2 A, mat4x2 B) => new mat4x2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11, A.m20 + B.m20, A.m21 + B.m21, A.m30 + B.m30, A.m31 + B.m31); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static mat4x2 CompSub(mat4x2 A, mat4x2 B) => new mat4x2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11, A.m20 - B.m20, A.m21 - B.m21, A.m30 - B.m30, A.m31 - B.m31); /// <summary> /// Executes a component-wise + (add). /// </summary> public static mat4x2 operator+(mat4x2 lhs, mat4x2 rhs) => new mat4x2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21, lhs.m30 + rhs.m30, lhs.m31 + rhs.m31); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static mat4x2 operator+(mat4x2 lhs, float rhs) => new mat4x2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m20 + rhs, lhs.m21 + rhs, lhs.m30 + rhs, lhs.m31 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static mat4x2 operator+(float lhs, mat4x2 rhs) => new mat4x2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m20, lhs + rhs.m21, lhs + rhs.m30, lhs + rhs.m31); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static mat4x2 operator-(mat4x2 lhs, mat4x2 rhs) => new mat4x2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21, lhs.m30 - rhs.m30, lhs.m31 - rhs.m31); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static mat4x2 operator-(mat4x2 lhs, float rhs) => new mat4x2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m20 - rhs, lhs.m21 - rhs, lhs.m30 - rhs, lhs.m31 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static mat4x2 operator-(float lhs, mat4x2 rhs) => new mat4x2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m20, lhs - rhs.m21, lhs - rhs.m30, lhs - rhs.m31); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static mat4x2 operator/(mat4x2 lhs, float rhs) => new mat4x2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m20 / rhs, lhs.m21 / rhs, lhs.m30 / rhs, lhs.m31 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static mat4x2 operator/(float lhs, mat4x2 rhs) => new mat4x2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m20, lhs / rhs.m21, lhs / rhs.m30, lhs / rhs.m31); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static mat4x2 operator*(mat4x2 lhs, float rhs) => new mat4x2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m20 * rhs, lhs.m21 * rhs, lhs.m30 * rhs, lhs.m31 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static mat4x2 operator*(float lhs, mat4x2 rhs) => new mat4x2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m20, lhs * rhs.m21, lhs * rhs.m30, lhs * rhs.m31); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat4x2 operator<(mat4x2 lhs, mat4x2 rhs) => new bmat4x2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m20 < rhs.m20, lhs.m21 < rhs.m21, lhs.m30 < rhs.m30, lhs.m31 < rhs.m31); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat4x2 operator<(mat4x2 lhs, float rhs) => new bmat4x2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m20 < rhs, lhs.m21 < rhs, lhs.m30 < rhs, lhs.m31 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat4x2 operator<(float lhs, mat4x2 rhs) => new bmat4x2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m20, lhs < rhs.m21, lhs < rhs.m30, lhs < rhs.m31); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat4x2 operator<=(mat4x2 lhs, mat4x2 rhs) => new bmat4x2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m20 <= rhs.m20, lhs.m21 <= rhs.m21, lhs.m30 <= rhs.m30, lhs.m31 <= rhs.m31); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator<=(mat4x2 lhs, float rhs) => new bmat4x2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m20 <= rhs, lhs.m21 <= rhs, lhs.m30 <= rhs, lhs.m31 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator<=(float lhs, mat4x2 rhs) => new bmat4x2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m20, lhs <= rhs.m21, lhs <= rhs.m30, lhs <= rhs.m31); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat4x2 operator>(mat4x2 lhs, mat4x2 rhs) => new bmat4x2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m20 > rhs.m20, lhs.m21 > rhs.m21, lhs.m30 > rhs.m30, lhs.m31 > rhs.m31); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat4x2 operator>(mat4x2 lhs, float rhs) => new bmat4x2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m20 > rhs, lhs.m21 > rhs, lhs.m30 > rhs, lhs.m31 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat4x2 operator>(float lhs, mat4x2 rhs) => new bmat4x2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m20, lhs > rhs.m21, lhs > rhs.m30, lhs > rhs.m31); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat4x2 operator>=(mat4x2 lhs, mat4x2 rhs) => new bmat4x2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m20 >= rhs.m20, lhs.m21 >= rhs.m21, lhs.m30 >= rhs.m30, lhs.m31 >= rhs.m31); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator>=(mat4x2 lhs, float rhs) => new bmat4x2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m20 >= rhs, lhs.m21 >= rhs, lhs.m30 >= rhs, lhs.m31 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator>=(float lhs, mat4x2 rhs) => new bmat4x2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m20, lhs >= rhs.m21, lhs >= rhs.m30, lhs >= rhs.m31); } }
using System; using System.Collections.Generic; namespace Lucene.Net.Analysis { using System.IO; using CharacterRunAutomaton = Lucene.Net.Util.Automaton.CharacterRunAutomaton; /* * 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 LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /// <summary> /// Analyzer for testing /// <p> /// this analyzer is a replacement for Whitespace/Simple/KeywordAnalyzers /// for unit tests. If you are testing a custom component such as a queryparser /// or analyzer-wrapper that consumes analysis streams, its a great idea to test /// it with this analyzer instead. MockAnalyzer has the following behavior: /// <ul> /// <li>By default, the assertions in <seealso cref="MockTokenizer"/> are turned on for extra /// checks that the consumer is consuming properly. These checks can be disabled /// with <seealso cref="#setEnableChecks(boolean)"/>. /// <li>Payload data is randomly injected into the stream for more thorough testing /// of payloads. /// </ul> </summary> /// <seealso cref= MockTokenizer </seealso> public sealed class MockAnalyzer : Analyzer { private readonly CharacterRunAutomaton RunAutomaton; private readonly bool LowerCase; private readonly CharacterRunAutomaton Filter; private int PositionIncrementGap_Renamed; private int? OffsetGap_Renamed; private readonly Random Random; private IDictionary<string, int?> PreviousMappings = new Dictionary<string, int?>(); private bool EnableChecks_Renamed = true; private int MaxTokenLength_Renamed = MockTokenizer.DEFAULT_MAX_TOKEN_LENGTH; /// <summary> /// Creates a new MockAnalyzer. /// </summary> /// <param name="random"> Random for payloads behavior </param> /// <param name="runAutomaton"> DFA describing how tokenization should happen (e.g. [a-zA-Z]+) </param> /// <param name="lowerCase"> true if the tokenizer should lowercase terms </param> /// <param name="filter"> DFA describing how terms should be filtered (set of stopwords, etc) </param> public MockAnalyzer(Random random, CharacterRunAutomaton runAutomaton, bool lowerCase, CharacterRunAutomaton filter) : base(PER_FIELD_REUSE_STRATEGY) { // TODO: this should be solved in a different way; Random should not be shared (!). this.Random = new Random(random.Next()); this.RunAutomaton = runAutomaton; this.LowerCase = lowerCase; this.Filter = filter; } /// <summary> /// Calls {@link #MockAnalyzer(Random, CharacterRunAutomaton, boolean, CharacterRunAutomaton) /// MockAnalyzer(random, runAutomaton, lowerCase, MockTokenFilter.EMPTY_STOPSET, false}). /// </summary> public MockAnalyzer(Random random, CharacterRunAutomaton runAutomaton, bool lowerCase) : this(random, runAutomaton, lowerCase, MockTokenFilter.EMPTY_STOPSET) { } /// <summary> /// Create a Whitespace-lowercasing analyzer with no stopwords removal. /// <p> /// Calls {@link #MockAnalyzer(Random, CharacterRunAutomaton, boolean, CharacterRunAutomaton) /// MockAnalyzer(random, MockTokenizer.WHITESPACE, true, MockTokenFilter.EMPTY_STOPSET, false}). /// </summary> public MockAnalyzer(Random random) : this(random, MockTokenizer.WHITESPACE, true) { } public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { MockTokenizer tokenizer = new MockTokenizer(reader, RunAutomaton, LowerCase, MaxTokenLength_Renamed); tokenizer.EnableChecks = EnableChecks_Renamed; MockTokenFilter filt = new MockTokenFilter(tokenizer, Filter); return new TokenStreamComponents(tokenizer, MaybePayload(filt, fieldName)); } private TokenFilter MaybePayload(TokenFilter stream, string fieldName) { lock (this) { int? val; PreviousMappings.TryGetValue(fieldName, out val); if (val == null) { val = -1; // no payloads if (LuceneTestCase.Rarely(Random)) { switch (Random.Next(3)) { case 0: // no payloads val = -1; break; case 1: // variable length payload val = int.MaxValue; break; case 2: // fixed length payload val = Random.Next(12); break; } } if (LuceneTestCase.VERBOSE) { if (val == int.MaxValue) { Console.WriteLine("MockAnalyzer: field=" + fieldName + " gets variable length payloads"); } else if (val != -1) { Console.WriteLine("MockAnalyzer: field=" + fieldName + " gets fixed length=" + val + " payloads"); } } PreviousMappings[fieldName] = val; // save it so we are consistent for this field } if (val == -1) { return stream; } else if (val == int.MaxValue) { return new MockVariableLengthPayloadFilter(Random, stream); } else { return new MockFixedLengthPayloadFilter(Random, stream, (int)val); } } } public int PositionIncrementGap { set { this.PositionIncrementGap_Renamed = value; } } public override int GetPositionIncrementGap(string fieldName) { return PositionIncrementGap_Renamed; } /// <summary> /// Set a new offset gap which will then be added to the offset when several fields with the same name are indexed </summary> /// <param name="offsetGap"> The offset gap that should be used. </param> public int OffsetGap { set { this.OffsetGap_Renamed = value; } } /// <summary> /// Get the offset gap between tokens in fields if several fields with the same name were added. </summary> /// <param name="fieldName"> Currently not used, the same offset gap is returned for each field. </param> public override int GetOffsetGap(string fieldName) { return OffsetGap_Renamed == null ? base.GetOffsetGap(fieldName) : OffsetGap_Renamed.Value; } /// <summary> /// Toggle consumer workflow checking: if your test consumes tokenstreams normally you /// should leave this enabled. /// </summary> public bool EnableChecks { set { this.EnableChecks_Renamed = value; } } /// <summary> /// Toggle maxTokenLength for MockTokenizer /// </summary> public int MaxTokenLength { set { this.MaxTokenLength_Renamed = value; } } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // 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 Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Data; using System.Text; using System.Drawing.Imaging; using System.Drawing.Printing; using System.Collections.Generic; using System.Windows.Forms; using Microsoft.Reporting.WinForms; namespace CallButler.Manager.Utils { public class ReportPrinter { private int currentPageIndex; private List<Stream> streams; private IWin32Window parent; private LocalReport report; public delegate void PrintPageSelectionEventHandler(object source, PrintPageEventArgs e); public event PrintPageSelectionEventHandler OnPrintPageSelectionEvent; public ReportPrinter(string dataSourceName, object dataSource, string embeddedResource, IWin32Window parent) { this.parent = parent; Report = new LocalReport(); ReportDataSource r = new ReportDataSource(); r.Name = dataSourceName; r.Value = dataSource; report.DataSources.Add(r); report.ReportEmbeddedResource = embeddedResource; CurrentPageIndex = 0; Export(report); } public ReportPrinter(LocalReport report) { Report = report; CurrentPageIndex = 0; Export(report); } private LocalReport Report { get { return report; } set { report = value; } } public object DataSource { get { if (Report.DataSources.Count > 0) { return Report.DataSources[0]; } else { return null; } } set { if (Report.DataSources.Count > 0) { Report.DataSources[0].Value = value; } Export(Report); } } private void PrintPage(object sender, PrintPageEventArgs e) { if (e.PageSettings.PrinterSettings.PrintRange == PrintRange.Selection) { PrintPageSelectionEventHandler eh = OnPrintPageSelectionEvent; if (eh != null) { OnPrintPageSelectionEvent(this, e); } } else { FinalizePrint(e); } } private int CurrentPageIndex { get { return currentPageIndex; } set { currentPageIndex = value; } } private List<Stream> Streams { get { if (streams == null) { streams = new List<Stream>(); } return streams; } set { streams = value; } } public void FinalizePrint(PrintPageEventArgs e) { Metafile pageImage = new Metafile(Streams[CurrentPageIndex]); e.Graphics.DrawImage(pageImage, e.PageBounds); CurrentPageIndex++; e.HasMorePages = (CurrentPageIndex < Streams.Count); } // Routine to provide to the report renderer, in order to // save an image for each page of the report. private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) { Stream stream = new MemoryStream(); Streams.Add(stream); return stream; } // Export the given report as an EMF (Enhanced Metafile) file. private void Export(LocalReport report) { StringBuilder deviceInfo = new StringBuilder(); deviceInfo.Append("<DeviceInfo>"); deviceInfo.Append(" <OutputFormat>EMF</OutputFormat>"); deviceInfo.Append(" <PageWidth>8.5in</PageWidth>"); deviceInfo.Append(" <PageHeight>11in</PageHeight>"); deviceInfo.Append(" <MarginTop>0.25in</MarginTop>"); deviceInfo.Append(" <MarginLeft>0.25in</MarginLeft>"); deviceInfo.Append(" <MarginRight>0.25in</MarginRight>"); deviceInfo.Append(" <MarginBottom>0.25in</MarginBottom>"); deviceInfo.Append("</DeviceInfo>"); string di = deviceInfo.ToString(); Warning[] warnings; Streams = new List<Stream>(); report.Render("Image", di, CreateStream, out warnings); foreach (Stream stream in Streams) { stream.Position = 0; } } public void Print() { PrintDocument printDocument = new PrintDocument(); PrintDialog dlg = new PrintDialog(); dlg.AllowCurrentPage = false; dlg.AllowPrintToFile = false; dlg.AllowSelection = true; dlg.AllowSomePages = false; dlg.PrintToFile = false; dlg.ShowHelp = false; dlg.ShowNetwork = false; if (parent != null) { if (dlg.ShowDialog(parent) != DialogResult.OK) { return; } } else { if (dlg.ShowDialog() != DialogResult.OK) { return; } } printDocument.PrinterSettings = dlg.PrinterSettings; printDocument.DefaultPageSettings = dlg.PrinterSettings.DefaultPageSettings; printDocument.PrintPage += new PrintPageEventHandler(PrintPage); try { printDocument.Print(); } catch (Exception e) { MessageBox.Show(CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.ReportPrinter_UnableToPrint) + e.Message, CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.ReportPrinter_PrintError), MessageBoxButtons.OK, MessageBoxIcon.Warning); } } public void Dispose() { if (streams != null) { foreach (Stream stream in Streams) { try { stream.Close(); } catch { } } streams = null; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Docker.DotNet.Models; using Newtonsoft.Json; using Xunit; using Xunit.Abstractions; namespace Docker.DotNet.Tests { [Collection("Test collection")] public class IContainerOperationsTests { private readonly CancellationTokenSource _cts; private readonly DockerClient _dockerClient; private readonly DockerClientConfiguration _dockerClientConfiguration; private readonly string _imageId; private readonly Tests.TestOutput _output; public IContainerOperationsTests(TestFixture testFixture, ITestOutputHelper outputHelper) { // Do not wait forever in case it gets stuck _cts = CancellationTokenSource.CreateLinkedTokenSource(testFixture.cts.Token); _cts.CancelAfter(TimeSpan.FromMinutes(5)); _cts.Token.Register(() => throw new TimeoutException("IContainerOperationsTest timeout")); _dockerClient = testFixture.dockerClient; _dockerClientConfiguration = testFixture.dockerClientConfiguration; _output = new TestOutput(outputHelper); _imageId = testFixture.imageId; } [Fact] public async Task CreateContainerAsync_CreatesContainer() { var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters { Image = _imageId, Name = Guid.NewGuid().ToString(), }, _cts.Token ); Assert.NotNull(createContainerResponse); Assert.NotEmpty(createContainerResponse.ID); } // Timeout causing task to be cancelled [Theory] [InlineData(1)] [InlineData(5)] [InlineData(10)] public async Task CreateContainerAsync_TimeoutExpires_Fails(int millisecondsTimeout) { using var dockerClientWithTimeout = _dockerClientConfiguration.CreateClient(); dockerClientWithTimeout.DefaultTimeout = TimeSpan.FromMilliseconds(millisecondsTimeout); _output.WriteLine($"Time available for CreateContainer operation: {millisecondsTimeout} ms'"); var timer = new Stopwatch(); timer.Start(); var createContainerTask = dockerClientWithTimeout.Containers.CreateContainerAsync( new CreateContainerParameters { Image = _imageId, Name = Guid.NewGuid().ToString(), }, _cts.Token); _ = await Assert.ThrowsAsync<OperationCanceledException>(() => createContainerTask); timer.Stop(); _output.WriteLine($"CreateContainerOperation finished after {timer.ElapsedMilliseconds} ms"); Assert.True(createContainerTask.IsCanceled); Assert.True(createContainerTask.IsCompleted); } [Fact] public async Task GetContainerLogs_Follow_False_TaskIsCompleted() { using var containerLogsCts = new CancellationTokenSource(TimeSpan.FromSeconds(60)); var logList = new List<string>(); var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString(), Tty = false }, _cts.Token ); await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); containerLogsCts.CancelAfter(TimeSpan.FromSeconds(20)); var containerLogsTask = _dockerClient.Containers.GetContainerLogsAsync( createContainerResponse.ID, new ContainerLogsParameters { ShowStderr = true, ShowStdout = true, Timestamps = true, Follow = true }, containerLogsCts.Token, new Progress<string>((m) => { _output.WriteLine(m); logList.Add(m); }) ); await _dockerClient.Containers.StopContainerAsync( createContainerResponse.ID, new ContainerStopParameters(), _cts.Token ); await containerLogsTask; Assert.True(containerLogsTask.IsCompletedSuccessfully); } [Fact] public async Task GetContainerLogs_Tty_False_Follow_False_ReadsLogs() { using var containerLogsCts = new CancellationTokenSource(TimeSpan.FromSeconds(50)); var logList = new List<string>(); var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString(), Tty = false }, _cts.Token ); await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); await _dockerClient.Containers.GetContainerLogsAsync( createContainerResponse.ID, new ContainerLogsParameters { ShowStderr = true, ShowStdout = true, Timestamps = true, Follow = false }, containerLogsCts.Token, new Progress<string>((m) => { logList.Add(m); _output.WriteLine(m); }) ); await _dockerClient.Containers.StopContainerAsync( createContainerResponse.ID, new ContainerStopParameters(), _cts.Token ); _output.WriteLine($"Line count: {logList.Count}"); Assert.NotEmpty(logList); } [Fact] public async Task GetContainerLogs_Tty_False_Follow_True_Requires_Task_To_Be_Cancelled() { using var containerLogsCts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token); var logList = new List<string>(); var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString(), Tty = false }, _cts.Token ); await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); containerLogsCts.CancelAfter(TimeSpan.FromSeconds(5)); // Will be cancelled after CancellationTokenSource interval, would run forever otherwise await Assert.ThrowsAsync<TaskCanceledException>(() => _dockerClient.Containers.GetContainerLogsAsync( createContainerResponse.ID, new ContainerLogsParameters { ShowStderr = true, ShowStdout = true, Timestamps = true, Follow = true }, containerLogsCts.Token, new Progress<string>((m) => { _output.WriteLine(JsonConvert.SerializeObject(m)); logList.Add(m); }) )); } [Fact] public async Task GetContainerLogs_Tty_True_Follow_True_Requires_Task_To_Be_Cancelled() { using var containerLogsCts = new CancellationTokenSource(TimeSpan.FromSeconds(60)); var logList = new List<string>(); var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString(), Tty = true }, _cts.Token ); await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); containerLogsCts.CancelAfter(TimeSpan.FromSeconds(10)); var containerLogsTask = _dockerClient.Containers.GetContainerLogsAsync( createContainerResponse.ID, new ContainerLogsParameters { ShowStderr = true, ShowStdout = true, Timestamps = true, Follow = true }, containerLogsCts.Token, new Progress<string>((m) => { _output.WriteLine(m); logList.Add(m); }) ); await Assert.ThrowsAsync<TaskCanceledException>(() => containerLogsTask); } [Fact] public async Task GetContainerLogs_Tty_True_Follow_True_StreamLogs_TaskIsCancelled() { using var containerLogsCts = new CancellationTokenSource(TimeSpan.FromSeconds(60)); var logList = new List<string>(); var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString(), Tty = true }, _cts.Token ); await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); containerLogsCts.CancelAfter(TimeSpan.FromSeconds(5)); var containerLogsTask = _dockerClient.Containers.GetContainerLogsAsync( createContainerResponse.ID, new ContainerLogsParameters { ShowStderr = true, ShowStdout = true, Timestamps = true, Follow = true }, containerLogsCts.Token, new Progress<string>((m) => { _output.WriteLine(m); logList.Add(m); }) ); await Task.Delay(TimeSpan.FromSeconds(10)); await _dockerClient.Containers.StopContainerAsync( createContainerResponse.ID, new ContainerStopParameters { WaitBeforeKillSeconds = 0 }, _cts.Token ); await _dockerClient.Containers.RemoveContainerAsync( createContainerResponse.ID, new ContainerRemoveParameters { Force = true }, _cts.Token ); await Assert.ThrowsAsync<TaskCanceledException>(() => containerLogsTask); _output.WriteLine(JsonConvert.SerializeObject(new { AsyncState = containerLogsTask.AsyncState, CreationOptions = containerLogsTask.CreationOptions, Exception = containerLogsTask.Exception, Id = containerLogsTask.Id, IsCanceled = containerLogsTask.IsCanceled, IsCompleted = containerLogsTask.IsCompleted, IsCompletedSuccessfully = containerLogsTask.IsCompletedSuccessfully, Status = containerLogsTask.Status } )); _output.WriteLine($"Line count: {logList.Count}"); await Task.Delay(TimeSpan.FromSeconds(1)); Assert.NotEmpty(logList); } [Fact] public async Task GetContainerLogs_Tty_True_ReadsLogs() { using var containerLogsCts = new CancellationTokenSource(TimeSpan.FromSeconds(60)); var logList = new List<string>(); var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString(), Tty = true }, _cts.Token ); await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); containerLogsCts.CancelAfter(TimeSpan.FromSeconds(5)); var containerLogsTask = _dockerClient.Containers.GetContainerLogsAsync( createContainerResponse.ID, new ContainerLogsParameters { ShowStderr = true, ShowStdout = true, Timestamps = true, Follow = false }, containerLogsCts.Token, new Progress<string>((m) => { _output.WriteLine(m); logList.Add(m); }) ); await Task.Delay(TimeSpan.FromSeconds(10)); await _dockerClient.Containers.StopContainerAsync( createContainerResponse.ID, new ContainerStopParameters { WaitBeforeKillSeconds = 0 }, _cts.Token ); await _dockerClient.Containers.RemoveContainerAsync( createContainerResponse.ID, new ContainerRemoveParameters { Force = true }, _cts.Token ); await containerLogsTask; _output.WriteLine(JsonConvert.SerializeObject(new { AsyncState = containerLogsTask.AsyncState, CreationOptions = containerLogsTask.CreationOptions, Exception = containerLogsTask.Exception, Id = containerLogsTask.Id, IsCanceled = containerLogsTask.IsCanceled, IsCompleted = containerLogsTask.IsCompleted, IsCompletedSuccessfully = containerLogsTask.IsCompletedSuccessfully, Status = containerLogsTask.Status } )); _output.WriteLine($"Line count: {logList.Count}"); Assert.NotEmpty(logList); } [Fact] public async Task GetContainerStatsAsync_Tty_False_Stream_False_ReadsStats() { using var tcs = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token); var containerStatsList = new List<ContainerStatsResponse>(); var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters { Image = _imageId, Name = Guid.NewGuid().ToString(), Tty = false }, _cts.Token ); _ = await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); tcs.CancelAfter(TimeSpan.FromSeconds(10)); await _dockerClient.Containers.GetContainerStatsAsync( createContainerResponse.ID, new ContainerStatsParameters { Stream = false }, new Progress<ContainerStatsResponse>((m) => { _output.WriteLine(m.ID); containerStatsList.Add(m); }), tcs.Token ); await Task.Delay(TimeSpan.FromSeconds(10)); Assert.NotEmpty(containerStatsList); Assert.Single(containerStatsList); _output.WriteLine($"ConntainerStats count: {containerStatsList.Count}"); } [Fact] public async Task GetContainerStatsAsync_Tty_False_StreamStats() { using var tcs = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token); using (tcs.Token.Register(() => throw new TimeoutException("GetContainerStatsAsync_Tty_False_StreamStats"))) { _output.WriteLine($"Running test {MethodBase.GetCurrentMethod().Module}->{MethodBase.GetCurrentMethod().Name}"); var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString(), Tty = false }, _cts.Token ); _ = await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); List<ContainerStatsResponse> containerStatsList = new List<ContainerStatsResponse>(); using var linkedCts = new CancellationTokenSource(); linkedCts.CancelAfter(TimeSpan.FromSeconds(5)); try { await _dockerClient.Containers.GetContainerStatsAsync( createContainerResponse.ID, new ContainerStatsParameters { Stream = true }, new Progress<ContainerStatsResponse>((m) => { containerStatsList.Add(m); _output.WriteLine(JsonConvert.SerializeObject(m)); }), linkedCts.Token ); } catch (TaskCanceledException) { // this is expected to happen on task cancelaltion } _output.WriteLine($"Container stats count: {containerStatsList.Count}"); Assert.NotEmpty(containerStatsList); } } [Fact] public async Task GetContainerStatsAsync_Tty_True_Stream_False_ReadsStats() { using var tcs = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token); var containerStatsList = new List<ContainerStatsResponse>(); var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters { Image = _imageId, Name = Guid.NewGuid().ToString(), Tty = true }, _cts.Token ); _ = await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); tcs.CancelAfter(TimeSpan.FromSeconds(10)); await _dockerClient.Containers.GetContainerStatsAsync( createContainerResponse.ID, new ContainerStatsParameters { Stream = false }, new Progress<ContainerStatsResponse>((m) => { _output.WriteLine(m.ID); containerStatsList.Add(m); }), tcs.Token ); await Task.Delay(TimeSpan.FromSeconds(10)); Assert.NotEmpty(containerStatsList); Assert.Single(containerStatsList); _output.WriteLine($"ConntainerStats count: {containerStatsList.Count}"); } [Fact] public async Task GetContainerStatsAsync_Tty_True_StreamStats() { using var tcs = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token); using (tcs.Token.Register(() => throw new TimeoutException("GetContainerStatsAsync_Tty_True_StreamStats"))) { _output.WriteLine($"Running test GetContainerStatsAsync_Tty_True_StreamStats"); var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString(), Tty = true }, _cts.Token ); _ = await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); List<ContainerStatsResponse> containerStatsList = new List<ContainerStatsResponse>(); using var linkedTcs = CancellationTokenSource.CreateLinkedTokenSource(tcs.Token); linkedTcs.CancelAfter(TimeSpan.FromSeconds(5)); try { await _dockerClient.Containers.GetContainerStatsAsync( createContainerResponse.ID, new ContainerStatsParameters { Stream = true }, new Progress<ContainerStatsResponse>((m) => { containerStatsList.Add(m); _output.WriteLine(JsonConvert.SerializeObject(m)); }), linkedTcs.Token ); } catch (TaskCanceledException) { // this is expected to happen on task cancelaltion } await Task.Delay(TimeSpan.FromSeconds(1)); _output.WriteLine($"Container stats count: {containerStatsList.Count}"); Assert.NotEmpty(containerStatsList); } } [Fact] public async Task KillContainerAsync_ContainerRunning_Succeeds() { var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters { Image = _imageId }, _cts.Token); await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); var inspectRunningContainerResponse = await _dockerClient.Containers.InspectContainerAsync( createContainerResponse.ID, _cts.Token); await _dockerClient.Containers.KillContainerAsync( createContainerResponse.ID, new ContainerKillParameters(), _cts.Token); var inspectKilledContainerResponse = await _dockerClient.Containers.InspectContainerAsync( createContainerResponse.ID, _cts.Token); Assert.True(inspectRunningContainerResponse.State.Running); Assert.False(inspectKilledContainerResponse.State.Running); Assert.Equal("exited", inspectKilledContainerResponse.State.Status); _output.WriteLine("Killed"); _output.WriteLine(JsonConvert.SerializeObject(inspectKilledContainerResponse)); } [Fact] public async Task ListContainersAsync_ContainerExists_Succeeds() { await _dockerClient.Containers.CreateContainerAsync(new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString() }, _cts.Token); IList<ContainerListResponse> containerList = await _dockerClient.Containers.ListContainersAsync( new ContainersListParameters { Filters = new Dictionary<string, IDictionary<string, bool>> { ["ancestor"] = new Dictionary<string, bool> { [_imageId] = true } }, All = true }, _cts.Token ); Assert.NotNull(containerList); Assert.NotEmpty(containerList); } [Fact] public async Task ListProcessesAsync_RunningContainer_Succeeds() { var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString() }, _cts.Token ); await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); var containerProcessesResponse = await _dockerClient.Containers.ListProcessesAsync( createContainerResponse.ID, new ContainerListProcessesParameters(), _cts.Token ); _output.WriteLine($"Title '{containerProcessesResponse.Titles[0]}' - '{containerProcessesResponse.Titles[1]}' - '{containerProcessesResponse.Titles[2]}' - '{containerProcessesResponse.Titles[3]}'"); foreach (var processes in containerProcessesResponse.Processes) { _output.WriteLine($"Process '{processes[0]}' - ''{processes[1]}' - '{processes[2]}' - '{processes[3]}'"); } Assert.NotNull(containerProcessesResponse); Assert.NotEmpty(containerProcessesResponse.Processes); } [Fact] public async Task RemoveContainerAsync_ContainerExists_Succeedes() { var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString() }, _cts.Token ); ContainerInspectResponse inspectCreatedContainer = await _dockerClient.Containers.InspectContainerAsync( createContainerResponse.ID, _cts.Token ); await _dockerClient.Containers.RemoveContainerAsync( createContainerResponse.ID, new ContainerRemoveParameters { Force = true }, _cts.Token ); Task inspectRemovedContainerTask = _dockerClient.Containers.InspectContainerAsync( createContainerResponse.ID, _cts.Token ); Assert.NotNull(inspectCreatedContainer.State); await Assert.ThrowsAsync<DockerContainerNotFoundException>(() => inspectRemovedContainerTask); } [Fact] public async Task StartContainerAsync_ContainerExists_Succeeds() { var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters() { Image = _imageId, Name = Guid.NewGuid().ToString() }, _cts.Token ); var startContainerResult = await _dockerClient.Containers.StartContainerAsync( createContainerResponse.ID, new ContainerStartParameters(), _cts.Token ); Assert.True(startContainerResult); } [Fact] public async Task StartContainerAsync_ContainerNotExists_ThrowsException() { Task startContainerTask = _dockerClient.Containers.StartContainerAsync( Guid.NewGuid().ToString(), new ContainerStartParameters(), _cts.Token ); await Assert.ThrowsAsync<DockerContainerNotFoundException>(() => startContainerTask); } [Fact] public async Task WaitContainerAsync_TokenIsCancelled_OperationCancelledException() { var stopWatch = new Stopwatch(); using var waitContainerCts = new CancellationTokenSource(delay: TimeSpan.FromMinutes(5)); var createContainerResponse = await _dockerClient.Containers.CreateContainerAsync( new CreateContainerParameters { Image = _imageId, Name = Guid.NewGuid().ToString(), }, waitContainerCts.Token ); _output.WriteLine($"CreateContainerResponse: '{JsonConvert.SerializeObject(createContainerResponse)}'"); var startContainerResult = await _dockerClient.Containers.StartContainerAsync(createContainerResponse.ID, new ContainerStartParameters(), waitContainerCts.Token); _output.WriteLine("Starting timeout to cancel WaitContainer operation."); TimeSpan delay = TimeSpan.FromSeconds(5); waitContainerCts.CancelAfter(delay); stopWatch.Start(); // Will wait forever here if cancelation fails. var waitContainerTask = _dockerClient.Containers.WaitContainerAsync(createContainerResponse.ID, waitContainerCts.Token); var exception = await Assert.ThrowsAsync<TaskCanceledException>(() => waitContainerTask); stopWatch.Stop(); _output.WriteLine($"WaitContainerTask was cancelled after {stopWatch.ElapsedMilliseconds} ms"); _output.WriteLine($"WaitContainerAsync: {stopWatch.Elapsed} elapsed"); // Task should be cancelled when CancelAfter timespan expires TimeSpan tolerance = TimeSpan.FromMilliseconds(500); Assert.InRange(stopWatch.Elapsed, delay.Subtract(tolerance), delay.Add(tolerance)); Assert.True(waitContainerTask.IsCanceled); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; public static partial class RouteTablesOperationsExtensions { /// <summary> /// The Delete RouteTable operation deletes the specifed Route Table /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> public static void Delete(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName) { Task.Factory.StartNew(s => ((IRouteTablesOperations)s).DeleteAsync(resourceGroupName, routeTableName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete RouteTable operation deletes the specifed Route Table /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync( this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Delete RouteTable operation deletes the specifed Route Table /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> public static void BeginDelete(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName) { Task.Factory.StartNew(s => ((IRouteTablesOperations)s).BeginDeleteAsync(resourceGroupName, routeTableName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete RouteTable operation deletes the specifed Route Table /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync( this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Get RouteTables operation retrieves information about the specified /// route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='expand'> /// expand references resources. /// </param> public static RouteTable Get(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, string expand = default(string)) { return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).GetAsync(resourceGroupName, routeTableName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get RouteTables operation retrieves information about the specified /// route table. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='expand'> /// expand references resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteTable> GetAsync( this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<RouteTable> result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeTableName, expand, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Put RouteTable operation creates/updates a route tablein the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Route Table operation /// </param> public static RouteTable CreateOrUpdate(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters) { return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).CreateOrUpdateAsync(resourceGroupName, routeTableName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put RouteTable operation creates/updates a route tablein the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Route Table operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteTable> CreateOrUpdateAsync( this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<RouteTable> result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Put RouteTable operation creates/updates a route tablein the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Route Table operation /// </param> public static RouteTable BeginCreateOrUpdate(this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters) { return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, routeTableName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put RouteTable operation creates/updates a route tablein the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Route Table operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteTable> BeginCreateOrUpdateAsync( this IRouteTablesOperations operations, string resourceGroupName, string routeTableName, RouteTable parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<RouteTable> result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list RouteTables returns all route tables in a resource group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<RouteTable> List(this IRouteTablesOperations operations, string resourceGroupName) { return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list RouteTables returns all route tables in a resource group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteTable>> ListAsync( this IRouteTablesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<RouteTable>> result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list RouteTables returns all route tables in a subscription /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<RouteTable> ListAll(this IRouteTablesOperations operations) { return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list RouteTables returns all route tables in a subscription /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteTable>> ListAllAsync( this IRouteTablesOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<RouteTable>> result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list RouteTables returns all route tables in a resource group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<RouteTable> ListNext(this IRouteTablesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list RouteTables returns all route tables in a resource group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteTable>> ListNextAsync( this IRouteTablesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<RouteTable>> result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list RouteTables returns all route tables in a subscription /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<RouteTable> ListAllNext(this IRouteTablesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IRouteTablesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list RouteTables returns all route tables in a subscription /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteTable>> ListAllNextAsync( this IRouteTablesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<RouteTable>> result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
using IdentityModel; using IdentityServer4.Events; using IdentityServer4.Services; using IdentityServer4.Stores; using IdentityServer4.Test; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Threading.Tasks; namespace IdentityServer4.Quickstart.UI { [SecurityHeaders] [AllowAnonymous] public class ExternalController : Controller { private readonly TestUserStore _users; private readonly IIdentityServerInteractionService _interaction; private readonly IClientStore _clientStore; private readonly ILogger<ExternalController> _logger; private readonly IEventService _events; public ExternalController( IIdentityServerInteractionService interaction, IClientStore clientStore, IEventService events, ILogger<ExternalController> logger, TestUserStore users = null) { // if the TestUserStore is not in DI, then we'll just use the global users collection // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity) _users = users ?? new TestUserStore(TestUsers.Users); _interaction = interaction; _clientStore = clientStore; _logger = logger; _events = events; } /// <summary> /// initiate roundtrip to external authentication provider /// </summary> [HttpGet] public async Task<IActionResult> Challenge(string provider, string returnUrl) { if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/"; // validate returnUrl - either it is a valid OIDC URL or back to a local page if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false) { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } if (AccountOptions.WindowsAuthenticationSchemeName == provider) { // windows authentication needs special handling return await ProcessWindowsLoginAsync(returnUrl); } else { // start challenge and roundtrip the return URL and scheme var props = new AuthenticationProperties { RedirectUri = Url.Action(nameof(Callback)), Items = { { "returnUrl", returnUrl }, { "scheme", provider }, } }; return Challenge(props, provider); } } /// <summary> /// Post processing of external authentication /// </summary> [HttpGet] public async Task<IActionResult> Callback() { // read external identity from the temporary cookie var result = await HttpContext.AuthenticateAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); if (result?.Succeeded != true) { throw new Exception("External authentication error"); } if (_logger.IsEnabled(LogLevel.Debug)) { var externalClaims = result.Principal.Claims.Select(c => $"{c.Type}: {c.Value}"); _logger.LogDebug("External claims: {@claims}", externalClaims); } // lookup our user and external provider info var (user, provider, providerUserId, claims) = FindUserFromExternalProvider(result); if (user == null) { // this might be where you might initiate a custom workflow for user registration // in this sample we don't show how that would be done, as our sample implementation // simply auto-provisions new external user user = AutoProvisionUser(provider, providerUserId, claims); } // this allows us to collect any additonal claims or properties // for the specific prtotocols used and store them in the local auth cookie. // this is typically used to store data needed for signout from those protocols. var additionalLocalClaims = new List<Claim>(); var localSignInProps = new AuthenticationProperties(); ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps); // issue authentication cookie for user var isuser = new IdentityServerUser(user.SubjectId) { DisplayName = user.Username, IdentityProvider = provider, AdditionalClaims = additionalLocalClaims }; await HttpContext.SignInAsync(isuser, localSignInProps); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); // retrieve return URL var returnUrl = result.Properties.Items["returnUrl"] ?? "~/"; // check if external login is in the context of an OIDC request var context = await _interaction.GetAuthorizationContextAsync(returnUrl); await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.SubjectId, user.Username, true, context?.ClientId)); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return View("Redirect", new RedirectViewModel { RedirectUrl = returnUrl }); } } return Redirect(returnUrl); } private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl) { // see if windows auth has already been requested and succeeded var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName); if (result?.Principal is WindowsPrincipal wp) { // we will issue the external cookie and then redirect the // user back to the external callback, in essence, treating windows // auth the same as any other external authentication mechanism var props = new AuthenticationProperties() { RedirectUri = Url.Action("Callback"), Items = { { "returnUrl", returnUrl }, { "scheme", AccountOptions.WindowsAuthenticationSchemeName }, } }; var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName); id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name)); id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name)); // add the groups as claims -- be careful if the number of groups is too large if (AccountOptions.IncludeWindowsGroups) { var wi = wp.Identity as WindowsIdentity; var groups = wi.Groups.Translate(typeof(NTAccount)); var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value)); id.AddClaims(roles); } await HttpContext.SignInAsync( IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme, new ClaimsPrincipal(id), props); return Redirect(props.RedirectUri); } else { // trigger windows auth // since windows auth don't support the redirect uri, // this URL is re-triggered when we call challenge return Challenge(AccountOptions.WindowsAuthenticationSchemeName); } } private (TestUser user, string provider, string providerUserId, IEnumerable<Claim> claims) FindUserFromExternalProvider(AuthenticateResult result) { var externalUser = result.Principal; // try to determine the unique id of the external user (issued by the provider) // the most common claim type for that are the sub claim and the NameIdentifier // depending on the external provider, some other claim type might be used var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ?? externalUser.FindFirst(ClaimTypes.NameIdentifier) ?? throw new Exception("Unknown userid"); // remove the user id claim so we don't include it as an extra claim if/when we provision the user var claims = externalUser.Claims.ToList(); claims.Remove(userIdClaim); var provider = result.Properties.Items["scheme"]; var providerUserId = userIdClaim.Value; // find external user var user = _users.FindByExternalProvider(provider, providerUserId); return (user, provider, providerUserId, claims); } private TestUser AutoProvisionUser(string provider, string providerUserId, IEnumerable<Claim> claims) { var user = _users.AutoProvisionUser(provider, providerUserId, claims.ToList()); return user; } private void ProcessLoginCallbackForOidc(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { // if the external system sent a session id claim, copy it over // so we can use it for single sign-out var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId); if (sid != null) { localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value)); } // if the external provider issued an id_token, we'll keep it for signout var id_token = externalResult.Properties.GetTokenValue("id_token"); if (id_token != null) { localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } }); } } private void ProcessLoginCallbackForWsFed(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { } private void ProcessLoginCallbackForSaml2p(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { } } }
// UPSTREAM: https://raw.githubusercontent.com/xunit/assert.xunit/2.4.1/Sdk/ArgumentFormatter.cs #pragma warning disable CA1305 // Specify IFormatProvider #pragma warning disable IDE0007 // Use implicit type #pragma warning disable IDE0011 // Add braces #pragma warning disable IDE0018 // Inline variable declaration #pragma warning disable IDE0019 // Use pattern matching #pragma warning disable IDE0020 // Use pattern matching #pragma warning disable IDE0022 // Use expression body for methods #pragma warning disable IDE0040 // Add accessibility modifiers #pragma warning disable IDE0045 // Convert to conditional expression #pragma warning disable IDE0046 // Convert to conditional expression using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Xunit.Sdk { /// <summary> /// Formats arguments for display in theories. /// </summary> static class ArgumentFormatter { const int MAX_DEPTH = 3; const int MAX_ENUMERABLE_LENGTH = 5; const int MAX_OBJECT_PARAMETER_COUNT = 5; const int MAX_STRING_LENGTH = 50; static readonly object[] EmptyObjects = new object[0]; static readonly Type[] EmptyTypes = new Type[0]; // List of system types => C# type names static readonly Dictionary<TypeInfo, string> TypeMappings = new Dictionary<TypeInfo, string> { { typeof(bool).GetTypeInfo(), "bool" }, { typeof(byte).GetTypeInfo(), "byte" }, { typeof(sbyte).GetTypeInfo(), "sbyte" }, { typeof(char).GetTypeInfo(), "char" }, { typeof(decimal).GetTypeInfo(), "decimal" }, { typeof(double).GetTypeInfo(), "double" }, { typeof(float).GetTypeInfo(), "float" }, { typeof(int).GetTypeInfo(), "int" }, { typeof(uint).GetTypeInfo(), "uint" }, { typeof(long).GetTypeInfo(), "long" }, { typeof(ulong).GetTypeInfo(), "ulong" }, { typeof(object).GetTypeInfo(), "object" }, { typeof(short).GetTypeInfo(), "short" }, { typeof(ushort).GetTypeInfo(), "ushort" }, { typeof(string).GetTypeInfo(), "string" }, }; /// <summary> /// Format the value for presentation. /// </summary> /// <param name="value">The value to be formatted.</param> /// <returns>The formatted value.</returns> public static string Format(object value) { return Format(value, 1); } static string Format(object value, int depth) { if (value == null) return "null"; var valueAsType = value as Type; if (valueAsType != null) return $"typeof({FormatTypeName(valueAsType)})"; try { if (value.GetType().GetTypeInfo().IsEnum) return value.ToString().Replace(", ", " | "); if (value is char) { var charValue = (char)value; if (charValue == '\'') return @"'\''"; // Take care of all of the escape sequences string escapeSequence; if (TryGetEscapeSequence(charValue, out escapeSequence)) { return $"'{escapeSequence}'"; } if (char.IsLetterOrDigit(charValue) || char.IsPunctuation(charValue) || char.IsSymbol(charValue) || charValue == ' ') return $"'{charValue}'"; // Fallback to hex return $"0x{(int)charValue:x4}"; } if (value is DateTime || value is DateTimeOffset) return $"{value:o}"; var stringParameter = value as string; if (stringParameter != null) { stringParameter = EscapeHexChars(stringParameter); stringParameter = stringParameter.Replace(@"""", @"\"""); // escape double quotes if (stringParameter.Length > MAX_STRING_LENGTH) { string displayed = stringParameter.Substring(0, MAX_STRING_LENGTH); return $"\"{displayed}\"..."; } return $"\"{stringParameter}\""; } try { var enumerable = value as IEnumerable; if (enumerable != null) return FormatEnumerable(enumerable.Cast<object>(), depth); } catch { // Sometimes enumerables cannot be enumerated when being, and instead thrown an exception. // This could be, for example, because they require state that is not provided by Xunit. // In these cases, just continue formatting. } var type = value.GetType(); var typeInfo = type.GetTypeInfo(); if (typeInfo.IsValueType) return Convert.ToString(value, CultureInfo.CurrentCulture); var task = value as Task; if (task != null) { var typeParameters = typeInfo.GenericTypeArguments; var typeName = typeParameters.Length == 0 ? "Task" : $"Task<{string.Join(",", typeParameters.Select(FormatTypeName))}>"; return $"{typeName} {{ Status = {task.Status} }}"; } var toString = type.GetRuntimeMethod("ToString", EmptyTypes); if (toString != null && toString.DeclaringType != typeof(object)) return (string)toString.Invoke(value, EmptyObjects); return FormatComplexValue(value, depth, type); } catch (Exception ex) { // Sometimes an exception is thrown when formatting an argument, such as in ToString. // In these cases, we don't want xunit to crash, as tests may have passed despite this. return $"{ex.GetType().Name} was thrown formatting an object of type \"{value.GetType()}\""; } } static string FormatComplexValue(object value, int depth, Type type) { if (depth == MAX_DEPTH) return $"{type.Name} {{ ... }}"; var fields = type.GetRuntimeFields() .Where(f => f.IsPublic && !f.IsStatic) .Select(f => new { name = f.Name, value = WrapAndGetFormattedValue(() => f.GetValue(value), depth) }); var properties = type.GetRuntimeProperties() .Where(p => p.GetMethod != null && p.GetMethod.IsPublic && !p.GetMethod.IsStatic) .Select(p => new { name = p.Name, value = WrapAndGetFormattedValue(() => p.GetValue(value), depth) }); var parameters = fields.Concat(properties) .OrderBy(p => p.name) .Take(MAX_OBJECT_PARAMETER_COUNT + 1) .ToList(); if (parameters.Count == 0) return $"{type.Name} {{ }}"; var formattedParameters = string.Join(", ", parameters.Take(MAX_OBJECT_PARAMETER_COUNT) .Select(p => $"{p.name} = {p.value}")); if (parameters.Count > MAX_OBJECT_PARAMETER_COUNT) formattedParameters += ", ..."; return $"{type.Name} {{ {formattedParameters} }}"; } static string FormatEnumerable(IEnumerable<object> enumerableValues, int depth) { if (depth == MAX_DEPTH) return "[...]"; var values = enumerableValues.Take(MAX_ENUMERABLE_LENGTH + 1).ToList(); var printedValues = string.Join(", ", values.Take(MAX_ENUMERABLE_LENGTH).Select(x => Format(x, depth + 1))); if (values.Count > MAX_ENUMERABLE_LENGTH) printedValues += ", ..."; return $"[{printedValues}]"; } static string FormatTypeName(Type type) { var typeInfo = type.GetTypeInfo(); var arraySuffix = ""; // Deconstruct and re-construct array while (typeInfo.IsArray) { var rank = typeInfo.GetArrayRank(); arraySuffix += $"[{new string(',', rank - 1)}]"; typeInfo = typeInfo.GetElementType().GetTypeInfo(); } // Map C# built-in type names string result; if (TypeMappings.TryGetValue(typeInfo, out result)) return result + arraySuffix; // Strip off generic suffix var name = typeInfo.FullName; // catch special case of generic parameters not being bound to a specific type: if (name == null) return typeInfo.Name; var tickIdx = name.IndexOf('`'); if (tickIdx > 0) name = name.Substring(0, tickIdx); if (typeInfo.IsGenericTypeDefinition) name = $"{name}<{new string(',', typeInfo.GenericTypeParameters.Length - 1)}>"; else if (typeInfo.IsGenericType) { if (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>)) name = FormatTypeName(typeInfo.GenericTypeArguments[0]) + "?"; else name = $"{name}<{string.Join(", ", typeInfo.GenericTypeArguments.Select(FormatTypeName))}>"; } return name + arraySuffix; } static string WrapAndGetFormattedValue(Func<object> getter, int depth) { try { return Format(getter(), depth + 1); } catch (Exception ex) { return $"(throws {UnwrapException(ex).GetType().Name})"; } } static Exception UnwrapException(Exception ex) { while (true) { var tiex = ex as TargetInvocationException; if (tiex == null) return ex; ex = tiex.InnerException; } } static string EscapeHexChars(string s) { var builder = new StringBuilder(s.Length); for (int i = 0; i < s.Length; i++) { char ch = s[i]; string escapeSequence; if (TryGetEscapeSequence(ch, out escapeSequence)) builder.Append(escapeSequence); else if (ch < 32) // C0 control char builder.AppendFormat(@"\x{0}", (+ch).ToString("x2")); else if (char.IsSurrogatePair(s, i)) // should handle the case of ch being the last one { // For valid surrogates, append like normal builder.Append(ch); builder.Append(s[++i]); } // Check for stray surrogates/other invalid chars else if (char.IsSurrogate(ch) || ch == '\uFFFE' || ch == '\uFFFF') { builder.AppendFormat(@"\x{0}", (+ch).ToString("x4")); } else builder.Append(ch); // Append the char like normal } return builder.ToString(); } static bool TryGetEscapeSequence(char ch, out string value) { value = null; if (ch == '\t') // tab value = @"\t"; if (ch == '\n') // newline value = @"\n"; if (ch == '\v') // vertical tab value = @"\v"; if (ch == '\a') // alert value = @"\a"; if (ch == '\r') // carriage return value = @"\r"; if (ch == '\f') // formfeed value = @"\f"; if (ch == '\b') // backspace value = @"\b"; if (ch == '\0') // null char value = @"\0"; if (ch == '\\') // backslash value = @"\\"; return value != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Text; namespace EncodingTests { public static class UTF32BE { private static readonly EncodingTestHelper s_encodingUtil_UTF32BE = new EncodingTestHelper("UTF-32BE"); [Fact] public static void GetByteCount_InvalidArgumentAndBoundaryValues() { s_encodingUtil_UTF32BE.GetByteCountTest(String.Empty, 0, 0, 0); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetByteCountTest(String.Empty, 0, 1, 0)); Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetByteCountTest((String)null, 0, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetByteCountTest("abc", -1, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetByteCountTest("abc", 0, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetByteCountTest("abc", -1, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetByteCountTest("abc", 1, -1, 0)); s_encodingUtil_UTF32BE.GetByteCountTest("abc", 3, 0, 0); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetByteCountTest("abc", 3, 1, 0)); s_encodingUtil_UTF32BE.GetByteCountTest("abc", 2, 1, 4); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetByteCountTest("abc", 4, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetByteCountTest("abc", 2, 2, 0)); } [Fact] public static void GetCharCount_InvalidArgumentAndBoundaryValues() { Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetCharCountTest((Byte[])null, 0, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, -1, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, -1, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 1, -1, 0)); s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 8, 0, 0); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 8, 1, 0)); s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 4, 4, 1); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 9, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 4, 5, 0)); } [Fact] public static void GetByteCount_InvalidArgumentAndBoundaryValues_Pointer() { Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetByteCountTest((String)null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetByteCountTest(String.Empty, -1, 0)); s_encodingUtil_UTF32BE.GetByteCountTest(String.Empty, 0, 0); s_encodingUtil_UTF32BE.GetByteCountTest("a", 0, 0); } [Fact] public static void GetCharCount_InvalidArgumentAndBoundaryValues_Pointer() { Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetCharCountTest((Byte[])null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { }, -1, 0)); s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { }, 0, 0); s_encodingUtil_UTF32BE.GetCharCountTest(new Byte[] { 0x00, 0x00, 0x00, 0x61 }, 0, 0); } [Fact] public static void GetBytes_InvalidConversionInput() { Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetBytesTest((String)null, 0, 0, 0, 0, new Byte[] { }, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", -1, 0, 0, 0, new Byte[] { }, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, -1, 0, 0, new Byte[] { }, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", -1, -1, 0, 0, new Byte[] { }, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", 1, -1, 0, 0, new Byte[] { }, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, 4, 0, 0, new Byte[] { }, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", 1, 3, 0, 0, new Byte[] { }, 0)); } [Fact] public static void GetChars_InvalidConversionInput() { Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetCharsTest((Byte[])null, 0, 0, 0, 0, String.Empty, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, -1, 0, 0, 0, String.Empty, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, -1, 0, 0, String.Empty, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, -1, -1, 0, 0, String.Empty, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 1, -1, 0, 0, String.Empty, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, 9, 0, 0, String.Empty, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 4, 5, 0, 0, String.Empty, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61 }, 5, -2, 0, 0, String.Empty, 0)); } [Fact] public static void GetChars_BufferBoundary() { Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, 8, -2, 0, String.Empty, 0)); Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, 8, 0, 0, String.Empty, 0)); Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, 8, -1, 1, String.Empty, 0)); Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, 8, 1, 0, String.Empty, 0)); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, 0, 1, 1, "\u0000", 0); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, 0, 1, 2, String.Empty, 0)); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, 8, 4, 1, "\u0000\u0061\u0062\u0000", 2); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, 0, -1, -1, String.Empty, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62 }, 0, 4, -1, -1, String.Empty, 0)); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { }, 0, 0, -1, 0, String.Empty, 0); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { }, 0, 0, 0, 0, String.Empty, 0); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61 }, 0, 0, 1, 0, "\u0000", 0); } [Fact] public static void GetBytes_BufferBoundary() { Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, 3, -2, 0, (Byte[])null, 0)); Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, 3, 0, 0, (Byte[])null, 0)); Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, 3, -1, 1, (Byte[])null, 0)); Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, 3, 1, 0, (Byte[])null, 0)); s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, 0, 1, 1, new Byte[] { 0x00 }, 0); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, 0, 1, 2, (Byte[])null, 0)); s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, 3, 14, 1, new Byte[] { 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62, 0x00, 0x00, 0x00, 0x63, 0x00 }, 12); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, 0, -1, -1, (Byte[])null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, 1, -1, -1, (Byte[])null, 0)); s_encodingUtil_UTF32BE.GetBytesTest(String.Empty, 0, 0, -1, 0, new Byte[] { }, 0); s_encodingUtil_UTF32BE.GetBytesTest(String.Empty, 0, 0, 0, 0, new Byte[] { }, 0); s_encodingUtil_UTF32BE.GetBytesTest("a", 0, 0, 4, 0, new Byte[] { 0x00, 0x00, 0x00, 0x00 }, 0); } [Fact] public static void GetChars_BufferBoundary_Pointer() { Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetCharsTest((Byte[])null, 0, 0, 0, String.Empty, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { }, -1, 0, 0, String.Empty, 0)); Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { }, 0, -2, 0, (String)null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { }, 0, 0, -1, String.Empty, 0)); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { }, 0, 0, 0, String.Empty, 0); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { }, 0, -1, -100, String.Empty, 0); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61 }, 0, 1, 1, "\u0000", 0); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61 }, 4, -1, -100, "a", 1); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61 }, 4, 2, 2, "\u0061\u0000", 1); Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61 }, 4, 0, 0, String.Empty, 0)); } [Fact] public static void GetBytes_BufferBoundary_Pointer() { Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetBytesTest((String)null, 0, 0, 0, new Byte[] { }, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetBytesTest(String.Empty, -1, 0, 0, new Byte[] { }, 0)); Assert.Throws<ArgumentNullException>(() => s_encodingUtil_UTF32BE.GetBytesTest(String.Empty, 0, -2, 0, (Byte[])null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetBytesTest(String.Empty, 0, 0, -1, new Byte[] { }, 0)); s_encodingUtil_UTF32BE.GetBytesTest(String.Empty, 0, 0, 0, new Byte[] { }, 0); s_encodingUtil_UTF32BE.GetBytesTest(String.Empty, 0, -1, -100, new Byte[] { }, 0); s_encodingUtil_UTF32BE.GetBytesTest("a", 0, 4, 4, new Byte[] { 0x00, 0x00, 0x00, 0x00 }, 0); s_encodingUtil_UTF32BE.GetBytesTest("a", 1, -1, -100, new Byte[] { 0x00, 0x00, 0x00, 0x61 }, 4); s_encodingUtil_UTF32BE.GetBytesTest("a", 1, 6, 6, new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00 }, 4); Assert.Throws<ArgumentException>(() => s_encodingUtil_UTF32BE.GetBytesTest("a", 1, 0, 0, new Byte[] { }, 0)); } [Fact] public static void ValidCodePoints() { s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x00, 0x61 }, 0, 4, -1, 0, "a", 1); s_encodingUtil_UTF32BE.GetBytesTest("abc", 0, 3, -1, 0, new Byte[] { 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x62, 0x00, 0x00, 0x00, 0x63 }, 12); } [Fact] public static void GetChars_InvalidSequence_OddNumberOfByte() { s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x61, 0x00 }, 0, 3, -1, 0, "\uFFFD", 1); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x61 }, 0, 2, -1, 0, "\uFFFD", 1); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x61 }, 0, 1, -1, 0, "\uFFFD", 1); s_encodingUtil_UTF32BE.GetCharsTest(false, false, new Byte[] { 0x00, 0x61, 0x00 }, 0, 3, -1, 0, "\uFFFD", 1); s_encodingUtil_UTF32BE.GetCharsTest(false, false, new Byte[] { 0x00, 0x61 }, 0, 2, -1, 0, "\uFFFD", 1); s_encodingUtil_UTF32BE.GetCharsTest(false, false, new Byte[] { 0x61 }, 0, 1, -1, 0, "\uFFFD", 1); Assert.Throws<DecoderFallbackException>(() => s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x00, 0x61, 0x00 }, 0, 3, 1, 0, String.Empty, 0)); Assert.Throws<DecoderFallbackException>(() => s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x00, 0x61 }, 0, 2, 1, 0, String.Empty, 0)); Assert.Throws<DecoderFallbackException>(() => s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x61 }, 0, 1, 1, 0, String.Empty, 0)); } // They don't represent abstract characters, but still need to be transmitted [Fact] public static void Specials() { // U+FFFF, U+FFFE, U+FFFD s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0xFF, 0xFD }, 0, 12, -1, 0, "\uFFFF\uFFFE\uFFFD", 3); s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0xFF, 0xFD }, 0, 12, -1, 0, "\uFFFF\uFFFE\uFFFD", 3); s_encodingUtil_UTF32BE.GetBytesTest("\uFFFF\uFFFE\uFFFD", 0, 3, -1, 0, new Byte[] { 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0xFF, 0xFD }, 12); s_encodingUtil_UTF32BE.GetBytesTest(false, true, "\uFFFF\uFFFE\uFFFD", 0, 3, -1, 0, new Byte[] { 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0xFF, 0xFD }, 12); /// U+FDD0 - U+FDEF s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0xFD, 0xD0, 0x00, 0x00, 0xFD, 0xEF }, 0, 8, -1, 0, "\uFDD0\uFDEF", 2); s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x00, 0x00, 0xFD, 0xD0, 0x00, 0x00, 0xFD, 0xEF }, 0, 8, -1, 0, "\uFDD0\uFDEF", 2); } /// <summary> /// High: D800 - DBFF; Low: DC00-DFFF /// Invalid/unpaired surrogates are not considered representing unique /// Unicode scalar values, therefore they should be always filtered out /// (they are removed from the roundtripping requirement by design) /// /// D800 + DC00: 110110-0000-000000 110111-0000000000: U+000-00001-00000000-00000000 /// D800 + DFFF: 110110-0000-000000 110111-1111111111: U+000-00001-00000011-11111111 /// DBFF + DC00: 110110-1111-111111 110111-0000000000: U+000-10000-11111100-00000000 /// DBFF + DFFF: 110110-1111-111111 110111-1111111111: U+000-10000-11111111-11111111 /// </summary> [Fact] public static void Surrogates() { s_encodingUtil_UTF32BE.GetBytesTest("\uD800\uDC00", 0, 2, -1, 0, new Byte[] { 0x00, 0x01, 0x00, 0x00 }, 4); s_encodingUtil_UTF32BE.GetBytesTest("\uD800\uDFFF", 0, 2, -1, 0, new Byte[] { 0x00, 0x01, 0x03, 0xFF }, 4); s_encodingUtil_UTF32BE.GetBytesTest("\uDBFF\uDC00", 0, 2, -1, 0, new Byte[] { 0x00, 0x10, 0xFC, 0x00 }, 4); s_encodingUtil_UTF32BE.GetBytesTest("\uDBFF\uDFFF", 0, 2, -1, 0, new Byte[] { 0x00, 0x10, 0xFF, 0xFF }, 4); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0xFF, 0xFF }, 0, 8, -1, 0, "\uD800\uDC00\uDBFF\uDFFF", 4); // Invalid 1 surrogate character s_encodingUtil_UTF32BE.GetBytesTest("\uD800\uDC00", 0, 1, -1, 0, new Byte[] { 0x00, 0x00, 0xFF, 0xFD }, 4); Assert.Throws<EncoderFallbackException>(() => s_encodingUtil_UTF32BE.GetBytesTest(false, true, "\uD800\uDC00", 0, 1, 4, 0, new Byte[] { }, 0)); s_encodingUtil_UTF32BE.GetBytesTest("\uD800\uDC00", 1, 1, -1, 0, new Byte[] { 0x00, 0x00, 0xFF, 0xFD }, 4); Assert.Throws<EncoderFallbackException>(() => s_encodingUtil_UTF32BE.GetBytesTest(false, true, "\uD800\uDC00", 1, 1, 4, 0, new Byte[] { }, 0)); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0xDB, 0xFF, 0x00, 0x00, 0xDF, 0xFF }, 0, 4, -1, 0, "\uFFFD", 1); Assert.Throws<DecoderFallbackException>(() => s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x00, 0x00, 0xDB, 0xFF, 0x00, 0x00, 0xDF, 0xFF }, 0, 4, 1, 0, String.Empty, 0)); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0xDB, 0xFF, 0x00, 0x00, 0xDF, 0xFF }, 4, 4, -1, 0, "\uFFFD", 1); Assert.Throws<DecoderFallbackException>(() => s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x00, 0x00, 0xDB, 0xFF, 0x00, 0x00, 0xDF, 0xFF }, 4, 4, 1, 0, String.Empty, 0)); // Surrogate pair s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0xDB, 0xFF, 0x00, 0x00, 0xDF, 0xFF }, 0, 8, -1, 0, "\uFFFD\uFFFD", 2); Assert.Throws<DecoderFallbackException>(() => s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x00, 0x00, 0xDB, 0xFF, 0x00, 0x00, 0xDF, 0xFF }, 0, 8, 2, 0, String.Empty, 0)); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0xD8, 0x00, 0x00, 0x00, 0xDC, 0x00 }, 0, 8, -1, 0, "\uFFFD\uFFFD", 2); Assert.Throws<DecoderFallbackException>(() => s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x00, 0x00, 0xD8, 0x00, 0x00, 0x00, 0xDC, 0x00 }, 0, 8, 2, 0, String.Empty, 0)); // Invalid first/second s_encodingUtil_UTF32BE.GetBytesTest("\uD800\u0041", 0, 2, -1, 0, new Byte[] { 0x00, 0x00, 0xFF, 0xFD, 0x00, 0x00, 0x00, 0x41 }, 8); Assert.Throws<EncoderFallbackException>(() => s_encodingUtil_UTF32BE.GetBytesTest(false, true, "\uD800\u0041", 0, 2, 8, 0, new Byte[] { }, 0)); s_encodingUtil_UTF32BE.GetBytesTest("\u0065\uDC00", 0, 2, -1, 0, new Byte[] { 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0xFF, 0xFD }, 8); Assert.Throws<EncoderFallbackException>(() => s_encodingUtil_UTF32BE.GetBytesTest(false, true, "\u0065\uDC00", 0, 2, 8, 0, new Byte[] { }, 0)); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0xDB, 0xFF, 0x00, 0x00, 0xFF, 0xFD }, 0, 8, -1, 0, "\uFFFD\uFFFD", 2); Assert.Throws<DecoderFallbackException>(() => s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x00, 0x00, 0xDB, 0xFF, 0x00, 0x00, 0xFF, 0xFD }, 0, 8, 2, 0, String.Empty, 0)); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xDF, 0xFF }, 0, 8, -1, 0, "\u8000\uFFFD", 2); Assert.Throws<DecoderFallbackException>(() => s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xDF, 0xFF }, 0, 8, 2, 0, String.Empty, 0)); // Too high scalar value s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x11, 0xFF, 0xFF }, 0, 4, -1, 0, "\uFFFD", 1); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x00, 0x11, 0x00, 0x00 }, 0, 4, -1, 0, "\uFFFD", 1); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x01, 0x00, 0x00, 0x00 }, 0, 4, -1, 0, "\uFFFD", 1); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0x01, 0x10, 0xFF, 0xFF }, 0, 4, -1, 0, "\uFFFD", 1); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0xFF, 0x00, 0x00, 0x00 }, 0, 4, -1, 0, "\uFFFD", 1); s_encodingUtil_UTF32BE.GetCharsTest(new Byte[] { 0xFF, 0xFF, 0xFF, 0xFF }, 0, 4, -1, 0, "\uFFFD", 1); Assert.Throws<DecoderFallbackException>(() => s_encodingUtil_UTF32BE.GetCharsTest(false, true, new Byte[] { 0x00, 0x11, 0x00, 0x00 }, 0, 4, 2, 0, String.Empty, 0)); s_encodingUtil_UTF32BE.GetMaxByteCountTest(0, 4); s_encodingUtil_UTF32BE.GetMaxByteCountTest(2, 12); s_encodingUtil_UTF32BE.GetMaxByteCountTest(4, 20); s_encodingUtil_UTF32BE.GetMaxByteCountTest(536870910, 2147483644); Assert.Throws<ArgumentOutOfRangeException>(() => s_encodingUtil_UTF32BE.GetMaxByteCountTest(536870911, 0)); } [Fact] public static void GetMaxCount() { s_encodingUtil_UTF32BE.GetMaxCharCountTest(0, 2); s_encodingUtil_UTF32BE.GetMaxCharCountTest(1, 2); s_encodingUtil_UTF32BE.GetMaxCharCountTest(2, 3); s_encodingUtil_UTF32BE.GetMaxCharCountTest(3, 3); s_encodingUtil_UTF32BE.GetMaxCharCountTest(4, 4); s_encodingUtil_UTF32BE.GetMaxCharCountTest(5, 4); s_encodingUtil_UTF32BE.GetMaxCharCountTest(6, 5); s_encodingUtil_UTF32BE.GetMaxCharCountTest(7, 5); s_encodingUtil_UTF32BE.GetMaxCharCountTest(8, 6); s_encodingUtil_UTF32BE.GetMaxCharCountTest(9, 6); s_encodingUtil_UTF32BE.GetMaxCharCountTest(10, 7); s_encodingUtil_UTF32BE.GetMaxCharCountTest(11, 7); s_encodingUtil_UTF32BE.GetMaxCharCountTest(12, 8); s_encodingUtil_UTF32BE.GetMaxCharCountTest(13, 8); s_encodingUtil_UTF32BE.GetMaxCharCountTest(14, 9); s_encodingUtil_UTF32BE.GetMaxCharCountTest(2147483647, 1073741825); } [Fact] public static void GetPreamble() { s_encodingUtil_UTF32BE.GetPreambleTest(false, false, new Byte[] { }); s_encodingUtil_UTF32BE.GetPreambleTest(true, false, new Byte[] { 0x00, 0x00, 0xFE, 0xFF }); s_encodingUtil_UTF32BE.GetPreambleTest(new Byte[] { 0x00, 0x00, 0xFE, 0xFF }); } } }
// Copyright 2017 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Android.App; using Android.OS; using Android.Widget; using ArcGISRuntimeXamarin.Managers; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks; using Esri.ArcGISRuntime.Tasks.Offline; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using Esri.ArcGISRuntime.ArcGISServices; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; namespace ArcGISRuntimeXamarin.Samples.EditAndSyncFeatures { [Activity] public class EditAndSyncFeatures : Activity { // Enumeration to track which phase of the workflow the sample is in private enum EditState { NotReady, // Geodatabase has not yet been generated Editing, // A feature is in the process of being moved Ready // The geodatabase is ready for synchronization or further edits } // URI for a feature service that supports geodatabase generation private Uri _featureServiceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer"); // Path to the geodatabase file on disk private string _gdbPath; // Task to be used for generating the geodatabase private GeodatabaseSyncTask _gdbSyncTask; // Flag to indicate which stage of the edit process we're in private EditState _readyForEdits = EditState.NotReady; // Hold a reference to the generated geodatabase private Geodatabase _resultGdb; // Mapview private MapView myMapView; // Generate Button private Button myGenerateButton; // Sync Button private Button mySyncButton; // Progress bar private ProgressBar myProgressBar; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Edit and Sync Features"; // Create the UI, setup the control references and execute initialization CreateLayout(); Initialize(); } private void CreateLayout() { // Create the layout LinearLayout layout = new LinearLayout(this); layout.Orientation = Orientation.Vertical; // Add the progress bar myProgressBar = new ProgressBar(this); myProgressBar.Visibility = Android.Views.ViewStates.Gone; layout.AddView(myProgressBar); // Add the generate button myGenerateButton = new Button(this); myGenerateButton.Text = "Generate"; myGenerateButton.Click += GenerateButton_Clicked; layout.AddView(myGenerateButton); // Add the sync button mySyncButton = new Button(this); mySyncButton.Text = "Synchronize"; mySyncButton.Click += SyncButton_Click; layout.AddView(mySyncButton); // Add the mapview myMapView = new MapView(this); layout.AddView(myMapView); // Add the layout to the view SetContentView(layout); } private async void Initialize() { // Create a tile cache and load it with the SanFrancisco streets tpk TileCache tileCache = new TileCache(await GetTpkPath()); // Create the corresponding layer based on the tile cache ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache); // Create the basemap based on the tile cache Basemap sfBasemap = new Basemap(tileLayer); // Create the map with the tile-based basemap Map myMap = new Map(sfBasemap); // Assign the map to the MapView myMapView.Map = myMap; // Create a new symbol for the extent graphic SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2); // Create graphics overlay for the extent graphic and apply a renderer GraphicsOverlay extentOverlay = new GraphicsOverlay(); extentOverlay.Renderer = new SimpleRenderer(lineSymbol); // Add graphics overlay to the map view myMapView.GraphicsOverlays.Add(extentOverlay); // Set up an event handler for when the viewpoint (extent) changes myMapView.ViewpointChanged += MapViewExtentChanged; // Set up event handler for mapview taps myMapView.GeoViewTapped += GeoViewTapped; // Update the local data path for the geodatabase file _gdbPath = GetFileStreamPath("wildfire.geodatabase").AbsolutePath; // Create a task for generating a geodatabase (GeodatabaseSyncTask) _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri); // Add all graphics from the service to the map foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos) { // Get the Uri for this particular layer Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id); // Create the ServiceFeatureTable ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri); // Wait for the table to load await onlineTable.LoadAsync(); // Add the layer to the map's operational layers if load succeeds if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded) { myMap.OperationalLayers.Add(new FeatureLayer(onlineTable)); } } } private async void GeoViewTapped(object sender, GeoViewInputEventArgs e) { // Disregard if not ready for edits if (_readyForEdits == EditState.NotReady) { return; } // If an edit is in process, finish it if (_readyForEdits == EditState.Editing) { // Hold a list of any selected features List<Feature> selectedFeatures = new List<Feature>(); // Get all selected features then clear selection foreach (FeatureLayer layer in myMapView.Map.OperationalLayers) { // Get the selected features FeatureQueryResult layerFeatures = await layer.GetSelectedFeaturesAsync(); // FeatureQueryResult implements IEnumerable, so it can be treated as a collection of features selectedFeatures.AddRange(layerFeatures); // Clear the selection layer.ClearSelection(); } // Update all selected features' geometry foreach (Feature feature in selectedFeatures) { // Get a reference to the correct feature table for the feature GeodatabaseFeatureTable table = feature.FeatureTable as GeodatabaseFeatureTable; // Ensure the geometry type of the table is point if (table.GeometryType != GeometryType.Point) { continue; } // Set the new geometry feature.Geometry = e.Location; // Update the feature in the table await table.UpdateFeatureAsync(feature); } // Update the edit state _readyForEdits = EditState.Ready; // Enable the sync button mySyncButton.Enabled = true; } // Otherwise, start an edit else { // Define a tolerance for use with identifying the feature double tolerance = 15 * myMapView.UnitsPerPixel; // Define the selection envelope Envelope selectionEnvelope = new Envelope(e.Location.X - tolerance, e.Location.Y - tolerance, e.Location.X + tolerance, e.Location.Y + tolerance); // Define query parameters for feature selection QueryParameters query = new QueryParameters() { Geometry = selectionEnvelope }; // Select the feature in all applicable tables foreach (FeatureLayer layer in myMapView.Map.OperationalLayers) { await layer.SelectFeaturesAsync(query, SelectionMode.New); } // Set the edit state _readyForEdits = EditState.Editing; } } private void UpdateMapExtent() { // Return if mapview is null if (myMapView == null) { return; } // Get the new viewpoint Viewpoint myViewPoint = myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry); // Return if viewpoint is null if (myViewPoint == null) { return; } // Get the updated extent for the new viewpoint Envelope extent = myViewPoint.TargetGeometry as Envelope; // Return if extent is null if (extent == null) { return; } // Create an envelope that is a bit smaller than the extent EnvelopeBuilder envelopeBldr = new EnvelopeBuilder(extent); envelopeBldr.Expand(0.80); // Get the (only) graphics overlay in the map view var extentOverlay = myMapView.GraphicsOverlays.FirstOrDefault(); // Return if the extent overlay is null if (extentOverlay == null) { return; } // Get the extent graphic Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault(); // Create the extent graphic and add it to the overlay if it doesn't exist if (extentGraphic == null) { extentGraphic = new Graphic(envelopeBldr.ToGeometry()); extentOverlay.Graphics.Add(extentGraphic); } else { // Otherwise, simply update the graphic's geometry extentGraphic.Geometry = envelopeBldr.ToGeometry(); } } private async void StartGeodatabaseGeneration() { // Create a task for generating a geodatabase (GeodatabaseSyncTask) _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri); // Get the (only) graphic in the map view GraphicsOverlay redPreviewBox = myMapView.GraphicsOverlays.FirstOrDefault(); // Get the current extent of the red preview box Envelope extent = redPreviewBox.Extent as Envelope; // Get the default parameters for the generate geodatabase task GenerateGeodatabaseParameters generateParams = await _gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(extent); // Create a generate geodatabase job GenerateGeodatabaseJob generateGdbJob = _gdbSyncTask.GenerateGeodatabase(generateParams, _gdbPath); // Handle the job changed event generateGdbJob.JobChanged += GenerateGdbJobChanged; // Handle the progress changed event with an inline (lambda) function to show the progress bar generateGdbJob.ProgressChanged += ((object sender, EventArgs e) => { // Get the job GenerateGeodatabaseJob job = sender as GenerateGeodatabaseJob; // Update the progress bar UpdateProgressBar(job.Progress); }); // Start the job generateGdbJob.Start(); } private async void HandleGenerationStatusChange(GenerateGeodatabaseJob job) { JobStatus status = job.Status; // If the job completed successfully, add the geodatabase data to the map if (status == JobStatus.Succeeded) { // Clear out the existing layers myMapView.Map.OperationalLayers.Clear(); // Get the new geodatabase _resultGdb = await job.GetResultAsync(); // Loop through all feature tables in the geodatabase and add a new layer to the map foreach (GeodatabaseFeatureTable table in _resultGdb.GeodatabaseFeatureTables) { // Create a new feature layer for the table FeatureLayer layer = new FeatureLayer(table); // Add the new layer to the map myMapView.Map.OperationalLayers.Add(layer); } // Enable editing features _readyForEdits = EditState.Ready; } // See if the job failed if (status == JobStatus.Failed) { // Create a message to show the user string message = "Generate geodatabase job failed"; // Show an error message (if there is one) if (job.Error != null) { message += ": " + job.Error.Message; } else { // If no error, show messages from the job foreach (JobMessage m in job.Messages) { // Get the text from the JobMessage and add it to the output string message += "\n" + m.Message; } } // Show the message ShowStatusMessage(message); } } private void HandleSyncStatusChange(SyncGeodatabaseJob job) { JobStatus status = job.Status; // Tell the user about job completion if (status == JobStatus.Succeeded) { ShowStatusMessage("Sync task completed"); } // See if the job failed if (status == JobStatus.Failed) { // Create a message to show the user string message = "Sync geodatabase job failed"; // Show an error message (if there is one) if (job.Error != null) { message += ": " + job.Error.Message; } else { // If no error, show messages from the job foreach (JobMessage m in job.Messages) { // Get the text from the JobMessage and add it to the output string message += "\n" + m.Message; } } // Show the message ShowStatusMessage(message); } } private void SyncGeodatabase() { // Return if not ready if (_readyForEdits != EditState.Ready) { return; } // Create parameters for the sync task SyncGeodatabaseParameters parameters = new SyncGeodatabaseParameters() { GeodatabaseSyncDirection = SyncDirection.Bidirectional, RollbackOnFailure = false }; // Get the layer Id for each feature table in the geodatabase, then add to the sync job foreach (GeodatabaseFeatureTable table in _resultGdb.GeodatabaseFeatureTables) { // Get the ID for the layer long id = table.ServiceLayerId; // Create the SyncLayerOption SyncLayerOption option = new SyncLayerOption(id); // Add the option parameters.LayerOptions.Add(option); } // Create job SyncGeodatabaseJob job = _gdbSyncTask.SyncGeodatabase(parameters, _resultGdb); // Subscribe to status updates job.JobChanged += Job_JobChanged; // Subscribe to progress updates job.ProgressChanged += Job_ProgressChanged; // Start the sync job.Start(); } private void Job_ProgressChanged(object sender, EventArgs e) { // Get the job object SyncGeodatabaseJob job = sender as SyncGeodatabaseJob; // Update the progress bar UpdateProgressBar(job.Progress); } // Get the path to the tile package used for the basemap // (this is plumbing for the sample viewer) private async Task<string> GetTpkPath() { // The desired tpk is expected to be called SanFrancisco.tpk string filename = "SanFrancisco.tpk"; // The data manager provides a method to get the folder string folder = DataManager.GetDataFolder(); // Get the full path string filepath = Path.Combine(folder, "SampleData", "EditAndSyncFeatures", filename); // Check if the file exists if (!File.Exists(filepath)) { // Download the map package file await DataManager.GetData("3f1bbf0ec70b409a975f5c91f363fe7d", "EditAndSyncFeatures"); } return filepath; } private void ShowStatusMessage(string message) { // Display the message to the user var builder = new AlertDialog.Builder(this); builder.SetMessage(message).SetTitle("Alert").Show(); } // Handler for the generate button clicked event private void GenerateButton_Clicked(object sender, EventArgs e) { // Call the cross-platform geodatabase generation method StartGeodatabaseGeneration(); } // Handler for the MapView Extent Changed event private void MapViewExtentChanged(object sender, EventArgs e) { // Call the cross-platform map extent update method UpdateMapExtent(); } // Handler for the job changed event private void GenerateGdbJobChanged(object sender, EventArgs e) { // Get the job object; will be passed to HandleGenerationStatusChange GenerateGeodatabaseJob job = sender as GenerateGeodatabaseJob; // Due to the nature of the threading implementation, // the dispatcher needs to be used to interact with the UI // The dispatcher takes an Action, provided here as a lambda function RunOnUiThread(() => { // Update progress bar visibility if (job.Status == JobStatus.Started) { myProgressBar.Visibility = Android.Views.ViewStates.Visible; } else { myProgressBar.Visibility = Android.Views.ViewStates.Gone; } // Do the remainder of the job status changed work HandleGenerationStatusChange(job); }); } private void UpdateProgressBar(int progress) { // Due to the nature of the threading implementation, // the dispatcher needs to be used to interact with the UI // The dispatcher takes an Action, provided here as a lambda function RunOnUiThread(() => { // Update the progress bar value myProgressBar.Progress = progress; }); } private void SyncButton_Click(object sender, EventArgs e) { SyncGeodatabase(); } private void Job_JobChanged(object sender, EventArgs e) { // Get the job object; will be passed to HandleGenerationStatusChange SyncGeodatabaseJob job = sender as SyncGeodatabaseJob; // Due to the nature of the threading implementation, // the dispatcher needs to be used to interact with the UI // The dispatcher takes an Action, provided here as a lambda function RunOnUiThread(() => { // Update the progress bar as appropriate if (job.Status == JobStatus.Succeeded || job.Status == JobStatus.Failed) { // Update the progress bar's value UpdateProgressBar(0); // Hide the progress bar myProgressBar.Visibility = Android.Views.ViewStates.Gone; } else { // Show the progress bar myProgressBar.Visibility = Android.Views.ViewStates.Visible; } // Do the remainder of the job status changed work HandleSyncStatusChange(job); }); } } }
using System; using System.Collections; using System.Globalization; using System.IO; using System.Text; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Oiw; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.Utilities; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.X509; namespace Org.BouncyCastle.Pkcs { public class Pkcs12Store { private readonly IgnoresCaseHashtable keys = new IgnoresCaseHashtable(); private readonly Hashtable localIds = new Hashtable(); private readonly IgnoresCaseHashtable certs = new IgnoresCaseHashtable(); private readonly Hashtable chainCerts = new Hashtable(); private readonly Hashtable keyCerts = new Hashtable(); private readonly DerObjectIdentifier keyAlgorithm; private readonly DerObjectIdentifier certAlgorithm; private const int MinIterations = 1024; private const int SaltSize = 20; private static SubjectKeyIdentifier CreateSubjectKeyID( AsymmetricKeyParameter pubKey) { return new SubjectKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey)); } internal class CertId { private readonly byte[] id; internal CertId( AsymmetricKeyParameter pubKey) { this.id = CreateSubjectKeyID(pubKey).GetKeyIdentifier(); } internal CertId( byte[] id) { this.id = id; } internal byte[] Id { get { return id; } } public override int GetHashCode() { return Arrays.GetHashCode(id); } public override bool Equals( object obj) { if (obj == this) return true; CertId other = obj as CertId; if (other == null) return false; return Arrays.AreEqual(id, other.id); } } internal Pkcs12Store( DerObjectIdentifier keyAlgorithm, DerObjectIdentifier certAlgorithm) { this.keyAlgorithm = keyAlgorithm; this.certAlgorithm = certAlgorithm; } // TODO Consider making obsolete // [Obsolete("Use 'Pkcs12StoreBuilder' instead")] public Pkcs12Store() : this(PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc, PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc) { } // TODO Consider making obsolete // [Obsolete("Use 'Pkcs12StoreBuilder' and 'Load' method instead")] public Pkcs12Store( Stream input, char[] password) : this() { Load(input, password); } public void Load( Stream input, char[] password) { if (input == null) throw new ArgumentNullException("input"); if (password == null) throw new ArgumentNullException("password"); Asn1Sequence obj = (Asn1Sequence) Asn1Object.FromStream(input); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; bool unmarkedKey = false; bool wrongPkcs12Zero = false; if (bag.MacData != null) // check the mac code { MacData mData = bag.MacData; DigestInfo dInfo = mData.Mac; AlgorithmIdentifier algId = dInfo.AlgorithmID; byte[] salt = mData.GetSalt(); int itCount = mData.IterationCount.IntValue; byte[] data = ((Asn1OctetString) info.Content).GetOctets(); byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data); byte[] dig = dInfo.GetDigest(); if (!Arrays.AreEqual(mac, dig)) { if (password.Length > 0) throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); // Try with incorrect zero length password mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data); if (!Arrays.AreEqual(mac, dig)) throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); wrongPkcs12Zero = true; } } keys.Clear(); localIds.Clear(); ArrayList chain = new ArrayList(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octs = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence) Asn1OctetString.FromByteArray(octs)); ContentInfo[] cis = authSafe.GetContentInfo(); foreach (ContentInfo ci in cis) { DerObjectIdentifier oid = ci.ContentType; if (oid.Equals(PkcsObjectIdentifiers.Data)) { byte[] octets = ((Asn1OctetString)ci.Content).GetOctets(); Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier) sq[0]; Asn1Set attrSet = (Asn1Set) sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.ContainsKey(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } if (localId != null) { byte[] hex = Hex.Encode(localId.GetOctets()); string name = Encoding.ASCII.GetString(hex, 0, hex.Length); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else { unmarkedKey = true; keys["unmarked"] = pkcs12Key; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else { Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); } } } else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData)) { EncryptedData d = EncryptedData.GetInstance(ci.Content); byte[] octets = CryptPbeData(false, d.EncryptionAlgorithm, password, wrongPkcs12Zero, d.Content.GetOctets()); Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier) sq[0]; Asn1Set attrSet = (Asn1Set) sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.ContainsKey(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } // TODO Should we be checking localIds != null here // as for PkcsObjectIdentifiers.Data version above? byte[] hex = Hex.Encode(localId.GetOctets()); string name = Encoding.ASCII.GetString(hex, 0, hex.Length); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { PrivateKeyInfo privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyInfo); // // set the attributes on the key // string alias = null; Asn1OctetString localId = null; Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier) sq[0]; Asn1Set attrSet = (Asn1Set) sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.ContainsKey(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } // TODO Should we be checking localIds != null here // as for PkcsObjectIdentifiers.Data version above? byte[] hex = Hex.Encode(localId.GetOctets()); string name = Encoding.ASCII.GetString(hex, 0, hex.Length); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else { Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); } } } else { Console.WriteLine("extra " + oid); Console.WriteLine("extra " + Asn1Dump.DumpAsString(ci.Content)); } } } certs.Clear(); chainCerts.Clear(); keyCerts.Clear(); foreach (SafeBag b in chain) { CertBag cb = new CertBag((Asn1Sequence)b.BagValue); byte[] octets = ((Asn1OctetString) cb.CertValue).GetOctets(); X509Certificate cert = new X509CertificateParser().ReadCertificate(octets); // // set the attributes // Hashtable attributes = new Hashtable(); Asn1OctetString localId = null; string alias = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier) sq[0]; Asn1Set attrSet = (Asn1Set) sq[1]; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set Asn1Encodable attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.ContainsKey(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } CertId certId = new CertId(cert.GetPublicKey()); X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes); chainCerts[certId] = pkcs12Cert; if (unmarkedKey) { if (keyCerts.Count == 0) { byte[] hex = Hex.Encode(certId.Id); string name = Encoding.ASCII.GetString(hex, 0, hex.Length); keyCerts[name] = pkcs12Cert; object temp = keys["unmarked"]; keys.Remove("unmarked"); keys[name] = temp; } } else { if (localId != null) { byte[] hex = Hex.Encode(localId.GetOctets()); string name = Encoding.ASCII.GetString(hex, 0, hex.Length); keyCerts[name] = pkcs12Cert; } if (alias != null) { // TODO There may have been more than one alias certs[alias] = pkcs12Cert; } } } } public AsymmetricKeyEntry GetKey( string alias) { if (alias == null) throw new ArgumentNullException("alias"); return (AsymmetricKeyEntry)keys[alias]; } public bool IsCertificateEntry( string alias) { if (alias == null) throw new ArgumentNullException("alias"); return (certs[alias] != null && keys[alias] == null); } public bool IsKeyEntry( string alias) { if (alias == null) throw new ArgumentNullException("alias"); return (keys[alias] != null); } private Hashtable GetAliasesTable() { Hashtable tab = new Hashtable(); foreach (string key in certs.Keys) { tab[key] = "cert"; } foreach (string a in keys.Keys) { if (tab[a] == null) { tab[a] = "key"; } } return tab; } public IEnumerable Aliases { get { return new EnumerableProxy(GetAliasesTable().Keys); } } public bool ContainsAlias( string alias) { return certs[alias] != null || keys[alias] != null; } /** * simply return the cert entry for the private key */ public X509CertificateEntry GetCertificate( string alias) { if (alias == null) throw new ArgumentNullException("alias"); X509CertificateEntry c = (X509CertificateEntry) certs[alias]; // // look up the key table - and try the local key id // if (c == null) { string id = (string)localIds[alias]; if (id != null) { c = (X509CertificateEntry)keyCerts[id]; } else { c = (X509CertificateEntry)keyCerts[alias]; } } return c; } public string GetCertificateAlias( X509Certificate cert) { if (cert == null) throw new ArgumentNullException("cert"); foreach (DictionaryEntry entry in certs) { X509CertificateEntry entryValue = (X509CertificateEntry) entry.Value; if (entryValue.Certificate.Equals(cert)) { return (string) entry.Key; } } foreach (DictionaryEntry entry in keyCerts) { X509CertificateEntry entryValue = (X509CertificateEntry) entry.Value; if (entryValue.Certificate.Equals(cert)) { return (string) entry.Key; } } return null; } public X509CertificateEntry[] GetCertificateChain( string alias) { if (alias == null) throw new ArgumentNullException("alias"); if (!IsKeyEntry(alias)) { return null; } X509CertificateEntry c = GetCertificate(alias); if (c != null) { ArrayList cs = new ArrayList(); while (c != null) { X509Certificate x509c = c.Certificate; X509CertificateEntry nextC = null; Asn1OctetString ext = x509c.GetExtensionValue(X509Extensions.AuthorityKeyIdentifier); if (ext != null) { AuthorityKeyIdentifier id = AuthorityKeyIdentifier.GetInstance( Asn1Object.FromByteArray(ext.GetOctets())); if (id.GetKeyIdentifier() != null) { nextC = (X509CertificateEntry) chainCerts[new CertId(id.GetKeyIdentifier())]; } } if (nextC == null) { // // no authority key id, try the Issuer DN // X509Name i = x509c.IssuerDN; X509Name s = x509c.SubjectDN; if (!i.Equivalent(s)) { foreach (CertId certId in chainCerts.Keys) { X509CertificateEntry x509CertEntry = (X509CertificateEntry) chainCerts[certId]; X509Certificate crt = x509CertEntry.Certificate; X509Name sub = crt.SubjectDN; if (sub.Equivalent(i)) { try { x509c.Verify(crt.GetPublicKey()); nextC = x509CertEntry; break; } catch (InvalidKeyException) { // TODO What if it doesn't verify? } } } } } cs.Add(c); if (nextC != c) // self signed - end of the chain { c = nextC; } else { c = null; } } return (X509CertificateEntry[]) cs.ToArray(typeof(X509CertificateEntry)); } return null; } public void SetCertificateEntry( string alias, X509CertificateEntry certEntry) { if (alias == null) throw new ArgumentNullException("alias"); if (certEntry == null) throw new ArgumentNullException("certEntry"); if (keys[alias] != null) throw new ArgumentException("There is a key entry with the name " + alias + "."); certs[alias] = certEntry; chainCerts[new CertId(certEntry.Certificate.GetPublicKey())] = certEntry; } public void SetKeyEntry( string alias, AsymmetricKeyEntry keyEntry, X509CertificateEntry[] chain) { if (alias == null) throw new ArgumentNullException("alias"); if (keyEntry == null) throw new ArgumentNullException("keyEntry"); if (keyEntry.Key.IsPrivate && (chain == null)) throw new ArgumentException("No certificate chain for private key"); if (keys[alias] != null) { DeleteEntry(alias); } keys[alias] = keyEntry; certs[alias] = chain[0]; for (int i = 0; i != chain.Length; i++) { chainCerts[new CertId(chain[i].Certificate.GetPublicKey())] = chain[i]; } } public void DeleteEntry( string alias) { if (alias == null) throw new ArgumentNullException("alias"); AsymmetricKeyEntry k = (AsymmetricKeyEntry)keys[alias]; if (k != null) { keys.Remove(alias); } X509CertificateEntry c = (X509CertificateEntry)certs[alias]; if (c != null) { certs.Remove(alias); chainCerts.Remove(new CertId(c.Certificate.GetPublicKey())); } if (k != null) { string id = (string)localIds[alias]; if (id != null) { localIds.Remove(alias); c = (X509CertificateEntry)keyCerts[id]; } if (c != null) { keyCerts.Remove(id); chainCerts.Remove(new CertId(c.Certificate.GetPublicKey())); } } if (c == null && k == null) { throw new ArgumentException("no such entry as " + alias); } } public bool IsEntryOfType( string alias, Type entryType) { if (entryType == typeof(X509CertificateEntry)) return IsCertificateEntry(alias); if (entryType == typeof(AsymmetricKeyEntry)) return IsKeyEntry(alias) && GetCertificate(alias) != null; return false; } [Obsolete("Use 'Count' property instead")] public int Size() { return Count; } public int Count { // TODO Seems a little inefficient get { return GetAliasesTable().Count; } } public void Save( Stream stream, char[] password, SecureRandom random) { if (stream == null) throw new ArgumentNullException("stream"); if (password == null) throw new ArgumentNullException("password"); if (random == null) throw new ArgumentNullException("random"); // // handle the key // Asn1EncodableVector keyS = new Asn1EncodableVector(); foreach (string name in keys.Keys) { byte[] kSalt = new byte[SaltSize]; random.NextBytes(kSalt); AsymmetricKeyEntry privKey = (AsymmetricKeyEntry) keys[name]; EncryptedPrivateKeyInfo kInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( keyAlgorithm, password, kSalt, MinIterations, privKey.Key); Asn1EncodableVector kName = new Asn1EncodableVector(); foreach (string oid in privKey.BagAttributeKeys) { Asn1Encodable entry = privKey[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) continue; kName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { kName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { X509CertificateEntry ct = GetCertificate(name); AsymmetricKeyParameter pubKey = ct.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); kName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } SafeBag kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName)); keyS.Add(kBag); } byte[] derEncodedBytes = new DerSequence(keyS).GetDerEncoded(); BerOctetString keyString = new BerOctetString(derEncodedBytes); // // certificate processing // byte[] cSalt = new byte[SaltSize]; random.NextBytes(cSalt); Asn1EncodableVector certSeq = new Asn1EncodableVector(); Pkcs12PbeParams cParams = new Pkcs12PbeParams(cSalt, MinIterations); AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object()); ISet doneCerts = new HashSet(); foreach (string name in keys.Keys) { X509CertificateEntry certEntry = GetCertificate(name); CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509Certificate, new DerOctetString(certEntry.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in certEntry.BagAttributeKeys) { Asn1Encodable entry = certEntry[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) continue; fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'name' //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(name)))); } // // make sure we have a local key-id // if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null) { AsymmetricKeyParameter pubKey = certEntry.Certificate.GetPublicKey(); SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey); fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtLocalKeyID, new DerSet(subjectKeyID))); } SafeBag sBag = new SafeBag( PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(certEntry.Certificate); } foreach (string certId in certs.Keys) { X509CertificateEntry cert = (X509CertificateEntry)certs[certId]; if (keys[certId] != null) continue; CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) continue; Asn1Encodable entry = cert[oid]; // NB: Ignore any existing FriendlyName if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id)) continue; fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(entry))); } // // make sure we are using the local alias on store // // NB: We always set the FriendlyName based on 'certId' //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null) { fName.Add( new DerSequence( PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(certId)))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); doneCerts.Add(cert.Certificate); } foreach (CertId certId in chainCerts.Keys) { X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId]; if (doneCerts.Contains(cert.Certificate)) continue; CertBag cBag = new CertBag( PkcsObjectIdentifiers.X509Certificate, new DerOctetString(cert.Certificate.GetEncoded())); Asn1EncodableVector fName = new Asn1EncodableVector(); foreach (string oid in cert.BagAttributeKeys) { // a certificate not immediately linked to a key doesn't require // a localKeyID and will confuse some PKCS12 implementations. // // If we find one, we'll prune it out. if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id)) continue; fName.Add( new DerSequence( new DerObjectIdentifier(oid), new DerSet(cert[oid]))); } SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)); certSeq.Add(sBag); } derEncodedBytes = new DerSequence(certSeq).GetDerEncoded(); byte[] certBytes = CryptPbeData(true, cAlgId, password, false, derEncodedBytes); EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes)); ContentInfo[] info = new ContentInfo[] { new ContentInfo(PkcsObjectIdentifiers.Data, keyString), new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object()) }; byte[] data = new AuthenticatedSafe(info).GetEncoded(); ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data)); // // create the mac // byte[] mSalt = new byte[20]; random.NextBytes(mSalt); byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1, mSalt, MinIterations, password, false, data); AlgorithmIdentifier algId = new AlgorithmIdentifier( OiwObjectIdentifiers.IdSha1, DerNull.Instance); DigestInfo dInfo = new DigestInfo(algId, mac); MacData mData = new MacData(dInfo, mSalt, MinIterations); // // output the Pfx // Pfx pfx = new Pfx(mainInfo, mData); BerOutputStream berOut = new BerOutputStream(stream); berOut.WriteObject(pfx); } private static byte[] CalculatePbeMac( DerObjectIdentifier oid, byte[] salt, int itCount, char[] password, bool wrongPkcs12Zero, byte[] data) { Asn1Encodable asn1Params = PbeUtilities.GenerateAlgorithmParameters( oid, salt, itCount); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters( oid, password, wrongPkcs12Zero, asn1Params); IMac mac = (IMac) PbeUtilities.CreateEngine(oid); mac.Init(cipherParams); mac.BlockUpdate(data, 0, data.Length); return MacUtilities.DoFinal(mac); } private static byte[] CryptPbeData( bool forEncryption, AlgorithmIdentifier algId, char[] password, bool wrongPkcs12Zero, byte[] data) { Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(algId.Parameters); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters( algId.ObjectID, password, wrongPkcs12Zero, pbeParams); IBufferedCipher cipher = PbeUtilities.CreateEngine(algId.ObjectID) as IBufferedCipher; if (cipher == null) throw new Exception("Unknown encryption algorithm: " + algId.ObjectID); cipher.Init(forEncryption, cipherParams); return cipher.DoFinal(data); } private class IgnoresCaseHashtable : IEnumerable { private readonly Hashtable orig = new Hashtable(); private readonly Hashtable keys = new Hashtable(); public void Clear() { orig.Clear(); keys.Clear(); } public IEnumerator GetEnumerator() { return orig.GetEnumerator(); } public ICollection Keys { get { return orig.Keys; } } public object Remove( string alias) { string lower = alias.ToLower(CultureInfo.InvariantCulture); string k = (string) keys[lower]; if (k == null) return null; keys.Remove(lower); object o = orig[k]; orig.Remove(k); return o; } public object this[ string alias] { get { string lower = alias.ToLower(CultureInfo.InvariantCulture); string k = (string) keys[lower]; if (k == null) return null; return orig[k]; } set { string lower = alias.ToLower(CultureInfo.InvariantCulture); string k = (string) keys[lower]; if (k != null) { orig.Remove(k); } keys[lower] = alias; orig[alias] = value; } } public ICollection Values { get { return orig.Values; } } } } }
/* * 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 Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; // using log4net; // using System.Reflection; /***************************************************** * * WorldCommModule * * * Holding place for world comms - basically llListen * function implementation. * * lLListen(integer channel, string name, key id, string msg) * The name, id, and msg arguments specify the filtering * criteria. You can pass the empty string * (or NULL_KEY for id) for these to set a completely * open filter; this causes the listen() event handler to be * invoked for all chat on the channel. To listen only * for chat spoken by a specific object or avatar, * specify the name and/or id arguments. To listen * only for a specific command, specify the * (case-sensitive) msg argument. If msg is not empty, * listener will only hear strings which are exactly equal * to msg. You can also use all the arguments to establish * the most restrictive filtering criteria. * * It might be useful for each listener to maintain a message * digest, with a list of recent messages by UUID. This can * be used to prevent in-world repeater loops. However, the * linden functions do not have this capability, so for now * thats the way it works. * Instead it blocks messages originating from the same prim. * (not Object!) * * For LSL compliance, note the following: * (Tested again 1.21.1 on May 2, 2008) * 1. 'id' has to be parsed into a UUID. None-UUID keys are * to be replaced by the ZeroID key. (Well, TryParse does * that for us. * 2. Setting up an listen event from the same script, with the * same filter settings (including step 1), returns the same * handle as the original filter. * 3. (TODO) handles should be script-local. Starting from 1. * Might be actually easier to map the global handle into * script-local handle in the ScriptEngine. Not sure if its * worth the effort tho. * * **************************************************/ namespace OpenSim.Region.CoreModules.Scripting.WorldComm { public class WorldCommModule : IRegionModule, IWorldComm { // private static readonly ILog m_log = // LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ListenerManager m_listenerManager; private Queue m_pending; private Queue m_pendingQ; private Scene m_scene; private int m_whisperdistance = 10; private int m_saydistance = 30; private int m_shoutdistance = 100; #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { // wrap this in a try block so that defaults will work if // the config file doesn't specify otherwise. int maxlisteners = 1000; int maxhandles = 64; try { m_whisperdistance = config.Configs["Chat"].GetInt("whisper_distance", m_whisperdistance); m_saydistance = config.Configs["Chat"].GetInt("say_distance", m_saydistance); m_shoutdistance = config.Configs["Chat"].GetInt("shout_distance", m_shoutdistance); maxlisteners = config.Configs["LL-Functions"].GetInt("max_listens_per_region", maxlisteners); maxhandles = config.Configs["LL-Functions"].GetInt("max_listens_per_script", maxhandles); } catch (Exception) { } if (maxlisteners < 1) maxlisteners = int.MaxValue; if (maxhandles < 1) maxhandles = int.MaxValue; m_scene = scene; m_scene.RegisterModuleInterface<IWorldComm>(this); m_listenerManager = new ListenerManager(maxlisteners, maxhandles); m_scene.EventManager.OnChatFromClient += DeliverClientMessage; m_scene.EventManager.OnChatBroadcast += DeliverClientMessage; m_pendingQ = new Queue(); m_pending = Queue.Synchronized(m_pendingQ); } public void PostInitialise() { } public void Close() { } public string Name { get { return "WorldCommModule"; } } public bool IsSharedModule { get { return false; } } #endregion #region IWorldComm Members /// <summary> /// Create a listen event callback with the specified filters. /// The parameters localID,itemID are needed to uniquely identify /// the script during 'peek' time. Parameter hostID is needed to /// determine the position of the script. /// </summary> /// <param name="localID">localID of the script engine</param> /// <param name="itemID">UUID of the script engine</param> /// <param name="hostID">UUID of the SceneObjectPart</param> /// <param name="channel">channel to listen on</param> /// <param name="name">name to filter on</param> /// <param name="id">key to filter on (user given, could be totally faked)</param> /// <param name="msg">msg to filter on</param> /// <returns>number of the scripts handle</returns> public int Listen(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg) { return m_listenerManager.AddListener(localID, itemID, hostID, channel, name, id, msg); } /// <summary> /// Sets the listen event with handle as active (active = TRUE) or inactive (active = FALSE). /// The handle used is returned from Listen() /// </summary> /// <param name="itemID">UUID of the script engine</param> /// <param name="handle">handle returned by Listen()</param> /// <param name="active">temp. activate or deactivate the Listen()</param> public void ListenControl(UUID itemID, int handle, int active) { if (active == 1) m_listenerManager.Activate(itemID, handle); else if (active == 0) m_listenerManager.Dectivate(itemID, handle); } /// <summary> /// Removes the listen event callback with handle /// </summary> /// <param name="itemID">UUID of the script engine</param> /// <param name="handle">handle returned by Listen()</param> public void ListenRemove(UUID itemID, int handle) { m_listenerManager.Remove(itemID, handle); } /// <summary> /// Removes all listen event callbacks for the given itemID /// (script engine) /// </summary> /// <param name="itemID">UUID of the script engine</param> public void DeleteListener(UUID itemID) { m_listenerManager.DeleteListener(itemID); } protected static Vector3 CenterOfRegion = new Vector3(128, 128, 20); public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg) { Vector3 position; SceneObjectPart source; ScenePresence avatar; if ((source = m_scene.GetSceneObjectPart(id)) != null) position = source.AbsolutePosition; else if ((avatar = m_scene.GetScenePresence(id)) != null) position = avatar.AbsolutePosition; else if (ChatTypeEnum.Region == type) position = CenterOfRegion; else return; DeliverMessage(type, channel, name, id, msg, position); } /// <summary> /// This method scans over the objects which registered an interest in listen callbacks. /// For everyone it finds, it checks if it fits the given filter. If it does, then /// enqueue the message for delivery to the objects listen event handler. /// The enqueued ListenerInfo no longer has filter values, but the actually trigged values. /// Objects that do an llSay have their messages delivered here and for nearby avatars, /// the OnChatFromClient event is used. /// </summary> /// <param name="type">type of delvery (whisper,say,shout or regionwide)</param> /// <param name="channel">channel to sent on</param> /// <param name="name">name of sender (object or avatar)</param> /// <param name="id">key of sender (object or avatar)</param> /// <param name="msg">msg to sent</param> public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg, Vector3 position) { // m_log.DebugFormat("[WorldComm] got[2] type {0}, channel {1}, name {2}, id {3}, msg {4}", // type, channel, name, id, msg); // Determine which listen event filters match the given set of arguments, this results // in a limited set of listeners, each belonging a host. If the host is in range, add them // to the pending queue. foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg)) { // Dont process if this message is from yourself! if (li.GetHostID().Equals(id)) continue; SceneObjectPart sPart = m_scene.GetSceneObjectPart(li.GetHostID()); if (sPart == null) continue; double dis = Util.GetDistanceTo(sPart.AbsolutePosition, position); switch (type) { case ChatTypeEnum.Whisper: if (dis < m_whisperdistance) { lock (m_pending.SyncRoot) { m_pending.Enqueue(new ListenerInfo(li,name,id,msg)); } } break; case ChatTypeEnum.Say: if (dis < m_saydistance) { lock (m_pending.SyncRoot) { m_pending.Enqueue(new ListenerInfo(li,name,id,msg)); } } break; case ChatTypeEnum.Shout: if (dis < m_shoutdistance) { lock (m_pending.SyncRoot) { m_pending.Enqueue(new ListenerInfo(li,name,id,msg)); } } break; case ChatTypeEnum.Region: lock (m_pending.SyncRoot) { m_pending.Enqueue(new ListenerInfo(li,name,id,msg)); } break; } } } /// <summary> /// Are there any listen events ready to be dispatched? /// </summary> /// <returns>boolean indication</returns> public bool HasMessages() { return (m_pending.Count > 0); } /// <summary> /// Pop the first availlable listen event from the queue /// </summary> /// <returns>ListenerInfo with filter filled in</returns> public IWorldCommListenerInfo GetNextMessage() { ListenerInfo li = null; lock (m_pending.SyncRoot) { li = (ListenerInfo) m_pending.Dequeue(); } return li; } #endregion /******************************************************************** * * Listener Stuff * * *****************************************************************/ private void DeliverClientMessage(Object sender, OSChatMessage e) { if (null != e.Sender) DeliverMessage(e.Type, e.Channel, e.Sender.Name, e.Sender.AgentId, e.Message, e.Position); else DeliverMessage(e.Type, e.Channel, e.From, UUID.Zero, e.Message, e.Position); } public Object[] GetSerializationData(UUID itemID) { return m_listenerManager.GetSerializationData(itemID); } public void CreateFromData(uint localID, UUID itemID, UUID hostID, Object[] data) { m_listenerManager.AddFromData(localID, itemID, hostID, data); } } public class ListenerManager { private Dictionary<int, List<ListenerInfo>> m_listeners = new Dictionary<int, List<ListenerInfo>>(); private int m_maxlisteners; private int m_maxhandles; private int m_curlisteners; public ListenerManager(int maxlisteners, int maxhandles) { m_maxlisteners = maxlisteners; m_maxhandles = maxhandles; m_curlisteners = 0; } public int AddListener(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg) { // do we already have a match on this particular filter event? List<ListenerInfo> coll = GetListeners(itemID, channel, name, id, msg); if (coll.Count > 0) { // special case, called with same filter settings, return same handle // (2008-05-02, tested on 1.21.1 server, still holds) return coll[0].GetHandle(); } if (m_curlisteners < m_maxlisteners) { lock (m_listeners) { int newHandle = GetNewHandle(itemID); if (newHandle > 0) { ListenerInfo li = new ListenerInfo(newHandle, localID, itemID, hostID, channel, name, id, msg); List<ListenerInfo> listeners; if (!m_listeners.TryGetValue(channel,out listeners)) { listeners = new List<ListenerInfo>(); m_listeners.Add(channel, listeners); } listeners.Add(li); m_curlisteners++; return newHandle; } } } return -1; } public void Remove(UUID itemID, int handle) { lock (m_listeners) { foreach (KeyValuePair<int,List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle().Equals(handle)) { lis.Value.Remove(li); if (lis.Value.Count == 0) { m_listeners.Remove(lis.Key); m_curlisteners--; } // there should be only one, so we bail out early return; } } } } } public void DeleteListener(UUID itemID) { List<int> emptyChannels = new List<int>(); List<ListenerInfo> removedListeners = new List<ListenerInfo>(); lock (m_listeners) { foreach (KeyValuePair<int,List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID)) { // store them first, else the enumerated bails on us removedListeners.Add(li); } } foreach (ListenerInfo li in removedListeners) { lis.Value.Remove(li); m_curlisteners--; } removedListeners.Clear(); if (lis.Value.Count == 0) { // again, store first, remove later emptyChannels.Add(lis.Key); } } foreach (int channel in emptyChannels) { m_listeners.Remove(channel); } } } public void Activate(UUID itemID, int handle) { lock (m_listeners) { foreach (KeyValuePair<int,List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle() == handle) { li.Activate(); // only one, bail out return; } } } } } public void Dectivate(UUID itemID, int handle) { lock (m_listeners) { foreach (KeyValuePair<int,List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle() == handle) { li.Deactivate(); // only one, bail out return; } } } } } // non-locked access, since its always called in the context of the lock private int GetNewHandle(UUID itemID) { List<int> handles = new List<int>(); // build a list of used keys for this specific itemID... foreach (KeyValuePair<int,List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID)) handles.Add(li.GetHandle()); } } // Note: 0 is NOT a valid handle for llListen() to return for (int i = 1; i <= m_maxhandles; i++) { if (!handles.Contains(i)) return i; } return -1; } // Theres probably a more clever and efficient way to // do this, maybe with regex. // PM2008: Ha, one could even be smart and define a specialized Enumerator. public List<ListenerInfo> GetListeners(UUID itemID, int channel, string name, UUID id, string msg) { List<ListenerInfo> collection = new List<ListenerInfo>(); lock (m_listeners) { List<ListenerInfo> listeners; if (!m_listeners.TryGetValue(channel,out listeners)) { return collection; } foreach (ListenerInfo li in listeners) { if (!li.IsActive()) { continue; } if (!itemID.Equals(UUID.Zero) && !li.GetItemID().Equals(itemID)) { continue; } if (li.GetName().Length > 0 && !li.GetName().Equals(name)) { continue; } if (!li.GetID().Equals(UUID.Zero) && !li.GetID().Equals(id)) { continue; } if (li.GetMessage().Length > 0 && !li.GetMessage().Equals(msg)) { continue; } collection.Add(li); } } return collection; } public Object[] GetSerializationData(UUID itemID) { List<Object> data = new List<Object>(); lock (m_listeners) { foreach (List<ListenerInfo> list in m_listeners.Values) { foreach (ListenerInfo l in list) { if (l.GetItemID() == itemID) data.AddRange(l.GetSerializationData()); } } } return (Object[])data.ToArray(); } public void AddFromData(uint localID, UUID itemID, UUID hostID, Object[] data) { int idx = 0; Object[] item = new Object[6]; while (idx < data.Length) { Array.Copy(data, idx, item, 0, 6); ListenerInfo info = ListenerInfo.FromData(localID, itemID, hostID, item); if (!m_listeners.ContainsKey((int)item[2])) m_listeners.Add((int)item[2], new List<ListenerInfo>()); m_listeners[(int)item[2]].Add(info); idx+=6; } } } public class ListenerInfo: IWorldCommListenerInfo { private bool m_active; // Listener is active or not private int m_handle; // Assigned handle of this listener private uint m_localID; // Local ID from script engine private UUID m_itemID; // ID of the host script engine private UUID m_hostID; // ID of the host/scene part private int m_channel; // Channel private UUID m_id; // ID to filter messages from private string m_name; // Object name to filter messages from private string m_message; // The message public ListenerInfo(int handle, uint localID, UUID ItemID, UUID hostID, int channel, string name, UUID id, string message) { Initialise(handle, localID, ItemID, hostID, channel, name, id, message); } public ListenerInfo(ListenerInfo li, string name, UUID id, string message) { Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID, li.m_channel, name, id, message); } private void Initialise(int handle, uint localID, UUID ItemID, UUID hostID, int channel, string name, UUID id, string message) { m_active = true; m_handle = handle; m_localID = localID; m_itemID = ItemID; m_hostID = hostID; m_channel = channel; m_name = name; m_id = id; m_message = message; } public Object[] GetSerializationData() { Object[] data = new Object[6]; data[0] = m_active; data[1] = m_handle; data[2] = m_channel; data[3] = m_name; data[4] = m_id; data[5] = m_message; return data; } public static ListenerInfo FromData(uint localID, UUID ItemID, UUID hostID, Object[] data) { ListenerInfo linfo = new ListenerInfo((int)data[1], localID, ItemID, hostID, (int)data[2], (string)data[3], (UUID)data[4], (string)data[5]); linfo.m_active=(bool)data[0]; return linfo; } public UUID GetItemID() { return m_itemID; } public UUID GetHostID() { return m_hostID; } public int GetChannel() { return m_channel; } public uint GetLocalID() { return m_localID; } public int GetHandle() { return m_handle; } public string GetMessage() { return m_message; } public string GetName() { return m_name; } public bool IsActive() { return m_active; } public void Deactivate() { m_active = false; } public void Activate() { m_active = true; } public UUID GetID() { return m_id; } } }
// 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. #if ES_BUILD_STANDALONE using System; using System.Diagnostics; #endif using System.Collections.Generic; using System.Reflection; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: Type handler for empty or unsupported types. /// </summary> internal sealed class NullTypeInfo : TraceLoggingTypeInfo { public NullTypeInfo() : base(typeof(EmptyStruct)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { collector.AddGroup(name); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { return; } public override object? GetData(object? value) { return null; } } /// <summary> /// Type handler for simple scalar types. /// </summary> internal sealed class ScalarTypeInfo : TraceLoggingTypeInfo { private readonly Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc; private readonly TraceLoggingDataType nativeFormat; private ScalarTypeInfo( Type type, Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc, TraceLoggingDataType nativeFormat) : base(type) { this.formatFunc = formatFunc; this.nativeFormat = nativeFormat; } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { collector.AddScalar(name!, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar(value); } public static TraceLoggingTypeInfo Boolean() { return new ScalarTypeInfo(typeof(bool), Statics.Format8, TraceLoggingDataType.Boolean8); } public static TraceLoggingTypeInfo Byte() { return new ScalarTypeInfo(typeof(byte), Statics.Format8, TraceLoggingDataType.UInt8); } public static TraceLoggingTypeInfo SByte() { return new ScalarTypeInfo(typeof(sbyte), Statics.Format8, TraceLoggingDataType.Int8); } public static TraceLoggingTypeInfo Char() { return new ScalarTypeInfo(typeof(char), Statics.Format16, TraceLoggingDataType.Char16); } public static TraceLoggingTypeInfo Int16() { return new ScalarTypeInfo(typeof(short), Statics.Format16, TraceLoggingDataType.Int16); } public static TraceLoggingTypeInfo UInt16() { return new ScalarTypeInfo(typeof(ushort), Statics.Format16, TraceLoggingDataType.UInt16); } public static TraceLoggingTypeInfo Int32() { return new ScalarTypeInfo(typeof(int), Statics.Format32, TraceLoggingDataType.Int32); } public static TraceLoggingTypeInfo UInt32() { return new ScalarTypeInfo(typeof(uint), Statics.Format32, TraceLoggingDataType.UInt32); } public static TraceLoggingTypeInfo Int64() { return new ScalarTypeInfo(typeof(long), Statics.Format64, TraceLoggingDataType.Int64); } public static TraceLoggingTypeInfo UInt64() { return new ScalarTypeInfo(typeof(ulong), Statics.Format64, TraceLoggingDataType.UInt64); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarTypeInfo(typeof(IntPtr), Statics.FormatPtr, Statics.IntPtrType); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarTypeInfo(typeof(UIntPtr), Statics.FormatPtr, Statics.UIntPtrType); } public static TraceLoggingTypeInfo Single() { return new ScalarTypeInfo(typeof(float), Statics.Format32, TraceLoggingDataType.Float); } public static TraceLoggingTypeInfo Double() { return new ScalarTypeInfo(typeof(double), Statics.Format64, TraceLoggingDataType.Double); } public static TraceLoggingTypeInfo Guid() { return new ScalarTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid); } } /// <summary> /// Type handler for arrays of scalars /// </summary> internal sealed class ScalarArrayTypeInfo : TraceLoggingTypeInfo { private readonly Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc; private readonly TraceLoggingDataType nativeFormat; private readonly int elementSize; private ScalarArrayTypeInfo( Type type, Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc, TraceLoggingDataType nativeFormat, int elementSize) : base(type) { this.formatFunc = formatFunc; this.nativeFormat = nativeFormat; this.elementSize = elementSize; } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { collector.AddArray(name!, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddArray(value, elementSize); } public static TraceLoggingTypeInfo Boolean() { return new ScalarArrayTypeInfo(typeof(bool[]), Statics.Format8, TraceLoggingDataType.Boolean8, sizeof(bool)); } public static TraceLoggingTypeInfo Byte() { return new ScalarArrayTypeInfo(typeof(byte[]), Statics.Format8, TraceLoggingDataType.UInt8, sizeof(byte)); } public static TraceLoggingTypeInfo SByte() { return new ScalarArrayTypeInfo(typeof(sbyte[]), Statics.Format8, TraceLoggingDataType.Int8, sizeof(sbyte)); } public static TraceLoggingTypeInfo Char() { return new ScalarArrayTypeInfo(typeof(char[]), Statics.Format16, TraceLoggingDataType.Char16, sizeof(char)); } public static TraceLoggingTypeInfo Int16() { return new ScalarArrayTypeInfo(typeof(short[]), Statics.Format16, TraceLoggingDataType.Int16, sizeof(short)); } public static TraceLoggingTypeInfo UInt16() { return new ScalarArrayTypeInfo(typeof(ushort[]), Statics.Format16, TraceLoggingDataType.UInt16, sizeof(ushort)); } public static TraceLoggingTypeInfo Int32() { return new ScalarArrayTypeInfo(typeof(int[]), Statics.Format32, TraceLoggingDataType.Int32, sizeof(int)); } public static TraceLoggingTypeInfo UInt32() { return new ScalarArrayTypeInfo(typeof(uint[]), Statics.Format32, TraceLoggingDataType.UInt32, sizeof(uint)); } public static TraceLoggingTypeInfo Int64() { return new ScalarArrayTypeInfo(typeof(long[]), Statics.Format64, TraceLoggingDataType.Int64, sizeof(long)); } public static TraceLoggingTypeInfo UInt64() { return new ScalarArrayTypeInfo(typeof(ulong[]), Statics.Format64, TraceLoggingDataType.UInt64, sizeof(ulong)); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarArrayTypeInfo(typeof(IntPtr[]), Statics.FormatPtr, Statics.IntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarArrayTypeInfo(typeof(UIntPtr[]), Statics.FormatPtr, Statics.UIntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo Single() { return new ScalarArrayTypeInfo(typeof(float[]), Statics.Format32, TraceLoggingDataType.Float, sizeof(float)); } public static TraceLoggingTypeInfo Double() { return new ScalarArrayTypeInfo(typeof(double[]), Statics.Format64, TraceLoggingDataType.Double, sizeof(double)); } public static unsafe TraceLoggingTypeInfo Guid() { return new ScalarArrayTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid, sizeof(Guid)); } } /// <summary> /// TraceLogging: Type handler for String. /// </summary> internal sealed class StringTypeInfo : TraceLoggingTypeInfo { public StringTypeInfo() : base(typeof(string)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { collector.AddNullTerminatedString(name!, Statics.MakeDataType(TraceLoggingDataType.Utf16String, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddNullTerminatedString((string?)value.ReferenceValue); } public override object GetData(object? value) { if (value == null) { return ""; } return value; } } /// <summary> /// TraceLogging: Type handler for DateTime. /// </summary> internal sealed class DateTimeTypeInfo : TraceLoggingTypeInfo { public DateTimeTypeInfo() : base(typeof(DateTime)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { collector.AddScalar(name!, Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { DateTime dateTime = value.ScalarValue.AsDateTime; const long UTCMinTicks = 504911232000000000; long dateTimeTicks = 0; // We cannot translate dates sooner than 1/1/1601 in UTC. // To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks if (dateTime.Ticks > UTCMinTicks) dateTimeTicks = dateTime.ToFileTimeUtc(); collector.AddScalar(dateTimeTicks); } } /// <summary> /// TraceLogging: Type handler for DateTimeOffset. /// </summary> internal sealed class DateTimeOffsetTypeInfo : TraceLoggingTypeInfo { public DateTimeOffsetTypeInfo() : base(typeof(DateTimeOffset)) { } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { TraceLoggingMetadataCollector group = collector.AddGroup(name); group.AddScalar("Ticks", Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); group.AddScalar("Offset", TraceLoggingDataType.Int64); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { DateTimeOffset dateTimeOffset = value.ScalarValue.AsDateTimeOffset; long ticks = dateTimeOffset.Ticks; collector.AddScalar(ticks < 504911232000000000 ? 0 : ticks - 504911232000000000); collector.AddScalar(dateTimeOffset.Offset.Ticks); } } /// <summary> /// TraceLogging: Type handler for TimeSpan. /// </summary> internal sealed class TimeSpanTypeInfo : TraceLoggingTypeInfo { public TimeSpanTypeInfo() : base(typeof(TimeSpan)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { collector.AddScalar(name!, Statics.MakeDataType(TraceLoggingDataType.Int64, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar(value.ScalarValue.AsTimeSpan.Ticks); } } /// <summary> /// TraceLogging: Type handler for decimal. (Note: not full-fidelity, exposed as Double.) /// </summary> internal sealed class DecimalTypeInfo : TraceLoggingTypeInfo { public DecimalTypeInfo() : base(typeof(decimal)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { collector.AddScalar(name!, Statics.MakeDataType(TraceLoggingDataType.Double, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar((double)value.ScalarValue.AsDecimal); } } /// <summary> /// TraceLogging: Type handler for Nullable. /// </summary> internal sealed class NullableTypeInfo : TraceLoggingTypeInfo { private readonly TraceLoggingTypeInfo valueInfo; private readonly Func<PropertyValue, PropertyValue> valueGetter; public NullableTypeInfo(Type type, List<Type> recursionCheck) : base(type) { Type[] typeArgs = type.GenericTypeArguments; Debug.Assert(typeArgs.Length == 1); this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck); this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value")!); } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { TraceLoggingMetadataCollector group = collector.AddGroup(name); group.AddScalar("HasValue", TraceLoggingDataType.Boolean8); this.valueInfo.WriteMetadata(group, "Value", format); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { // It's not currently possible to get the HasValue property of a nullable type through reflection when the // value is null. Instead, we simply check that the nullable is not null. bool hasValue = value.ReferenceValue != null; collector.AddScalar(hasValue); PropertyValue val = hasValue ? valueGetter(value) : valueInfo.PropertyValueFactory(Activator.CreateInstance(valueInfo.DataType)); this.valueInfo.WriteData(collector, val); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/channels/travel_agent.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Booking.Channels { /// <summary>Holder for reflection information generated from booking/channels/travel_agent.proto</summary> public static partial class TravelAgentReflection { #region Descriptor /// <summary>File descriptor for booking/channels/travel_agent.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TravelAgentReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiNib29raW5nL2NoYW5uZWxzL3RyYXZlbF9hZ2VudC5wcm90bxIcaG9sbXMu", "dHlwZXMuYm9va2luZy5jaGFubmVscxomYm9va2luZy9jaGFubmVscy9jb21t", "aXNzaW9uX3R5cGUucHJvdG8aL2Jvb2tpbmcvaW5kaWNhdG9ycy90cmF2ZWxf", "YWdlbnRfaW5kaWNhdG9yLnByb3RvGiFwcmltaXRpdmUvZml4ZWRfcG9pbnRf", "cmF0aW8ucHJvdG8aH3ByaW1pdGl2ZS9tb25ldGFyeV9hbW91bnQucHJvdG8i", "0AQKC1RyYXZlbEFnZW50EkcKCWVudGl0eV9pZBgBIAEoCzI0LmhvbG1zLnR5", "cGVzLmJvb2tpbmcuaW5kaWNhdG9ycy5UcmF2ZWxBZ2VudEluZGljYXRvchIP", "CgdpYXRhX2lkGAIgASgJEkUKD2NvbW1pc3Npb25fdHlwZRgDIAEoDjIsLmhv", "bG1zLnR5cGVzLmJvb2tpbmcuY2hhbm5lbHMuQ29tbWlzc2lvblR5cGUSQAoR", "Y29tbWlzc2lvbl9hbW91bnQYBCABKAsyJS5ob2xtcy50eXBlcy5wcmltaXRp", "dmUuTW9uZXRhcnlBbW91bnQSRQoVY29tbWlzc2lvbl9wZXJjZW50YWdlGAUg", "ASgLMiYuaG9sbXMudHlwZXMucHJpbWl0aXZlLkZpeGVkUG9pbnRSYXRpbxIS", "CgpnaXZlbl9uYW1lGAYgASgJEhMKC2ZhbWlseV9uYW1lGAcgASgJEhkKEWJ1", "c2luZXNzX2FkZHJlc3MxGAggASgJEhkKEWJ1c2luZXNzX2FkZHJlc3MyGAkg", "ASgJEhUKDWJ1c2luZXNzX2NpdHkYCiABKAkSFgoOYnVzaW5lc3Nfc3RhdGUY", "CyABKAkSFAoMYnVzaW5lc3NfemlwGAwgASgJEhcKD2J1c2luZXNzX25hdGlv", "bhgNIAEoCRIdChVidXNpbmVzc19waG9uZV9udW1iZXIYDiABKAkSGwoTYnVz", "aW5lc3NfZmF4X251bWJlchgPIAEoCRIeChZidXNpbmVzc19lbWFpbF9hZGRy", "ZXNzGBAgASgJQjFaEGJvb2tpbmcvY2hhbm5lbHOqAhxIT0xNUy5UeXBlcy5C", "b29raW5nLkNoYW5uZWxzYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Channels.CommissionTypeReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.TravelAgentIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.FixedPointRatioReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Channels.TravelAgent), global::HOLMS.Types.Booking.Channels.TravelAgent.Parser, new[]{ "EntityId", "IataId", "CommissionType", "CommissionAmount", "CommissionPercentage", "GivenName", "FamilyName", "BusinessAddress1", "BusinessAddress2", "BusinessCity", "BusinessState", "BusinessZip", "BusinessNation", "BusinessPhoneNumber", "BusinessFaxNumber", "BusinessEmailAddress" }, null, null, null) })); } #endregion } #region Messages public sealed partial class TravelAgent : pb::IMessage<TravelAgent> { private static readonly pb::MessageParser<TravelAgent> _parser = new pb::MessageParser<TravelAgent>(() => new TravelAgent()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TravelAgent> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.Channels.TravelAgentReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TravelAgent() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TravelAgent(TravelAgent other) : this() { EntityId = other.entityId_ != null ? other.EntityId.Clone() : null; iataId_ = other.iataId_; commissionType_ = other.commissionType_; CommissionAmount = other.commissionAmount_ != null ? other.CommissionAmount.Clone() : null; CommissionPercentage = other.commissionPercentage_ != null ? other.CommissionPercentage.Clone() : null; givenName_ = other.givenName_; familyName_ = other.familyName_; businessAddress1_ = other.businessAddress1_; businessAddress2_ = other.businessAddress2_; businessCity_ = other.businessCity_; businessState_ = other.businessState_; businessZip_ = other.businessZip_; businessNation_ = other.businessNation_; businessPhoneNumber_ = other.businessPhoneNumber_; businessFaxNumber_ = other.businessFaxNumber_; businessEmailAddress_ = other.businessEmailAddress_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TravelAgent Clone() { return new TravelAgent(this); } /// <summary>Field number for the "entity_id" field.</summary> public const int EntityIdFieldNumber = 1; private global::HOLMS.Types.Booking.Indicators.TravelAgentIndicator entityId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.TravelAgentIndicator EntityId { get { return entityId_; } set { entityId_ = value; } } /// <summary>Field number for the "iata_id" field.</summary> public const int IataIdFieldNumber = 2; private string iataId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string IataId { get { return iataId_; } set { iataId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "commission_type" field.</summary> public const int CommissionTypeFieldNumber = 3; private global::HOLMS.Types.Booking.Channels.CommissionType commissionType_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Channels.CommissionType CommissionType { get { return commissionType_; } set { commissionType_ = value; } } /// <summary>Field number for the "commission_amount" field.</summary> public const int CommissionAmountFieldNumber = 4; private global::HOLMS.Types.Primitive.MonetaryAmount commissionAmount_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount CommissionAmount { get { return commissionAmount_; } set { commissionAmount_ = value; } } /// <summary>Field number for the "commission_percentage" field.</summary> public const int CommissionPercentageFieldNumber = 5; private global::HOLMS.Types.Primitive.FixedPointRatio commissionPercentage_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.FixedPointRatio CommissionPercentage { get { return commissionPercentage_; } set { commissionPercentage_ = value; } } /// <summary>Field number for the "given_name" field.</summary> public const int GivenNameFieldNumber = 6; private string givenName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string GivenName { get { return givenName_; } set { givenName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "family_name" field.</summary> public const int FamilyNameFieldNumber = 7; private string familyName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string FamilyName { get { return familyName_; } set { familyName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "business_address1" field.</summary> public const int BusinessAddress1FieldNumber = 8; private string businessAddress1_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BusinessAddress1 { get { return businessAddress1_; } set { businessAddress1_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "business_address2" field.</summary> public const int BusinessAddress2FieldNumber = 9; private string businessAddress2_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BusinessAddress2 { get { return businessAddress2_; } set { businessAddress2_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "business_city" field.</summary> public const int BusinessCityFieldNumber = 10; private string businessCity_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BusinessCity { get { return businessCity_; } set { businessCity_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "business_state" field.</summary> public const int BusinessStateFieldNumber = 11; private string businessState_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BusinessState { get { return businessState_; } set { businessState_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "business_zip" field.</summary> public const int BusinessZipFieldNumber = 12; private string businessZip_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BusinessZip { get { return businessZip_; } set { businessZip_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "business_nation" field.</summary> public const int BusinessNationFieldNumber = 13; private string businessNation_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BusinessNation { get { return businessNation_; } set { businessNation_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "business_phone_number" field.</summary> public const int BusinessPhoneNumberFieldNumber = 14; private string businessPhoneNumber_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BusinessPhoneNumber { get { return businessPhoneNumber_; } set { businessPhoneNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "business_fax_number" field.</summary> public const int BusinessFaxNumberFieldNumber = 15; private string businessFaxNumber_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BusinessFaxNumber { get { return businessFaxNumber_; } set { businessFaxNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "business_email_address" field.</summary> public const int BusinessEmailAddressFieldNumber = 16; private string businessEmailAddress_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BusinessEmailAddress { get { return businessEmailAddress_; } set { businessEmailAddress_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TravelAgent); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TravelAgent other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(EntityId, other.EntityId)) return false; if (IataId != other.IataId) return false; if (CommissionType != other.CommissionType) return false; if (!object.Equals(CommissionAmount, other.CommissionAmount)) return false; if (!object.Equals(CommissionPercentage, other.CommissionPercentage)) return false; if (GivenName != other.GivenName) return false; if (FamilyName != other.FamilyName) return false; if (BusinessAddress1 != other.BusinessAddress1) return false; if (BusinessAddress2 != other.BusinessAddress2) return false; if (BusinessCity != other.BusinessCity) return false; if (BusinessState != other.BusinessState) return false; if (BusinessZip != other.BusinessZip) return false; if (BusinessNation != other.BusinessNation) return false; if (BusinessPhoneNumber != other.BusinessPhoneNumber) return false; if (BusinessFaxNumber != other.BusinessFaxNumber) return false; if (BusinessEmailAddress != other.BusinessEmailAddress) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (entityId_ != null) hash ^= EntityId.GetHashCode(); if (IataId.Length != 0) hash ^= IataId.GetHashCode(); if (CommissionType != 0) hash ^= CommissionType.GetHashCode(); if (commissionAmount_ != null) hash ^= CommissionAmount.GetHashCode(); if (commissionPercentage_ != null) hash ^= CommissionPercentage.GetHashCode(); if (GivenName.Length != 0) hash ^= GivenName.GetHashCode(); if (FamilyName.Length != 0) hash ^= FamilyName.GetHashCode(); if (BusinessAddress1.Length != 0) hash ^= BusinessAddress1.GetHashCode(); if (BusinessAddress2.Length != 0) hash ^= BusinessAddress2.GetHashCode(); if (BusinessCity.Length != 0) hash ^= BusinessCity.GetHashCode(); if (BusinessState.Length != 0) hash ^= BusinessState.GetHashCode(); if (BusinessZip.Length != 0) hash ^= BusinessZip.GetHashCode(); if (BusinessNation.Length != 0) hash ^= BusinessNation.GetHashCode(); if (BusinessPhoneNumber.Length != 0) hash ^= BusinessPhoneNumber.GetHashCode(); if (BusinessFaxNumber.Length != 0) hash ^= BusinessFaxNumber.GetHashCode(); if (BusinessEmailAddress.Length != 0) hash ^= BusinessEmailAddress.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (entityId_ != null) { output.WriteRawTag(10); output.WriteMessage(EntityId); } if (IataId.Length != 0) { output.WriteRawTag(18); output.WriteString(IataId); } if (CommissionType != 0) { output.WriteRawTag(24); output.WriteEnum((int) CommissionType); } if (commissionAmount_ != null) { output.WriteRawTag(34); output.WriteMessage(CommissionAmount); } if (commissionPercentage_ != null) { output.WriteRawTag(42); output.WriteMessage(CommissionPercentage); } if (GivenName.Length != 0) { output.WriteRawTag(50); output.WriteString(GivenName); } if (FamilyName.Length != 0) { output.WriteRawTag(58); output.WriteString(FamilyName); } if (BusinessAddress1.Length != 0) { output.WriteRawTag(66); output.WriteString(BusinessAddress1); } if (BusinessAddress2.Length != 0) { output.WriteRawTag(74); output.WriteString(BusinessAddress2); } if (BusinessCity.Length != 0) { output.WriteRawTag(82); output.WriteString(BusinessCity); } if (BusinessState.Length != 0) { output.WriteRawTag(90); output.WriteString(BusinessState); } if (BusinessZip.Length != 0) { output.WriteRawTag(98); output.WriteString(BusinessZip); } if (BusinessNation.Length != 0) { output.WriteRawTag(106); output.WriteString(BusinessNation); } if (BusinessPhoneNumber.Length != 0) { output.WriteRawTag(114); output.WriteString(BusinessPhoneNumber); } if (BusinessFaxNumber.Length != 0) { output.WriteRawTag(122); output.WriteString(BusinessFaxNumber); } if (BusinessEmailAddress.Length != 0) { output.WriteRawTag(130, 1); output.WriteString(BusinessEmailAddress); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (entityId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId); } if (IataId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(IataId); } if (CommissionType != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) CommissionType); } if (commissionAmount_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CommissionAmount); } if (commissionPercentage_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CommissionPercentage); } if (GivenName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(GivenName); } if (FamilyName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(FamilyName); } if (BusinessAddress1.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BusinessAddress1); } if (BusinessAddress2.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BusinessAddress2); } if (BusinessCity.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BusinessCity); } if (BusinessState.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BusinessState); } if (BusinessZip.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BusinessZip); } if (BusinessNation.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BusinessNation); } if (BusinessPhoneNumber.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BusinessPhoneNumber); } if (BusinessFaxNumber.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BusinessFaxNumber); } if (BusinessEmailAddress.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(BusinessEmailAddress); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TravelAgent other) { if (other == null) { return; } if (other.entityId_ != null) { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.TravelAgentIndicator(); } EntityId.MergeFrom(other.EntityId); } if (other.IataId.Length != 0) { IataId = other.IataId; } if (other.CommissionType != 0) { CommissionType = other.CommissionType; } if (other.commissionAmount_ != null) { if (commissionAmount_ == null) { commissionAmount_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } CommissionAmount.MergeFrom(other.CommissionAmount); } if (other.commissionPercentage_ != null) { if (commissionPercentage_ == null) { commissionPercentage_ = new global::HOLMS.Types.Primitive.FixedPointRatio(); } CommissionPercentage.MergeFrom(other.CommissionPercentage); } if (other.GivenName.Length != 0) { GivenName = other.GivenName; } if (other.FamilyName.Length != 0) { FamilyName = other.FamilyName; } if (other.BusinessAddress1.Length != 0) { BusinessAddress1 = other.BusinessAddress1; } if (other.BusinessAddress2.Length != 0) { BusinessAddress2 = other.BusinessAddress2; } if (other.BusinessCity.Length != 0) { BusinessCity = other.BusinessCity; } if (other.BusinessState.Length != 0) { BusinessState = other.BusinessState; } if (other.BusinessZip.Length != 0) { BusinessZip = other.BusinessZip; } if (other.BusinessNation.Length != 0) { BusinessNation = other.BusinessNation; } if (other.BusinessPhoneNumber.Length != 0) { BusinessPhoneNumber = other.BusinessPhoneNumber; } if (other.BusinessFaxNumber.Length != 0) { BusinessFaxNumber = other.BusinessFaxNumber; } if (other.BusinessEmailAddress.Length != 0) { BusinessEmailAddress = other.BusinessEmailAddress; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.TravelAgentIndicator(); } input.ReadMessage(entityId_); break; } case 18: { IataId = input.ReadString(); break; } case 24: { commissionType_ = (global::HOLMS.Types.Booking.Channels.CommissionType) input.ReadEnum(); break; } case 34: { if (commissionAmount_ == null) { commissionAmount_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(commissionAmount_); break; } case 42: { if (commissionPercentage_ == null) { commissionPercentage_ = new global::HOLMS.Types.Primitive.FixedPointRatio(); } input.ReadMessage(commissionPercentage_); break; } case 50: { GivenName = input.ReadString(); break; } case 58: { FamilyName = input.ReadString(); break; } case 66: { BusinessAddress1 = input.ReadString(); break; } case 74: { BusinessAddress2 = input.ReadString(); break; } case 82: { BusinessCity = input.ReadString(); break; } case 90: { BusinessState = input.ReadString(); break; } case 98: { BusinessZip = input.ReadString(); break; } case 106: { BusinessNation = input.ReadString(); break; } case 114: { BusinessPhoneNumber = input.ReadString(); break; } case 122: { BusinessFaxNumber = input.ReadString(); break; } case 130: { BusinessEmailAddress = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
// // GtkNotificationAreaBox.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Mono.Unix; using Gtk; using Banshee.Gui; using Banshee.ServiceStack; using Banshee.MediaEngine; namespace Banshee.NotificationArea { public class GtkNotificationAreaBox : StatusIcon, INotificationAreaBox { public event EventHandler Disconnected; public event EventHandler Activated; public event PopupMenuHandler PopupMenuEvent; private TrackInfoPopup popup; private bool can_show_popup = false; private bool cursor_over_trayicon = false; private bool hide_delay_started = false; public Widget Widget { get { return null; } } public GtkNotificationAreaBox (BaseClientWindow window) { Visible = false; IconName = (IconThemeUtils.HasIcon ("banshee-panel")) ? "banshee-panel" : Banshee.ServiceStack.Application.IconName; HasTooltip = true; base.Activate += delegate {OnActivated ();}; base.PopupMenu += delegate {OnPopupMenuEvent ();}; popup = new TrackInfoPopup (); } public void PositionMenu (Menu menu, out int x, out int y, out bool push_in) { StatusIcon.PositionMenu (menu, out x, out y, out push_in, Handle); } private void HidePopup () { if (popup == null) { return; } popup.Hide (); popup.EnterNotifyEvent -= OnPopupEnterNotify; popup.LeaveNotifyEvent -= OnPopupLeaveNotify; popup.Destroy (); popup.Dispose (); popup = null; } private void ShowPopup () { if (popup != null) { return; } popup = new TrackInfoPopup (); popup.EnterNotifyEvent += OnPopupEnterNotify; popup.LeaveNotifyEvent += OnPopupLeaveNotify; PositionPopup (); popup.Show (); } private void OnPopupEnterNotify (object o, EnterNotifyEventArgs args) { hide_delay_started = false; } private void OnPopupLeaveNotify (object o, LeaveNotifyEventArgs args) { Gdk.Rectangle rect; if (!popup.Intersect (new Gdk.Rectangle ((int)args.Event.X, (int)args.Event.Y, 1, 1), out rect)) { OnLeaveNotifyEvent (o, args); } } private void PositionPopup () { int x, y; Gdk.Screen screen; Gdk.Rectangle area; Orientation orientation; GetGeometry (out screen, out area, out orientation); Gtk.Requisition popup_min_size, popup_natural_size; popup.GetPreferredSize (out popup_min_size, out popup_natural_size); bool on_bottom = area.Bottom + popup_natural_size.Height >= screen.Height; y = on_bottom ? area.Top - popup_natural_size.Height - 5 : area.Bottom + 5; int monitor = screen.GetMonitorAtPoint (area.Left, y); var monitor_rect = screen.GetMonitorGeometry(monitor); x = area.Left - (popup_natural_size.Width / 2) + (area.Width / 2); if (x + popup_natural_size.Width >= monitor_rect.Right - 5) { x = monitor_rect.Right - popup_natural_size.Width - 5; } else if (x < monitor_rect.Left + 5) { x = monitor_rect.Left + 5; } popup.Move (x, y); } private void OnEnterNotifyEvent (object o, EnterNotifyEventArgs args) { hide_delay_started = false; cursor_over_trayicon = true; if (can_show_popup) { // only show the popup when the cursor is still over the // tray icon after 500ms GLib.Timeout.Add (500, delegate { if (cursor_over_trayicon && can_show_popup) { ShowPopup (); } return false; }); } } private void OnLeaveNotifyEvent (object o, LeaveNotifyEventArgs args) { // Give the user half a second to move the mouse cursor to the popup. if (!hide_delay_started) { hide_delay_started = true; cursor_over_trayicon = false; GLib.Timeout.Add (500, delegate { if (hide_delay_started) { hide_delay_started = false; HidePopup (); } return false; }); } } public void OnPlayerEvent (PlayerEventArgs args) { switch (args.Event) { case PlayerEvent.StartOfStream: can_show_popup = false; break; case PlayerEvent.EndOfStream: // only hide the popup when we don't play again after 250ms GLib.Timeout.Add (250, delegate { if (ServiceManager.PlayerEngine.CurrentState != PlayerState.Playing) { can_show_popup = false; HidePopup (); } return false; }); break; } } protected override bool OnScrollEvent (Gdk.EventScroll evnt) { switch (evnt.Direction) { case Gdk.ScrollDirection.Up: if ((evnt.State & Gdk.ModifierType.ControlMask) != 0) { ServiceManager.PlayerEngine.Volume += (ushort)PlayerEngine.VolumeDelta; } else if((evnt.State & Gdk.ModifierType.ShiftMask) != 0) { ServiceManager.PlayerEngine.Position += PlayerEngine.SkipDelta; } else { ServiceManager.PlaybackController.Next (); } break; case Gdk.ScrollDirection.Down: if ((evnt.State & Gdk.ModifierType.ControlMask) != 0) { if (ServiceManager.PlayerEngine.Volume < (ushort)PlayerEngine.VolumeDelta) { ServiceManager.PlayerEngine.Volume = 0; } else { ServiceManager.PlayerEngine.Volume -= (ushort)PlayerEngine.VolumeDelta; } } else if((evnt.State & Gdk.ModifierType.ShiftMask) != 0) { ServiceManager.PlayerEngine.Position -= PlayerEngine.SkipDelta; } else { ServiceManager.PlaybackController.Previous (); } break; } return true; } protected override bool OnButtonPressEvent (Gdk.EventButton evnt) { if (evnt.Type != Gdk.EventType.ButtonPress) { return false; } switch (evnt.Button) { case 1: if ((evnt.State & Gdk.ModifierType.ControlMask) != 0) { ServiceManager.PlaybackController.Next (); } else { OnActivated (); } break; case 2: ServiceManager.PlayerEngine.TogglePlaying (); break; case 3: if ((evnt.State & Gdk.ModifierType.ControlMask) != 0) { ServiceManager.PlaybackController.Next (); } else { OnPopupMenuEvent (); } break; } return true; } protected override bool OnQueryTooltip (int x, int y, bool keyboard_mode, Tooltip tooltip) { tooltip.Custom = popup; return true; } public void Show () { Visible = true; } public void Hide () { Visible = false; } protected virtual void OnActivated () { EventHandler handler = Activated; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnPopupMenuEvent () { PopupMenuHandler handler = PopupMenuEvent; if (handler != null) { handler (this, new PopupMenuArgs ()); } } } }
//--------------------------------------------------------------------- // <copyright file="Perspective.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Diagnostics; using System.Linq; namespace System.Data.Metadata.Edm { using System.Collections.Generic; /// <summary> /// Internal helper class for query /// </summary> internal abstract class Perspective { #region Constructors /// <summary> /// Creates a new instance of perspective class so that query can work /// ignorant of all spaces /// </summary> /// <param name="metadataWorkspace">runtime metadata container</param> /// <param name="targetDataspace">target dataspace for the perspective</param> internal Perspective(MetadataWorkspace metadataWorkspace, DataSpace targetDataspace) { EntityUtil.CheckArgumentNull(metadataWorkspace, "metadataWorkspace"); m_metadataWorkspace = metadataWorkspace; m_targetDataspace = targetDataspace; } #endregion #region Fields private MetadataWorkspace m_metadataWorkspace; private DataSpace m_targetDataspace; #endregion #region Methods /// <summary> /// Given the type in the target space and the member name in the source space, /// get the corresponding member in the target space /// For e.g. consider a Conceptual Type 'Foo' with a member 'Bar' and a CLR type /// 'XFoo' with a member 'YBar'. If one has a reference to Foo one can /// invoke GetMember(Foo,"YBar") to retrieve the member metadata for bar /// </summary> /// <param name="type">The type in the target perspective</param> /// <param name="memberName">the name of the member in the source perspective</param> /// <param name="ignoreCase">Whether to do case-sensitive member look up or not</param> /// <param name="outMember">returns the member in target space, if a match is found</param> internal virtual bool TryGetMember(StructuralType type, String memberName, bool ignoreCase, out EdmMember outMember) { EntityUtil.CheckArgumentNull(type, "type"); EntityUtil.CheckStringArgument(memberName, "memberName"); outMember = null; return type.Members.TryGetValue(memberName, ignoreCase, out outMember); } internal bool TryGetEnumMember(EnumType type, String memberName, bool ignoreCase, out EnumMember outMember) { EntityUtil.CheckArgumentNull(type, "type"); EntityUtil.CheckStringArgument(memberName, "memberName"); outMember = null; return type.Members.TryGetValue(memberName, ignoreCase, out outMember); } /// <summary> /// Returns the extent in the target space, for the given entity container. /// </summary> /// <param name="entityContainer">name of the entity container in target space</param> /// <param name="extentName">name of the extent</param> /// <param name="ignoreCase">Whether to do case-sensitive member look up or not</param> /// <param name="outSet">extent in target space, if a match is found</param> /// <returns>returns true, if a match is found otherwise returns false</returns> internal bool TryGetExtent(EntityContainer entityContainer, String extentName, bool ignoreCase, out EntitySetBase outSet) { // There are no entity containers in the OSpace. So there is no mapping involved. // Hence the name should be a valid name in the CSpace. return entityContainer.BaseEntitySets.TryGetValue(extentName, ignoreCase, out outSet); } /// <summary> /// Returns the function import in the target space, for the given entity container. /// </summary> internal bool TryGetFunctionImport(EntityContainer entityContainer, String functionImportName, bool ignoreCase, out EdmFunction functionImport) { // There are no entity containers in the OSpace. So there is no mapping involved. // Hence the name should be a valid name in the CSpace. functionImport = null; if (ignoreCase) { functionImport = entityContainer.FunctionImports.Where(fi => String.Equals(fi.Name, functionImportName, StringComparison.OrdinalIgnoreCase)).SingleOrDefault(); } else { functionImport = entityContainer.FunctionImports.Where(fi => fi.Name == functionImportName).SingleOrDefault(); } return functionImport != null; } /// <summary> /// Get the default entity container /// returns null for any perspective other /// than the CLR perspective /// </summary> /// <returns>The default container</returns> internal virtual EntityContainer GetDefaultContainer() { return null; } /// <summary> /// Get an entity container based upon the strong name of the container /// If no entity container is found, returns null, else returns the first one/// </summary> /// <param name="name">name of the entity container</param> /// <param name="ignoreCase">true for case-insensitive lookup</param> /// <param name="entityContainer">returns the entity container if a match is found</param> /// <returns>returns true if a match is found, otherwise false</returns> internal virtual bool TryGetEntityContainer(string name, bool ignoreCase, out EntityContainer entityContainer) { return MetadataWorkspace.TryGetEntityContainer(name, ignoreCase, TargetDataspace, out entityContainer); } /// <summary> /// Gets a type with the given name in the target space. /// </summary> /// <param name="fullName">full name of the type</param> /// <param name="ignoreCase">true for case-insensitive lookup</param> /// <param name="typeUsage">TypeUsage for the type</param> /// <returns>returns true if a match was found, otherwise false</returns> internal abstract bool TryGetTypeByName(string fullName, bool ignoreCase, out TypeUsage typeUsage); /// <summary> /// Returns overloads of a function with the given name in the target space. /// </summary> /// <param name="namespaceName">namespace of the function</param> /// <param name="functionName">name of the function</param> /// <param name="ignoreCase">true for case-insensitive lookup</param> /// <param name="functionOverloads">function overloads</param> /// <returns>returns true if a match was found, otherwise false</returns> internal bool TryGetFunctionByName(string namespaceName, string functionName, bool ignoreCase, out IList<EdmFunction> functionOverloads) { EntityUtil.CheckStringArgument(namespaceName, "namespaceName"); EntityUtil.CheckStringArgument(functionName, "functionName"); var fullName = namespaceName + "." + functionName; // First look for a model-defined function in the target space. ItemCollection itemCollection = m_metadataWorkspace.GetItemCollection(m_targetDataspace); IList<EdmFunction> overloads = m_targetDataspace == DataSpace.SSpace ? ((StoreItemCollection)itemCollection).GetCTypeFunctions(fullName, ignoreCase) : itemCollection.GetFunctions(fullName, ignoreCase); if (m_targetDataspace == DataSpace.CSpace) { // Then look for a function import. if (overloads == null || overloads.Count == 0) { EntityContainer entityContainer; if (this.TryGetEntityContainer(namespaceName, /*ignoreCase:*/ false, out entityContainer)) { EdmFunction functionImport; if (this.TryGetFunctionImport(entityContainer, functionName, /*ignoreCase:*/ false, out functionImport)) { overloads = new EdmFunction[] { functionImport }; } } } // Last, look in SSpace. if (overloads == null || overloads.Count == 0) { ItemCollection storeItemCollection; if (m_metadataWorkspace.TryGetItemCollection(DataSpace.SSpace, out storeItemCollection)) { overloads = ((StoreItemCollection)storeItemCollection).GetCTypeFunctions(fullName, ignoreCase); } } } functionOverloads = (overloads != null && overloads.Count > 0) ? overloads : null; return functionOverloads != null; } /// <summary> /// Return the metadata workspace /// </summary> internal MetadataWorkspace MetadataWorkspace { get { return m_metadataWorkspace; } } /// <summary> /// returns the primitive type for a given primitive type kind. /// </summary> /// <param name="primitiveTypeKind"></param> /// <param name="primitiveType"></param> /// <returns></returns> internal virtual bool TryGetMappedPrimitiveType(PrimitiveTypeKind primitiveTypeKind, out PrimitiveType primitiveType) { primitiveType = m_metadataWorkspace.GetMappedPrimitiveType(primitiveTypeKind, DataSpace.CSpace); return (null != primitiveType); } // // This property will be needed to construct keys for transient types // /// <summary> /// Returns the target dataspace for this perspective /// </summary> internal DataSpace TargetDataspace { get { return m_targetDataspace; } } #endregion } }
// 32feet.NET - Personal Area Networking for .NET // // InTheHand.Net.Bluetooth.Factory.BluetoothFactory // // Copyright (c) 2003-2010 In The Hand Ltd, All rights reserved. // This source code is licensed under the MIT License using System; using System.Text; using System.Diagnostics; #if !V1 using List_BluetoothFactory = System.Collections.Generic.List<InTheHand.Net.Bluetooth.Factory.BluetoothFactory>; using IList_BluetoothFactory = System.Collections.Generic.IList<InTheHand.Net.Bluetooth.Factory.BluetoothFactory>; using List_Exception = System.Collections.Generic.List<System.Exception>; using System.Diagnostics.CodeAnalysis; #else using List_BluetoothFactory = System.Collections.ArrayList; using IList_BluetoothFactory = System.Collections.IList; using List_Exception = System.Collections.ArrayList; #endif namespace InTheHand.Net.Bluetooth.Factory { #pragma warning disable 1591 /// <exclude/> [CLSCompliant(false)] // Due to CommonRfcommStream public abstract class BluetoothFactory : IDisposable { [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] protected virtual IL2CapClient GetL2CapClient() { throw new NotImplementedException(); } protected abstract IBluetoothClient GetBluetoothClient(); protected abstract IBluetoothClient GetBluetoothClient(System.Net.Sockets.Socket acceptedSocket); protected abstract IBluetoothClient GetBluetoothClientForListener(CommonRfcommStream acceptedStrm); protected abstract IBluetoothClient GetBluetoothClient(BluetoothEndPoint localEP); protected abstract IBluetoothDeviceInfo GetBluetoothDeviceInfo(BluetoothAddress address); [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] protected abstract IBluetoothListener GetBluetoothListener(); // [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] protected abstract IBluetoothRadio GetPrimaryRadio(); protected abstract IBluetoothRadio[] GetAllRadios(); // [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] protected abstract IBluetoothSecurity GetBluetoothSecurity(); // void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected abstract void Dispose(bool disposing); //-------------------------------------------------------------- #region Internal accessors to abstract methods public IL2CapClient DoGetL2CapClient() { return GetL2CapClient(); } public IBluetoothClient DoGetBluetoothClient() { return GetBluetoothClient(); } public IBluetoothClient DoGetBluetoothClientForListener(CommonRfcommStream acceptedStream) { return GetBluetoothClientForListener(acceptedStream); } public IBluetoothClient DoGetBluetoothClient(System.Net.Sockets.Socket acceptedSocket) { return GetBluetoothClient(acceptedSocket); } public IBluetoothClient DoGetBluetoothClient(BluetoothEndPoint localEP) { return GetBluetoothClient(localEP); } public IBluetoothDeviceInfo DoGetBluetoothDeviceInfo(BluetoothAddress address) { return GetBluetoothDeviceInfo(address); } public IBluetoothListener DoGetBluetoothListener() { return GetBluetoothListener(); } // public IBluetoothRadio DoGetPrimaryRadio() { return GetPrimaryRadio(); } public IBluetoothRadio[] DoGetAllRadios() { return GetAllRadios(); } // public IBluetoothSecurity DoGetBluetoothSecurity() { return GetBluetoothSecurity(); } #endregion //-------------------------------------------------------------- static IList_BluetoothFactory s_factories; static object lockKey = new object(); #if !V1 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] #endif private static void GetStacks_inLock() { List_BluetoothFactory list = new List_BluetoothFactory(); List_Exception errors = new List_Exception(); var stacks = new System.Collections.Generic.List<string>( BluetoothFactoryConfig.KnownStacks); TraceWriteLibraryVersion(); foreach (string factoryName in stacks) { try { Type t = Type.GetType(factoryName, true); Debug.Assert(t != null, string.Format(System.Globalization.CultureInfo.InvariantCulture, "Expected GetType to throw when type not found: '{0}'", factoryName)); object tmp = Activator.CreateInstance(t); Debug.Assert(tmp != null, "Expect all failures to throw rather than return null."); IBluetoothFactoryFactory ff = tmp as IBluetoothFactoryFactory; if (ff == null) { list.Add((BluetoothFactory)tmp); } else { // BluetoothFactoryFactory! IList_BluetoothFactory multiple = ff.GetFactories(errors); if (multiple != null) { Debug.WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, "BluetoothFactoryFactory '{0}' supplied {1} items.", ff.GetType().AssemblyQualifiedName, multiple.Count)); list.AddRange(multiple); } else { Debug.WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, "BluetoothFactoryFactory '{0}' returned null.", ff.GetType().AssemblyQualifiedName)); } } if (BluetoothFactoryConfig.OneStackOnly) { break; } } catch (Exception ex) { if (ex is System.Reflection.TargetInvocationException) { Debug.Assert(ex.InnerException != null, "We know from the old }catch(TIEX){throw ex.InnerEx;} that this is non-null"); ex = ex.InnerException; } errors.Add(ex); string msg = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Exception creating factory '{0}, ex: {1}", factoryName, ex); if (BluetoothFactoryConfig.ReportAllErrors) { Utils.MiscUtils.Trace_Fail(msg); // (No Trace.Fail on NETCF). } Debug.WriteLine(msg); } }//for if (list.Count == 0) { if (!BluetoothFactoryConfig.ReportAllErrors) { // Have been reported above. foreach (Exception ex in errors) { string info = ExceptionExtension.ToStringNoStackTrace(ex); Utils.MiscUtils.Trace_WriteLine(info); } } #if !NO_WIDCOMM // Special case Widcomm -- report if stacks seems there, but not our DLL. Exception wcNoInterfaceDll = null; try { wcNoInterfaceDll = Widcomm.WidcommBtIf.IsWidcommStackPresentButNotInterfaceDll(); } catch (Exception ex) { // Maybe a P/Invoke exception calling GetModuleHandle if (Environment.OSVersion.Platform.ToString().StartsWith("Win", StringComparison.Ordinal)) { // Don't complain in Linux etc. Utils.MiscUtils.Trace_WriteLine("Exception in IsWidcommStackPresentButNotInterfaceDll: " + ex); } } if (wcNoInterfaceDll != null) throw wcNoInterfaceDll; #endif throw new PlatformNotSupportedException("No supported Bluetooth protocol stack found."); } else { SetFactories_inLock(list); } // result #if !ANDROID Debug.WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Num factories: {1}, Primary Factory: {0}", (s_factories == null ? "(null)" : s_factories[0].GetType().Name), (s_factories == null ? "(null)" : s_factories.Count.ToString()))); #endif } internal static IList_BluetoothFactory Factories { get { lock (lockKey) { if (s_factories == null) { GetStacks_inLock(); }//if Debug.Assert(s_factories.Count > 0, "Empty s_factories!"); #if !V1 // Have to suffer mutableness in NETCFv1. :-( Debug.Assert(((System.Collections.IList)s_factories).IsReadOnly, "!IsReadOnly"); Debug.Assert(((System.Collections.IList)s_factories).IsFixedSize, "!IsFixedSize"); #endif return s_factories; } } } internal static BluetoothFactory Factory { get { return (BluetoothFactory)Factories[0]; /* cast for NETCFv1 */ } } internal static void SetFactory(BluetoothFactory factory) { if (factory == null) throw new ArgumentNullException("factory"); lock (lockKey) { Debug.WriteLine("SetFactory: " + factory == null ? "(null)" : factory.GetType().Name); if (!TestUtilities.IsUnderTestHarness()) { Debug.Assert(s_factories == null, "Shouldn't change the factory."); // throw new InvalidOperationException("Can't change the factory."); } SetFactories_inLock(new List_BluetoothFactory(new BluetoothFactory[] { factory })); } } private static void SetFactories_inLock(List_BluetoothFactory list) { Debug.Assert(list.Count > 0, "Empty s_factories!"); #if !V1 s_factories = list.AsReadOnly(); #else s_factories = list; // warning not ReadOnly #endif } //-------------------------------------------------------------- public static void HackShutdownAll() { lock (lockKey) { if (s_factories != null) foreach (var cur in s_factories) { ((IDisposable)cur).Dispose(); } }//lock s_factories = null; } /// <summary> /// PRE-RELEASE /// Get the instance of the given factory type -- if it exists. /// </summary> /// - /// <typeparam name="TFactory">The factory type e.g. /// <see cref="T:InTheHand.Net.Bluetooth.SocketsBluetoothFactory"/> /// or <see cref="T:InTheHand.Net.Bluetooth.Widcomm.WidcommBluetoothFactoryBase"/> /// etc. /// </typeparam> /// - /// <returns>The instance of the given type or <c>null</c>. /// </returns> public static TFactory GetTheFactoryOfTypeOrDefault<TFactory>() where TFactory : BluetoothFactory { foreach (BluetoothFactory curF in BluetoothFactory.Factories) { var asF = curF as TFactory; if (asF != null) { return (TFactory)curF; } }//for return null; } /// <summary> /// PRE-RELEASE /// Get the instance of the given factory type -- if it exists. /// </summary> /// - /// <param name="factoryType">The factory type e.g. /// <see cref="T:InTheHand.Net.Bluetooth.SocketsBluetoothFactory"/> /// or <see cref="T:InTheHand.Net.Bluetooth.Widcomm.WidcommBluetoothFactoryBase"/> /// etc. /// </param> /// - /// <returns>The instance of the given type or <c>null</c>. /// </returns> public static BluetoothFactory GetTheFactoryOfTypeOrDefault(Type factoryType) { foreach (BluetoothFactory curF in BluetoothFactory.Factories) { if (factoryType.IsInstanceOfType(curF)) { return curF; } }//for return null; } //---- private static void TraceWriteLibraryVersion() { var a = System.Reflection.Assembly.GetExecutingAssembly(); var fn = a.FullName; //var an = new System.Reflection.AssemblyName(fn); var an = a.GetName(); var v = an.Version; // Is AssemblyVersionAttribute. // var aiva = GetCustomAttributes<System.Reflection.AssemblyInformationalVersionAttribute>(a); string vi = (aiva != null) ? aiva.InformationalVersion : null; // Utils.MiscUtils.Trace_WriteLine("32feet.NET: '{0}'\r\n versions: '{1}' and '{2}'.", an, v, vi); } static TAttr GetCustomAttributes<TAttr>(System.Reflection.Assembly a) where TAttr : Attribute { var arr = a.GetCustomAttributes(typeof(TAttr), true); #if false // _Not_ supported on NETCF var newArr = Array.ConvertAll(arr, x => (TAttr)x); #endif if (arr.Length == 0) return null; if (arr.Length > 1) { throw new InvalidOperationException("Don't support multiple attribute instances."); } var attr = (TAttr)arr[0]; return attr; } } }
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.14.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * YouTube Reporting API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/youtube/reporting/v1/reports/'>YouTube Reporting API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20160719 (565) * <tr><th>API Docs * <td><a href='https://developers.google.com/youtube/reporting/v1/reports/'> * https://developers.google.com/youtube/reporting/v1/reports/</a> * <tr><th>Discovery Name<td>youtubereporting * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using YouTube Reporting API can be found at * <a href='https://developers.google.com/youtube/reporting/v1/reports/'>https://developers.google.com/youtube/reporting/v1/reports/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.YouTubeReporting.v1 { /// <summary>The YouTubeReporting Service.</summary> public class YouTubeReportingService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public YouTubeReportingService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public YouTubeReportingService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { jobs = new JobsResource(this); media = new MediaResource(this); reportTypes = new ReportTypesResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "youtubereporting"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://youtubereporting.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } /// <summary>Available OAuth 2.0 scopes for use with the YouTube Reporting API.</summary> public class Scope { /// <summary>View monetary and non-monetary YouTube Analytics reports for your YouTube content</summary> public static string YtAnalyticsMonetaryReadonly = "https://www.googleapis.com/auth/yt-analytics-monetary.readonly"; /// <summary>View YouTube Analytics reports for your YouTube content</summary> public static string YtAnalyticsReadonly = "https://www.googleapis.com/auth/yt-analytics.readonly"; } private readonly JobsResource jobs; /// <summary>Gets the Jobs resource.</summary> public virtual JobsResource Jobs { get { return jobs; } } private readonly MediaResource media; /// <summary>Gets the Media resource.</summary> public virtual MediaResource Media { get { return media; } } private readonly ReportTypesResource reportTypes; /// <summary>Gets the ReportTypes resource.</summary> public virtual ReportTypesResource ReportTypes { get { return reportTypes; } } } ///<summary>A base abstract class for YouTubeReporting requests.</summary> public abstract class YouTubeReportingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new YouTubeReportingBaseServiceRequest instance.</summary> protected YouTubeReportingBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual string Xgafv { get; set; } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual string Alt { get; set; } /// <summary>OAuth bearer token.</summary> [Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string BearerToken { get; set; } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Pretty-print response.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Pp { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes YouTubeReporting parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "bearer_token", new Google.Apis.Discovery.Parameter { Name = "bearer_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pp", new Google.Apis.Discovery.Parameter { Name = "pp", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "jobs" collection of methods.</summary> public class JobsResource { private const string Resource = "jobs"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public JobsResource(Google.Apis.Services.IClientService service) { this.service = service; reports = new ReportsResource(service); } private readonly ReportsResource reports; /// <summary>Gets the Reports resource.</summary> public virtual ReportsResource Reports { get { return reports; } } /// <summary>The "reports" collection of methods.</summary> public class ReportsResource { private const string Resource = "reports"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ReportsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Gets the metadata of a specific report.</summary> /// <param name="jobId">The ID of the job.</param> /// <param name="reportId">The ID of the report to /// retrieve.</param> public virtual GetRequest Get(string jobId, string reportId) { return new GetRequest(service, jobId, reportId); } /// <summary>Gets the metadata of a specific report.</summary> public class GetRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.Report> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string jobId, string reportId) : base(service) { JobId = jobId; ReportId = reportId; InitParameters(); } /// <summary>The ID of the job.</summary> [Google.Apis.Util.RequestParameterAttribute("jobId", Google.Apis.Util.RequestParameterType.Path)] public virtual string JobId { get; private set; } /// <summary>The ID of the report to retrieve.</summary> [Google.Apis.Util.RequestParameterAttribute("reportId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ReportId { get; private set; } /// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user /// is acting for himself (his own channel).</summary> [Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)] public virtual string OnBehalfOfContentOwner { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/jobs/{jobId}/reports/{reportId}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "jobId", new Google.Apis.Discovery.Parameter { Name = "jobId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "reportId", new Google.Apis.Discovery.Parameter { Name = "reportId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter { Name = "onBehalfOfContentOwner", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Lists reports created by a specific job. Returns NOT_FOUND if the job does not exist.</summary> /// <param name="jobId">The ID of the job.</param> public virtual ListRequest List(string jobId) { return new ListRequest(service, jobId); } /// <summary>Lists reports created by a specific job. Returns NOT_FOUND if the job does not exist.</summary> public class ListRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.ListReportsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string jobId) : base(service) { JobId = jobId; InitParameters(); } /// <summary>The ID of the job.</summary> [Google.Apis.Util.RequestParameterAttribute("jobId", Google.Apis.Util.RequestParameterType.Path)] public virtual string JobId { get; private set; } /// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user /// is acting for himself (his own channel).</summary> [Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)] public virtual string OnBehalfOfContentOwner { get; set; } /// <summary>Requested page size. Server may return fewer report types than requested. If unspecified, /// server will pick an appropriate default.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>A token identifying a page of results the server should return. Typically, this is the /// value of ListReportsResponse.next_page_token returned in response to the previous call to the /// `ListReports` method.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>If set, only reports created after the specified date/time are returned.</summary> [Google.Apis.Util.RequestParameterAttribute("createdAfter", Google.Apis.Util.RequestParameterType.Query)] public virtual string CreatedAfter { get; set; } /// <summary>If set, only reports whose start time is greater than or equal the specified date/time are /// returned.</summary> [Google.Apis.Util.RequestParameterAttribute("startTimeAtOrAfter", Google.Apis.Util.RequestParameterType.Query)] public virtual string StartTimeAtOrAfter { get; set; } /// <summary>If set, only reports whose start time is smaller than the specified date/time are /// returned.</summary> [Google.Apis.Util.RequestParameterAttribute("startTimeBefore", Google.Apis.Util.RequestParameterType.Query)] public virtual string StartTimeBefore { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/jobs/{jobId}/reports"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "jobId", new Google.Apis.Discovery.Parameter { Name = "jobId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter { Name = "onBehalfOfContentOwner", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "createdAfter", new Google.Apis.Discovery.Parameter { Name = "createdAfter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "startTimeAtOrAfter", new Google.Apis.Discovery.Parameter { Name = "startTimeAtOrAfter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "startTimeBefore", new Google.Apis.Discovery.Parameter { Name = "startTimeBefore", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>Creates a job and returns it.</summary> /// <param name="body">The body of the request.</param> public virtual CreateRequest Create(Google.Apis.YouTubeReporting.v1.Data.Job body) { return new CreateRequest(service, body); } /// <summary>Creates a job and returns it.</summary> public class CreateRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.Job> { /// <summary>Constructs a new Create request.</summary> public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.YouTubeReporting.v1.Data.Job body) : base(service) { Body = body; InitParameters(); } /// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user is /// acting for himself (his own channel).</summary> [Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)] public virtual string OnBehalfOfContentOwner { get; set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.YouTubeReporting.v1.Data.Job Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "create"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/jobs"; } } /// <summary>Initializes Create parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter { Name = "onBehalfOfContentOwner", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Deletes a job.</summary> /// <param name="jobId">The ID of the job to delete.</param> public virtual DeleteRequest Delete(string jobId) { return new DeleteRequest(service, jobId); } /// <summary>Deletes a job.</summary> public class DeleteRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.Empty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string jobId) : base(service) { JobId = jobId; InitParameters(); } /// <summary>The ID of the job to delete.</summary> [Google.Apis.Util.RequestParameterAttribute("jobId", Google.Apis.Util.RequestParameterType.Path)] public virtual string JobId { get; private set; } /// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user is /// acting for himself (his own channel).</summary> [Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)] public virtual string OnBehalfOfContentOwner { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/jobs/{jobId}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "jobId", new Google.Apis.Discovery.Parameter { Name = "jobId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter { Name = "onBehalfOfContentOwner", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Gets a job.</summary> /// <param name="jobId">The ID of the job to retrieve.</param> public virtual GetRequest Get(string jobId) { return new GetRequest(service, jobId); } /// <summary>Gets a job.</summary> public class GetRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.Job> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string jobId) : base(service) { JobId = jobId; InitParameters(); } /// <summary>The ID of the job to retrieve.</summary> [Google.Apis.Util.RequestParameterAttribute("jobId", Google.Apis.Util.RequestParameterType.Path)] public virtual string JobId { get; private set; } /// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user is /// acting for himself (his own channel).</summary> [Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)] public virtual string OnBehalfOfContentOwner { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/jobs/{jobId}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "jobId", new Google.Apis.Discovery.Parameter { Name = "jobId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter { Name = "onBehalfOfContentOwner", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Lists jobs.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Lists jobs.</summary> public class ListRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.ListJobsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user is /// acting for himself (his own channel).</summary> [Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)] public virtual string OnBehalfOfContentOwner { get; set; } /// <summary>Requested page size. Server may return fewer jobs than requested. If unspecified, server will /// pick an appropriate default.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>A token identifying a page of results the server should return. Typically, this is the value of /// ListReportTypesResponse.next_page_token returned in response to the previous call to the `ListJobs` /// method.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>If set to true, also system-managed jobs will be returned; otherwise only user-created jobs /// will be returned. System-managed jobs can neither be modified nor deleted.</summary> [Google.Apis.Util.RequestParameterAttribute("includeSystemManaged", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> IncludeSystemManaged { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/jobs"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter { Name = "onBehalfOfContentOwner", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "includeSystemManaged", new Google.Apis.Discovery.Parameter { Name = "includeSystemManaged", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "media" collection of methods.</summary> public class MediaResource { private const string Resource = "media"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public MediaResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Method for media download. Download is supported on the URI /// `/v1/media/{+name}?alt=media`.</summary> /// <param name="resourceName">Name of the media that is being downloaded. See ReadRequest.resource_name.</param> public virtual DownloadRequest Download(string resourceName) { return new DownloadRequest(service, resourceName); } /// <summary>Method for media download. Download is supported on the URI /// `/v1/media/{+name}?alt=media`.</summary> public class DownloadRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.Media> { /// <summary>Constructs a new Download request.</summary> public DownloadRequest(Google.Apis.Services.IClientService service, string resourceName) : base(service) { ResourceName = resourceName; MediaDownloader = new Google.Apis.Download.MediaDownloader(service); InitParameters(); } /// <summary>Name of the media that is being downloaded. See ReadRequest.resource_name.</summary> [Google.Apis.Util.RequestParameterAttribute("resourceName", Google.Apis.Util.RequestParameterType.Path)] public virtual string ResourceName { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "download"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/media/{+resourceName}"; } } /// <summary>Initializes Download parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "resourceName", new Google.Apis.Discovery.Parameter { Name = "resourceName", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^.*$", }); } /// <summary>Gets the media downloader.</summary> public Google.Apis.Download.IMediaDownloader MediaDownloader { get; private set; } /// <summary>Synchronously download the media into the given stream.</summary> public virtual void Download(System.IO.Stream stream) { MediaDownloader.Download(this.GenerateRequestUri(), stream); } /// <summary>Asynchronously download the media into the given stream.</summary> public virtual System.Threading.Tasks.Task<Google.Apis.Download.IDownloadProgress> DownloadAsync(System.IO.Stream stream) { return MediaDownloader.DownloadAsync(this.GenerateRequestUri(), stream); } /// <summary>Asynchronously download the media into the given stream.</summary> public virtual System.Threading.Tasks.Task<Google.Apis.Download.IDownloadProgress> DownloadAsync(System.IO.Stream stream, System.Threading.CancellationToken cancellationToken) { return MediaDownloader.DownloadAsync(this.GenerateRequestUri(), stream, cancellationToken); } } } /// <summary>The "reportTypes" collection of methods.</summary> public class ReportTypesResource { private const string Resource = "reportTypes"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ReportTypesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Lists report types.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Lists report types.</summary> public class ListRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.ListReportTypesResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user is /// acting for himself (his own channel).</summary> [Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)] public virtual string OnBehalfOfContentOwner { get; set; } /// <summary>Requested page size. Server may return fewer report types than requested. If unspecified, /// server will pick an appropriate default.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>A token identifying a page of results the server should return. Typically, this is the value of /// ListReportTypesResponse.next_page_token returned in response to the previous call to the /// `ListReportTypes` method.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>If set to true, also system-managed report types will be returned; otherwise only the report /// types that can be used to create new reporting jobs will be returned.</summary> [Google.Apis.Util.RequestParameterAttribute("includeSystemManaged", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> IncludeSystemManaged { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/reportTypes"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter { Name = "onBehalfOfContentOwner", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "includeSystemManaged", new Google.Apis.Discovery.Parameter { Name = "includeSystemManaged", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.YouTubeReporting.v1.Data { /// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A /// typical example is to use it as the request or the response type of an API method. For instance: service Foo { /// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty /// JSON object `{}`.</summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A job creating reports of a specific type.</summary> public class Job : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The creation date/time of the job.</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual string CreateTime { get; set; } /// <summary>The date/time when this job will expire/expired. After a job expired, no new reports are /// generated.</summary> [Newtonsoft.Json.JsonPropertyAttribute("expireTime")] public virtual string ExpireTime { get; set; } /// <summary>The server-generated ID of the job (max. 40 characters).</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The name of the job (max. 100 characters).</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The type of reports this job creates. Corresponds to the ID of a ReportType.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reportTypeId")] public virtual string ReportTypeId { get; set; } /// <summary>True if this a system-managed job that cannot be modified by the user; otherwise false.</summary> [Newtonsoft.Json.JsonPropertyAttribute("systemManaged")] public virtual System.Nullable<bool> SystemManaged { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for ReportingService.ListJobs.</summary> public class ListJobsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The list of jobs.</summary> [Newtonsoft.Json.JsonPropertyAttribute("jobs")] public virtual System.Collections.Generic.IList<Job> Jobs { get; set; } /// <summary>A token to retrieve next page of results. Pass this value in the ListJobsRequest.page_token field /// in the subsequent call to `ListJobs` method to retrieve the next page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for ReportingService.ListReportTypes.</summary> public class ListReportTypesResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A token to retrieve next page of results. Pass this value in the ListReportTypesRequest.page_token /// field in the subsequent call to `ListReportTypes` method to retrieve the next page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The list of report types.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reportTypes")] public virtual System.Collections.Generic.IList<ReportType> ReportTypes { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for ReportingService.ListReports.</summary> public class ListReportsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A token to retrieve next page of results. Pass this value in the ListReportsRequest.page_token /// field in the subsequent call to `ListReports` method to retrieve the next page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The list of report types.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reports")] public virtual System.Collections.Generic.IList<Report> Reports { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Media resource.</summary> public class Media : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Name of the media resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("resourceName")] public virtual string ResourceName { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A report's metadata including the URL from which the report itself can be downloaded.</summary> public class Report : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The date/time when this report was created.</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual string CreateTime { get; set; } /// <summary>The URL from which the report can be downloaded (max. 1000 characters).</summary> [Newtonsoft.Json.JsonPropertyAttribute("downloadUrl")] public virtual string DownloadUrl { get; set; } /// <summary>The end of the time period that the report instance covers. The value is exclusive.</summary> [Newtonsoft.Json.JsonPropertyAttribute("endTime")] public virtual string EndTime { get; set; } /// <summary>The server-generated ID of the report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The date/time when the job this report belongs to will expire/expired.</summary> [Newtonsoft.Json.JsonPropertyAttribute("jobExpireTime")] public virtual string JobExpireTime { get; set; } /// <summary>The ID of the job that created this report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("jobId")] public virtual string JobId { get; set; } /// <summary>The start of the time period that the report instance covers. The value is inclusive.</summary> [Newtonsoft.Json.JsonPropertyAttribute("startTime")] public virtual string StartTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A report type.</summary> public class ReportType : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The date/time when this report type was/will be deprecated.</summary> [Newtonsoft.Json.JsonPropertyAttribute("deprecateTime")] public virtual string DeprecateTime { get; set; } /// <summary>The ID of the report type (max. 100 characters).</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The name of the report type (max. 100 characters).</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>True if this a system-managed report type; otherwise false. Reporting jobs for system-managed /// report types are created automatically and can thus not be used in the `CreateJob` method.</summary> [Newtonsoft.Json.JsonPropertyAttribute("systemManaged")] public virtual System.Nullable<bool> SystemManaged { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Threading; #if __UNIFIED__ using UIKit; using Foundation; using CoreAnimation; using CoreGraphics; using Accounts; using Twitter; #else using MonoTouch.UIKit; using MonoTouch.Foundation; using MonoTouch.CoreAnimation; using MonoTouch.CoreGraphics; using System.Drawing; using CGRect = global::System.Drawing.RectangleF; using CGPoint = global::System.Drawing.PointF; using CGSize = global::System.Drawing.SizeF; using nfloat = global::System.Single; using nint = global::System.Int32; using nuint = global::System.UInt32; using MonoTouch.Accounts; using MonoTouch.Twitter; #endif using Xamarin.Auth; namespace Xamarin.Social.Services { public class Twitter5Service : TwitterService { public Twitter5Service () { } #region Share public override UIViewController GetShareUI (Item item, Action<ShareResult> completionHandler) { // // Get the native UI // var vc = new TWTweetComposeViewController (); vc.SetCompletionHandler (result => { var shareResult = result == TWTweetComposeViewControllerResult.Done ? ShareResult.Done : ShareResult.Cancelled; completionHandler (shareResult); }); vc.SetInitialText (item.Text); foreach (var image in item.Images) { vc.AddImage (image.Image); } foreach (var link in item.Links) { vc.AddUrl (new NSUrl (link.AbsoluteUri)); } return vc; } public override Task ShareItemAsync (Item item, Account account, CancellationToken cancellationToken) { throw new NotSupportedException ("Sharing items without a GUI is not supported. Please use GetShareUI instead."); } #endregion #region Low-level Requests class TwitterRequest : Request { TWRequest request; public TwitterRequest (string method, Uri url, IDictionary<string, string> paramters, Account account) : base (method, url, paramters, account) { var ps = new NSMutableDictionary (); if (paramters != null) { foreach (var p in paramters) { ps.SetValueForKey (new NSString (p.Value), new NSString (p.Key)); } } var m = TWRequestMethod.Get; switch (method.ToLowerInvariant()) { case "get": m = TWRequestMethod.Get; break; case "post": m = TWRequestMethod.Post; break; case "delete": m = TWRequestMethod.Delete; break; default: throw new NotSupportedException ("Twitter does not support the HTTP method '" + method + "'"); } request = new TWRequest (new NSUrl (url.AbsoluteUri), ps, m); Account = account; } public override Account Account { get { return base.Account; } set { base.Account = value; if (request != null) { if (value == null) { // Don't do anything, not supported } else if (value is ACAccountWrapper) { request.Account = ((ACAccountWrapper)value).ACAccount; } else { throw new NotSupportedException ("Account type '" + value.GetType().FullName + "'not supported"); } } } } public override void AddMultipartData (string name, System.IO.Stream data, string mimeType, string filename) { request.AddMultiPartData (NSData.FromStream (data), name, mimeType); } public override Task<Response> GetResponseAsync (CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<Response> (); cancellationToken.Register (() => tcs.TrySetCanceled ()); request.PerformRequest ((resposeData, urlResponse, err) => { Response result = null; try { if (err != null) throw new Exception (err.LocalizedDescription); result = new FoundationResponse (resposeData, urlResponse); } catch (Exception ex) { tcs.TrySetException (ex); return; } tcs.TrySetResult (result); }); return tcs.Task; } } public override Request CreateRequest (string method, Uri url, IDictionary<string, string> paramters, Account account) { return new TwitterRequest (method, url, paramters, account); } #endregion #region Authentication ACAccountStore accountStore; // Save this reference since ACAccounts are only good so long as it's alive public override Task<IEnumerable<Account>> GetAccountsAsync () { if (accountStore == null) accountStore = new ACAccountStore (); var at = accountStore.FindAccountType (ACAccountType.Twitter); var tcs = new TaskCompletionSource<IEnumerable<Account>> (); accountStore.RequestAccess (at, (granted, error) => { if (granted) { var accounts = accountStore.FindAccounts (at) .Select (a => (Account) new ACAccountWrapper (a, accountStore)) .ToList (); tcs.SetResult (accounts); } else { tcs.SetResult (new Account [0]); } }); return tcs.Task; } public override bool SupportsAuthentication { get { return false; } } protected override Authenticator GetAuthenticator () { throw new NotSupportedException ("Twitter5Service does support authenticating users. You should direct them to the Settings application."); } #endregion #region Account management public override bool SupportsSave { get { return false; } } public override void SaveAccount (Account account) { throw new NotSupportedException ("Twitter5Service does support saving user accounts. You should direct them to the Settings application."); } public override void DeleteAccount (Account account) { throw new NotSupportedException ("Twitter5Service does support deleting user accounts. You should direct them to the Settings application."); } #endregion } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication.Abstractions; using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Sql.Database.Model; using Microsoft.Azure.Commands.Sql.ElasticPool.Services; using Microsoft.Azure.Commands.Sql.Server.Adapter; using Microsoft.Azure.Commands.Sql.Services; using Microsoft.Azure.Management.Sql.LegacySdk.Models; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Azure.Management.Sql.Models; namespace Microsoft.Azure.Commands.Sql.Database.Services { /// <summary> /// Adapter for database operations /// </summary> public class AzureSqlDatabaseAdapter { /// <summary> /// Gets or sets the AzureSqlDatabaseCommunicator which has all the needed management clients /// </summary> private AzureSqlDatabaseCommunicator Communicator { get; set; } /// <summary> /// Gets or sets the AzureSqlElasticPoolCommunicator which has all the needed management clients /// </summary> private AzureSqlElasticPoolCommunicator ElasticPoolCommunicator { get; set; } /// <summary> /// Gets or sets the Azure profile /// </summary> public IAzureContext Context { get; set; } /// <summary> /// Gets or sets the Azure Subscription /// </summary> private IAzureSubscription _subscription { get; set; } /// <summary> /// Constructs a database adapter /// </summary> /// <param name="profile">The current azure profile</param> /// <param name="subscription">The current azure subscription</param> public AzureSqlDatabaseAdapter(IAzureContext context) { Context = context; _subscription = context.Subscription; Communicator = new AzureSqlDatabaseCommunicator(Context); ElasticPoolCommunicator = new AzureSqlElasticPoolCommunicator(Context); } /// <summary> /// Gets an Azure Sql Database by name. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="databaseName">The name of the Azure Sql Database</param> /// <returns>The Azure Sql Database object</returns> internal AzureSqlDatabaseModel GetDatabase(string resourceGroupName, string serverName, string databaseName) { var resp = Communicator.Get(resourceGroupName, serverName, databaseName); return CreateDatabaseModelFromResponse(resourceGroupName, serverName, resp); } /// <summary> /// Gets an Azure Sql Database by name with additional information. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="databaseName">The name of the Azure Sql Database</param> /// <returns>The Azure Sql Database object</returns> internal AzureSqlDatabaseModelExpanded GetDatabaseExpanded(string resourceGroupName, string serverName, string databaseName) { var resp = Communicator.GetExpanded(resourceGroupName, serverName, databaseName); return CreateExpandedDatabaseModelFromResponse(resourceGroupName, serverName, resp); } /// <summary> /// Gets a list of Azure Sql Databases. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlDatabaseModel> ListDatabases(string resourceGroupName, string serverName) { var resp = Communicator.List(resourceGroupName, serverName); return resp.Select((db) => { return CreateDatabaseModelFromResponse(resourceGroupName, serverName, db); }).ToList(); } /// <summary> /// Gets a list of Azure Sql Databases with additional information. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlDatabaseModelExpanded> ListDatabasesExpanded(string resourceGroupName, string serverName) { var resp = Communicator.ListExpanded(resourceGroupName, serverName); return resp.Select((db) => { return CreateExpandedDatabaseModelFromResponse(resourceGroupName, serverName, db); }).ToList(); } /// <summary> /// Creates or updates an Azure Sql Database with new AutoRest SDK. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The upserted Azure Sql Database from AutoRest SDK</returns> internal AzureSqlDatabaseModel UpsertDatabaseWithNewSdk(string resourceGroup, string serverName, AzureSqlDatabaseCreateOrUpdateModel model) { // Construct the ARM resource Id of the pool string elasticPoolId = string.IsNullOrWhiteSpace(model.Database.ElasticPoolName) ? null : AzureSqlDatabaseModel.PoolIdTemplate.FormatInvariant( _subscription.Id, resourceGroup, serverName, model.Database.ElasticPoolName); // Use AutoRest SDK var resp = Communicator.CreateOrUpdate(resourceGroup, serverName, model.Database.DatabaseName, new Management.Sql.Models.Database { Location = model.Database.Location, Tags = model.Database.Tags, Collation = model.Database.CollationName, Sku = string.IsNullOrWhiteSpace(model.Database.SkuName) ? null : new Sku() { Name = model.Database.SkuName, Tier = model.Database.Edition, Family = model.Database.Family, Capacity = model.Database.Capacity }, MaxSizeBytes = model.Database.MaxSizeBytes, ReadScale = model.Database.ReadScale.ToString(), SampleName = model.SampleName, ZoneRedundant = model.Database.ZoneRedundant, ElasticPoolId = elasticPoolId, LicenseType = model.Database.LicenseType }); return CreateDatabaseModelFromResponse(resourceGroup, serverName, resp); } /// <summary> /// Deletes a database /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="databaseName">The name of the Azure Sql Database to delete</param> public void RemoveDatabase(string resourceGroupName, string serverName, string databaseName) { Communicator.Remove(resourceGroupName, serverName, databaseName); } /// <summary> /// Gets the Location of the server. /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the server</param> /// <returns></returns> public string GetServerLocation(string resourceGroupName, string serverName) { AzureSqlServerAdapter serverAdapter = new AzureSqlServerAdapter(Context); var server = serverAdapter.GetServer(resourceGroupName, serverName); return server.Location; } /// <summary> /// Converts the response from the service to a powershell database object /// </summary> /// <param name="resourceGroup">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="database">The service response</param> /// <returns>The converted model</returns> public static AzureSqlDatabaseModel CreateDatabaseModelFromResponse(string resourceGroup, string serverName, Management.Sql.Models.Database database) { return new AzureSqlDatabaseModel(resourceGroup, serverName, database); } /// <summary> /// Converts the response from the service to a powershell database object /// </summary> /// <param name="resourceGroup">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="database">The service response</param> /// <returns>The converted model</returns> public static AzureSqlDatabaseModel CreateDatabaseModelFromResponse(string resourceGroup, string serverName, Management.Sql.LegacySdk.Models.Database database) { return new AzureSqlDatabaseModel(resourceGroup, serverName, database); } /// <summary> /// Converts the response from the service to a powershell database object /// </summary> /// <param name="resourceGroup">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="database">The service response</param> /// <returns>The converted model</returns> public static AzureSqlDatabaseModelExpanded CreateExpandedDatabaseModelFromResponse(string resourceGroup, string serverName, Management.Sql.LegacySdk.Models.Database database) { return new AzureSqlDatabaseModelExpanded(resourceGroup, serverName, database); } internal IEnumerable<AzureSqlDatabaseActivityModel> ListDatabaseActivity(string resourceGroupName, string serverName, string elasticPoolName, string databaseName, Guid? operationId) { if (!string.IsNullOrEmpty(elasticPoolName)) { var response = ElasticPoolCommunicator.ListDatabaseActivity(resourceGroupName, serverName, elasticPoolName); IEnumerable<AzureSqlDatabaseActivityModel> list = response.Select((r) => { return new AzureSqlDatabaseActivityModel() { DatabaseName = r.DatabaseName, EndTime = r.EndTime, ErrorCode = r.ErrorCode, ErrorMessage = r.ErrorMessage, ErrorSeverity = r.ErrorSeverity, Operation = r.Operation, OperationId = r.OperationId, PercentComplete = r.PercentComplete, ServerName = r.ServerName, StartTime = r.StartTime, State = r.State, Properties = new AzureSqlDatabaseActivityModel.DatabaseState() { Current = new Dictionary<string, string>() { {"CurrentElasticPoolName", r.CurrentElasticPoolName}, {"CurrentServiceObjectiveName", r.CurrentServiceObjective}, }, Requested = new Dictionary<string, string>() { {"RequestedElasticPoolName", r.RequestedElasticPoolName}, {"RequestedServiceObjectiveName", r.RequestedServiceObjective}, } } }; }); // Check if we have a database name constraint if (!string.IsNullOrEmpty(databaseName)) { list = list.Where(pl => string.Equals(pl.DatabaseName, databaseName, StringComparison.OrdinalIgnoreCase)); } return list.ToList(); } else { var response = Communicator.ListOperations(resourceGroupName, serverName, databaseName); IEnumerable<AzureSqlDatabaseActivityModel> list = response.Select((r) => { return new AzureSqlDatabaseActivityModel() { DatabaseName = r.DatabaseName, ErrorCode = r.ErrorCode, ErrorMessage = r.ErrorDescription, ErrorSeverity = r.ErrorSeverity, Operation = r.Operation, OperationId = Guid.Parse(r.Name), PercentComplete = r.PercentComplete, ServerName = r.ServerName, StartTime = r.StartTime, State = r.State, Properties = new AzureSqlDatabaseActivityModel.DatabaseState() { Current = new Dictionary<string, string>(), Requested = new Dictionary<string, string>() }, EstimatedCompletionTime = r.EstimatedCompletionTime, Description = r.Description, IsCancellable = r.IsCancellable }; }); // Check if we have a operation id constraint if (operationId.HasValue) { list = list.Where(pl => Guid.Equals(pl.OperationId, operationId)); } return list.ToList(); } } internal IEnumerable<AzureSqlDatabaseActivityModel> CancelDatabaseActivity(string resourceGroupName, string serverName, string elasticPoolName, string databaseName, Guid? operationId) { if (!string.IsNullOrEmpty(elasticPoolName)) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Microsoft.Azure.Commands.Sql.Properties.Resources.ElasticPoolDatabaseActivityCancelNotSupported)); } if (!operationId.HasValue) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Microsoft.Azure.Commands.Sql.Properties.Resources.OperationIdRequired)); } Communicator.CancelOperation(resourceGroupName, serverName, databaseName, operationId.Value); // After Cancel event is fired, state will be in 'CancelInProgress' for a while but should expect to finish in a minute return ListDatabaseActivity(resourceGroupName, serverName, elasticPoolName, databaseName, operationId); } public void RenameDatabase(string resourceGroupName, string serverName, string databaseName, string newName) { Communicator.Rename(resourceGroupName, serverName, databaseName, newName); } /// <summary> /// Get database sku name based on edition /// Edition | SkuName /// GeneralPurpose | GP /// BusinessCritical | BC /// Standard | Standard /// Basic | Basic /// Premium | Premium /// </summary> /// <param name="tier">Azure Sql database edition</param> /// <returns>The sku name</returns> public static string GetDatabaseSkuName(string tier) { if (string.IsNullOrWhiteSpace(tier)) return null; switch(tier.ToLowerInvariant()) { case "generalpurpose": return "GP"; case "businesscritical": return "BC"; default: return tier; } } /// <summary> /// Gets the Sku for the Dtu database. /// </summary> /// <param name="requestedServiceObjectiveName">Requested service objective name of the Azure Sql database</param> /// <param name="edition">Edition of the Azure Sql database</param> /// <returns></returns> public static Sku GetDtuDatabaseSku(string requestedServiceObjectiveName, string edition) { Sku sku = null; if (!string.IsNullOrWhiteSpace(requestedServiceObjectiveName) || !string.IsNullOrWhiteSpace(edition)) { sku = new Sku() { Name = string.IsNullOrWhiteSpace(requestedServiceObjectiveName) ? GetDatabaseSkuName(edition) : requestedServiceObjectiveName, Tier = edition }; } return sku; } } }
/* * 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.Drawing; using System.IO; using System.Net; using System.Reflection; using OpenSim.Framework; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenMetaverse.StructuredData; using Nwc.XmlRpc; using log4net; using OpenSim.Services.Connectors.Simulation; namespace OpenSim.Services.Connectors.Hypergrid { public class GatekeeperServiceConnector : SimulationServiceConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static UUID m_HGMapImage = new UUID("00000000-0000-1111-9999-000000000013"); private IAssetService m_AssetService; public GatekeeperServiceConnector() : base() { } public GatekeeperServiceConnector(IAssetService assService) { m_AssetService = assService; } protected override string AgentPath() { return "foreignagent/"; } protected override string ObjectPath() { return "foreignobject/"; } public bool LinkRegion(GridRegion info, out UUID regionID, out ulong realHandle, out string externalName, out string imageURL, out string reason) { regionID = UUID.Zero; imageURL = string.Empty; realHandle = 0; externalName = string.Empty; reason = string.Empty; Hashtable hash = new Hashtable(); hash["region_name"] = info.RegionName; IList paramList = new ArrayList(); paramList.Add(hash); XmlRpcRequest request = new XmlRpcRequest("link_region", paramList); m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Linking to " + info.ServerURI); XmlRpcResponse response = null; try { response = request.Send(info.ServerURI, 10000); } catch (Exception e) { m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Exception " + e.Message); reason = "Error contacting remote server"; return false; } if (response.IsFault) { reason = response.FaultString; m_log.ErrorFormat("[GATEKEEPER SERVICE CONNECTOR]: remote call returned an error: {0}", response.FaultString); return false; } hash = (Hashtable)response.Value; //foreach (Object o in hash) // m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value); try { bool success = false; Boolean.TryParse((string)hash["result"], out success); if (success) { UUID.TryParse((string)hash["uuid"], out regionID); //m_log.Debug(">> HERE, uuid: " + regionID); if ((string)hash["handle"] != null) { realHandle = Convert.ToUInt64((string)hash["handle"]); //m_log.Debug(">> HERE, realHandle: " + realHandle); } if (hash["region_image"] != null) { imageURL = (string)hash["region_image"]; //m_log.Debug(">> HERE, imageURL: " + imageURL); } if (hash["external_name"] != null) { externalName = (string)hash["external_name"]; //m_log.Debug(">> HERE, externalName: " + externalName); } } } catch (Exception e) { reason = "Error parsing return arguments"; m_log.Error("[GATEKEEPER SERVICE CONNECTOR]: Got exception while parsing hyperlink response " + e.StackTrace); return false; } return true; } public UUID GetMapImage(UUID regionID, string imageURL, string storagePath) { if (m_AssetService == null) { m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: No AssetService defined. Map tile not retrieved."); return m_HGMapImage; } UUID mapTile = m_HGMapImage; string filename = string.Empty; try { WebClient c = new WebClient(); string name = regionID.ToString(); filename = Path.Combine(storagePath, name + ".jpg"); m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: Map image at {0}, cached at {1}", imageURL, filename); if (!File.Exists(filename)) { m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: downloading..."); c.DownloadFile(imageURL, filename); } else { m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: using cached image"); } byte[] imageData = null; using (Bitmap bitmap = new Bitmap(filename)) { //m_log.Debug("Size: " + m.PhysicalDimension.Height + "-" + m.PhysicalDimension.Width); imageData = OpenJPEG.EncodeFromImage(bitmap, true); } AssetBase ass = new AssetBase(UUID.Random(), "region " + name, (sbyte)AssetType.Texture, regionID.ToString()); // !!! for now //info.RegionSettings.TerrainImageID = ass.FullID; ass.Data = imageData; mapTile = ass.FullID; // finally m_AssetService.Store(ass); } catch // LEGIT: Catching problems caused by OpenJPEG p/invoke { m_log.Info("[GATEKEEPER SERVICE CONNECTOR]: Failed getting/storing map image, because it is probably already in the cache"); } return mapTile; } public GridRegion GetHyperlinkRegion(GridRegion gatekeeper, UUID regionID) { Hashtable hash = new Hashtable(); hash["region_uuid"] = regionID.ToString(); IList paramList = new ArrayList(); paramList.Add(hash); XmlRpcRequest request = new XmlRpcRequest("get_region", paramList); m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: contacting " + gatekeeper.ServerURI); XmlRpcResponse response = null; try { response = request.Send(gatekeeper.ServerURI, 10000); } catch (Exception e) { m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Exception " + e.Message); return null; } if (response.IsFault) { m_log.ErrorFormat("[GATEKEEPER SERVICE CONNECTOR]: remote call returned an error: {0}", response.FaultString); return null; } hash = (Hashtable)response.Value; //foreach (Object o in hash) // m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value); try { bool success = false; Boolean.TryParse((string)hash["result"], out success); if (success) { GridRegion region = new GridRegion(); UUID.TryParse((string)hash["uuid"], out region.RegionID); //m_log.Debug(">> HERE, uuid: " + region.RegionID); int n = 0; if (hash["x"] != null) { Int32.TryParse((string)hash["x"], out n); region.RegionLocX = n; //m_log.Debug(">> HERE, x: " + region.RegionLocX); } if (hash["y"] != null) { Int32.TryParse((string)hash["y"], out n); region.RegionLocY = n; //m_log.Debug(">> HERE, y: " + region.RegionLocY); } if (hash["region_name"] != null) { region.RegionName = (string)hash["region_name"]; //m_log.Debug(">> HERE, region_name: " + region.RegionName); } if (hash["hostname"] != null) { region.ExternalHostName = (string)hash["hostname"]; //m_log.Debug(">> HERE, hostname: " + region.ExternalHostName); } if (hash["http_port"] != null) { uint p = 0; UInt32.TryParse((string)hash["http_port"], out p); region.HttpPort = p; //m_log.Debug(">> HERE, http_port: " + region.HttpPort); } if (hash["internal_port"] != null) { int p = 0; Int32.TryParse((string)hash["internal_port"], out p); region.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), p); //m_log.Debug(">> HERE, internal_port: " + region.InternalEndPoint); } if (hash["server_uri"] != null) { region.ServerURI = (string)hash["server_uri"]; //m_log.Debug(">> HERE, server_uri: " + region.ServerURI); } // Successful return return region; } } catch (Exception e) { m_log.Error("[GATEKEEPER SERVICE CONNECTOR]: Got exception while parsing hyperlink response " + e.StackTrace); return null; } return null; } } }
using NBitcoin; using NBitcoin.Crypto; using NBitcoin.RPC; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WalletWasabi.BitcoinCore.Rpc; using WalletWasabi.CoinJoin.Client.Clients; using WalletWasabi.CoinJoin.Common.Models; using WalletWasabi.CoinJoin.Coordinator; using WalletWasabi.CoinJoin.Coordinator.Rounds; using WalletWasabi.Tests.Helpers; using WalletWasabi.Tests.XunitConfiguration; using WalletWasabi.Tor.Http; using Xunit; using static WalletWasabi.Crypto.SchnorrBlinding; using UnblindedSignature = WalletWasabi.Crypto.UnblindedSignature; namespace WalletWasabi.Tests.RegressionTests { [Collection("RegTest collection")] public class DosTests { public DosTests(RegTestFixture regTestFixture) { RegTestFixture = regTestFixture; BackendHttpClient = new ClearnetHttpClient(() => new Uri(RegTestFixture.BackendEndPoint)); SatoshiClient = new SatoshiClient(BackendHttpClient); } private RegTestFixture RegTestFixture { get; } public SatoshiClient SatoshiClient { get; } public IHttpClient BackendHttpClient { get; } private async Task WaitForTimeoutAsync() { var times = 0; while (!(await SatoshiClient.GetAllRoundStatesAsync()).All(x => x.Phase == RoundPhase.InputRegistration)) { await Task.Delay(100); if (times > 50) // 5 sec, 3 should be enough { throw new TimeoutException("Not all rounds were in InputRegistration."); } times++; } } [Fact] public async Task BanningTestsAsync() { (_, IRPCClient rpc, Network network, Coordinator coordinator, _, _, _) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1); Money denomination = Money.Coins(0.1m); decimal coordinatorFeePercent = 0.1m; int anonymitySet = 3; int connectionConfirmationTimeout = 120; var roundConfig = RegTestFixture.CreateRoundConfig(denomination, 140, 0.7, coordinatorFeePercent, anonymitySet, 240, connectionConfirmationTimeout, 1, 1, 1, 24, true, 11); coordinator.RoundConfig.UpdateOrDefault(roundConfig, toFile: true); coordinator.AbortAllRoundsInInputRegistration(""); await rpc.GenerateAsync(3); // So to make sure we have enough money. Uri baseUri = new Uri(RegTestFixture.BackendEndPoint); var fundingTxCount = 0; var inputRegistrationUsers = new List<(Requester requester, BlindedOutputWithNonceIndex blinded, BitcoinAddress activeOutputAddress, BitcoinAddress changeOutputAddress, IEnumerable<InputProofModel> inputProofModels, List<(Key key, BitcoinWitPubKeyAddress address, uint256 txHash, Transaction tx, OutPoint input)> userInputData)>(); CoordinatorRound round = null; for (int i = 0; i < roundConfig.AnonymitySet; i++) { var userInputData = new List<(Key key, BitcoinWitPubKeyAddress inputAddress, uint256 txHash, Transaction tx, OutPoint input)>(); var activeOutputAddress = new Key().PubKey.GetAddress(ScriptPubKeyType.Segwit, network); var changeOutputAddress = new Key().PubKey.GetAddress(ScriptPubKeyType.Segwit, network); round = coordinator.GetCurrentInputRegisterableRoundOrDefault(); Requester requester = new Requester(); var nonce = round.NonceProvider.GetNextNonce(); var blinded = new BlindedOutputWithNonceIndex(nonce.N, requester.BlindScript(round.MixingLevels.GetBaseLevel().SignerKey.PubKey, nonce.R, activeOutputAddress.ScriptPubKey)); uint256 blindedOutputScriptsHash = new uint256(Hashes.SHA256(blinded.BlindedOutput.ToBytes())); var inputProofModels = new List<InputProofModel>(); int numberOfInputs = CryptoHelpers.RandomInt(1, 6); var receiveSatoshiSum = 0; for (int j = 0; j < numberOfInputs; j++) { var key = new Key(); var receiveSatoshi = CryptoHelpers.RandomInt(1000, 100000000); receiveSatoshiSum += receiveSatoshi; if (j == numberOfInputs - 1) { receiveSatoshi = 100000000; } BitcoinWitPubKeyAddress inputAddress = key.PubKey.GetSegwitAddress(network); uint256 txHash = await rpc.SendToAddressAsync(inputAddress, Money.Satoshis(receiveSatoshi)); fundingTxCount++; Assert.NotNull(txHash); Transaction transaction = await rpc.GetRawTransactionAsync(txHash); var coin = transaction.Outputs.GetCoins(inputAddress.ScriptPubKey).Single(); OutPoint input = coin.Outpoint; var inputProof = new InputProofModel { Input = input, Proof = key.SignCompact(blindedOutputScriptsHash) }; inputProofModels.Add(inputProof); GetTxOutResponse getTxOutResponse = await rpc.GetTxOutAsync(input.Hash, (int)input.N, includeMempool: true); // Check if inputs are unspent. Assert.NotNull(getTxOutResponse); userInputData.Add((key, inputAddress, txHash, transaction, input)); } inputRegistrationUsers.Add((requester, blinded, activeOutputAddress, changeOutputAddress, inputProofModels, userInputData)); } var mempool = await rpc.GetRawMempoolAsync(); Assert.Equal(inputRegistrationUsers.SelectMany(x => x.userInputData).Count(), mempool.Length); while ((await rpc.GetRawMempoolAsync()).Length != 0) { await rpc.GenerateAsync(1); } var aliceClients = new List<Task<AliceClient4>>(); foreach (var user in inputRegistrationUsers) { aliceClients.Add(AliceClientBase.CreateNewAsync(round.RoundId, new[] { user.activeOutputAddress }, new[] { round.MixingLevels.GetBaseLevel().SignerKey.PubKey }, new[] { user.requester }, network, user.changeOutputAddress, new[] { user.blinded }, user.inputProofModels, BackendHttpClient)); } long roundId = 0; var users = new List<(Requester requester, BlindedOutputWithNonceIndex blinded, BitcoinAddress activeOutputAddress, BitcoinAddress changeOutputAddress, IEnumerable<InputProofModel> inputProofModels, List<(Key key, BitcoinWitPubKeyAddress address, uint256 txHash, Transaction tx, OutPoint input)> userInputData, AliceClient4 aliceClient, UnblindedSignature unblindedSignature)>(); for (int i = 0; i < inputRegistrationUsers.Count; i++) { var user = inputRegistrationUsers[i]; var request = aliceClients[i]; var aliceClient = await request; if (roundId == 0) { roundId = aliceClient.RoundId; } else { Assert.Equal(roundId, aliceClient.RoundId); } // Because it's valuetuple. users.Add((user.requester, user.blinded, user.activeOutputAddress, user.changeOutputAddress, user.inputProofModels, user.userInputData, aliceClient, null)); } Assert.Equal(users.Count, roundConfig.AnonymitySet); var confirmationRequests = new List<Task<(RoundPhase currentPhase, IEnumerable<ActiveOutput>)>>(); foreach (var user in users) { confirmationRequests.Add(user.aliceClient.PostConfirmationAsync()); } RoundPhase roundPhase = RoundPhase.InputRegistration; int k = 0; foreach (var request in confirmationRequests) { var resp = await request; if (roundPhase == RoundPhase.InputRegistration) { roundPhase = resp.currentPhase; } else { Assert.Equal(roundPhase, resp.currentPhase); } var user = users.ElementAt(k); user.unblindedSignature = resp.Item2.First().Signature; } { var times = 0; while (!(await SatoshiClient.GetAllRoundStatesAsync()).All(x => x.Phase == RoundPhase.InputRegistration)) { await Task.Delay(100); if (times > 50) // 5 sec, 3 should be enough { throw new TimeoutException("Not all rounds were in InputRegistration."); } times++; } } int bannedCount = coordinator.UtxoReferee.CountBanned(false); Assert.Equal(0, bannedCount); aliceClients.Clear(); round = coordinator.GetCurrentInputRegisterableRoundOrDefault(); foreach (var user in inputRegistrationUsers) { aliceClients.Add(AliceClientBase.CreateNewAsync(round.RoundId, new[] { user.activeOutputAddress }, new[] { round.MixingLevels.GetBaseLevel().SignerKey.PubKey }, new[] { user.requester }, network, user.changeOutputAddress, new[] { user.blinded }, user.inputProofModels, BackendHttpClient)); } roundId = 0; users = new List<(Requester requester, BlindedOutputWithNonceIndex blinded, BitcoinAddress activeOutputAddress, BitcoinAddress changeOutputAddress, IEnumerable<InputProofModel> inputProofModels, List<(Key key, BitcoinWitPubKeyAddress address, uint256 txHash, Transaction tx, OutPoint input)> userInputData, AliceClient4 aliceClient, UnblindedSignature unblindedSignature)>(); for (int i = 0; i < inputRegistrationUsers.Count; i++) { var user = inputRegistrationUsers[i]; var request = aliceClients[i]; var aliceClient = await request; if (roundId == 0) { roundId = aliceClient.RoundId; } else { Assert.Equal(roundId, aliceClient.RoundId); } // Because it's valuetuple. users.Add((user.requester, user.blinded, user.activeOutputAddress, user.changeOutputAddress, user.inputProofModels, user.userInputData, aliceClient, null)); } Assert.Equal(users.Count, roundConfig.AnonymitySet); confirmationRequests = new List<Task<(RoundPhase currentPhase, IEnumerable<ActiveOutput>)>>(); foreach (var user in users) { confirmationRequests.Add(user.aliceClient.PostConfirmationAsync()); } { var times = 0; while (!(await SatoshiClient.GetAllRoundStatesAsync()).All(x => x.Phase == RoundPhase.InputRegistration)) { await Task.Delay(100); if (times > 50) // 5 sec, 3 should be enough { throw new TimeoutException("Not all rounds were in InputRegistration."); } times++; } } bannedCount = coordinator.UtxoReferee.CountBanned(false); Assert.True(bannedCount >= roundConfig.AnonymitySet); foreach (var aliceClient in aliceClients) { aliceClient?.Dispose(); } } [Fact] public async Task NotingTestsAsync() { (_, IRPCClient rpc, Network network, Coordinator coordinator, _, _, _) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1); Money denomination = Money.Coins(1m); decimal coordinatorFeePercent = 0.1m; int anonymitySet = 2; int connectionConfirmationTimeout = 1; bool doesNoteBeforeBan = true; CoordinatorRoundConfig roundConfig = RegTestFixture.CreateRoundConfig(denomination, 140, 0.7, coordinatorFeePercent, anonymitySet, 240, connectionConfirmationTimeout, 1, 1, 1, 24, doesNoteBeforeBan, 11); coordinator.RoundConfig.UpdateOrDefault(roundConfig, toFile: true); coordinator.AbortAllRoundsInInputRegistration(""); Uri baseUri = new Uri(RegTestFixture.BackendEndPoint); var registerRequests = new List<(BitcoinWitPubKeyAddress changeOutputAddress, BlindedOutputWithNonceIndex blindedData, InputProofModel[] inputsProofs)>(); AliceClient4 aliceClientBackup = null; CoordinatorRound round = coordinator.GetCurrentInputRegisterableRoundOrDefault(); for (int i = 0; i < roundConfig.AnonymitySet; i++) { BitcoinWitPubKeyAddress activeOutputAddress = new Key().PubKey.GetSegwitAddress(network); BitcoinWitPubKeyAddress changeOutputAddress = new Key().PubKey.GetSegwitAddress(network); Key inputKey = new Key(); BitcoinWitPubKeyAddress inputAddress = inputKey.PubKey.GetSegwitAddress(network); var requester = new Requester(); var nonce = round.NonceProvider.GetNextNonce(); var blinded = new BlindedOutputWithNonceIndex(nonce.N, requester.BlindScript(round.MixingLevels.GetBaseLevel().SignerKey.PubKey, nonce.R, activeOutputAddress.ScriptPubKey)); uint256 blindedOutputScriptsHash = new uint256(Hashes.SHA256(blinded.BlindedOutput.ToBytes())); uint256 txHash = await rpc.SendToAddressAsync(inputAddress, Money.Coins(2)); await rpc.GenerateAsync(1); Transaction transaction = await rpc.GetRawTransactionAsync(txHash); Coin coin = transaction.Outputs.GetCoins(inputAddress.ScriptPubKey).Single(); OutPoint input = coin.Outpoint; InputProofModel inputProof = new InputProofModel { Input = input, Proof = inputKey.SignCompact(blindedOutputScriptsHash) }; InputProofModel[] inputsProofs = new InputProofModel[] { inputProof }; registerRequests.Add((changeOutputAddress, blinded, inputsProofs)); aliceClientBackup = await AliceClientBase.CreateNewAsync(round.RoundId, new[] { activeOutputAddress }, new[] { round.MixingLevels.GetBaseLevel().SignerKey.PubKey }, new[] { requester }, network, changeOutputAddress, new[] { blinded }, inputsProofs, BackendHttpClient); } await WaitForTimeoutAsync(); int bannedCount = coordinator.UtxoReferee.CountBanned(false); Assert.Equal(0, bannedCount); int notedCount = coordinator.UtxoReferee.CountBanned(true); Assert.Equal(anonymitySet, notedCount); round = coordinator.GetCurrentInputRegisterableRoundOrDefault(); foreach (var registerRequest in registerRequests) { await AliceClientBase.CreateNewAsync(round.RoundId, aliceClientBackup.RegisteredAddresses, round.MixingLevels.GetAllLevels().Select(x => x.SignerKey.PubKey), aliceClientBackup.Requesters, network, registerRequest.changeOutputAddress, new[] { registerRequest.blindedData }, registerRequest.inputsProofs, BackendHttpClient); } await WaitForTimeoutAsync(); bannedCount = coordinator.UtxoReferee.CountBanned(false); Assert.Equal(anonymitySet, bannedCount); notedCount = coordinator.UtxoReferee.CountBanned(true); Assert.Equal(anonymitySet, notedCount); } } }
#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 #if HAVE_ASYNC using System; using System.Globalization; using System.Threading; #if HAVE_BIG_INTEGER using System.Numerics; #endif using System.Threading.Tasks; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { public partial class JsonTextReader { // It's not safe to perform the async methods here in a derived class as if the synchronous equivalent // has been overriden then the asychronous method will no longer be doing the same operation #if HAVE_ASYNC // Double-check this isn't included inappropriately. private readonly bool _safeAsync; #endif /// <summary> /// Asynchronously reads the next JSON token from the source. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/> /// property returns <c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoReadAsync(cancellationToken) : base.ReadAsync(cancellationToken); } internal Task<bool> DoReadAsync(CancellationToken cancellationToken) { EnsureBuffer(); while (true) { switch (_currentState) { case State.Start: case State.Property: case State.Array: case State.ArrayStart: case State.Constructor: case State.ConstructorStart: return ParseValueAsync(cancellationToken); case State.Object: case State.ObjectStart: return ParseObjectAsync(cancellationToken); case State.PostValue: Task<bool> task = ParsePostValueAsync(false, cancellationToken); if (task.Status == TaskStatus.RanToCompletion) { if (task.Result) { return AsyncUtils.True; } } else { return DoReadAsync(task, cancellationToken); } break; case State.Finished: return ReadFromFinishedAsync(cancellationToken); default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); } } } private async Task<bool> DoReadAsync(Task<bool> task, CancellationToken cancellationToken) { bool result = await task.ConfigureAwait(false); if (result) { return true; } return await DoReadAsync(cancellationToken).ConfigureAwait(false); } private async Task<bool> ParsePostValueAsync(bool ignoreComments, CancellationToken cancellationToken) { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0) { _currentState = State.Finished; return false; } } else { _charPos++; } break; case '}': _charPos++; SetToken(JsonToken.EndObject); return true; case ']': _charPos++; SetToken(JsonToken.EndArray); return true; case ')': _charPos++; SetToken(JsonToken.EndConstructor); return true; case '/': await ParseCommentAsync(!ignoreComments, cancellationToken).ConfigureAwait(false); if (!ignoreComments) { return true; } break; case ',': _charPos++; // finished parsing SetStateBasedOnCurrent(); return false; case ' ': case StringUtils.Tab: // eat _charPos++; break; case StringUtils.CarriageReturn: await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; } else { // handle multiple content without comma delimiter if (SupportMultipleContent && Depth == 0) { SetStateBasedOnCurrent(); return false; } throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } break; } } } private async Task<bool> ReadFromFinishedAsync(CancellationToken cancellationToken) { if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false)) { await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false); if (_isEndOfFile) { SetToken(JsonToken.None); return false; } if (_chars[_charPos] == '/') { await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false); return true; } throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } SetToken(JsonToken.None); return false; } private Task<int> ReadDataAsync(bool append, CancellationToken cancellationToken) { return ReadDataAsync(append, 0, cancellationToken); } private async Task<int> ReadDataAsync(bool append, int charsRequired, CancellationToken cancellationToken) { if (_isEndOfFile) { return 0; } PrepareBufferForReadData(append, charsRequired); int charsRead = await _reader.ReadAsync(_chars, _charsUsed, _chars.Length - _charsUsed - 1, cancellationToken).ConfigureAwait(false); _charsUsed += charsRead; if (charsRead == 0) { _isEndOfFile = true; } _chars[_charsUsed] = '\0'; return charsRead; } private async Task<bool> ParseValueAsync(CancellationToken cancellationToken) { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0) { return false; } } else { _charPos++; } break; case '"': case '\'': await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false); return true; case 't': await ParseTrueAsync(cancellationToken).ConfigureAwait(false); return true; case 'f': await ParseFalseAsync(cancellationToken).ConfigureAwait(false); return true; case 'n': if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false)) { switch (_chars[_charPos + 1]) { case 'u': await ParseNullAsync(cancellationToken).ConfigureAwait(false); break; case 'e': await ParseConstructorAsync(cancellationToken).ConfigureAwait(false); break; default: throw CreateUnexpectedCharacterException(_chars[_charPos]); } } else { _charPos++; throw CreateUnexpectedEndException(); } return true; case 'N': await ParseNumberNaNAsync(ReadType.Read, cancellationToken).ConfigureAwait(false); return true; case 'I': await ParseNumberPositiveInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false); return true; case '-': if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I') { await ParseNumberNegativeInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false); } else { await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false); } return true; case '/': await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false); return true; case 'u': await ParseUndefinedAsync(cancellationToken).ConfigureAwait(false); return true; case '{': _charPos++; SetToken(JsonToken.StartObject); return true; case '[': _charPos++; SetToken(JsonToken.StartArray); return true; case ']': _charPos++; SetToken(JsonToken.EndArray); return true; case ',': // don't increment position, the next call to read will handle comma // this is done to handle multiple empty comma values SetToken(JsonToken.Undefined); return true; case ')': _charPos++; SetToken(JsonToken.EndConstructor); return true; case StringUtils.CarriageReturn: await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; break; } if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.') { ParseNumber(ReadType.Read); return true; } throw CreateUnexpectedCharacterException(currentChar); } } } private async Task ReadStringIntoBufferAsync(char quote, CancellationToken cancellationToken) { int charPos = _charPos; int initialPosition = _charPos; int lastWritePosition = _charPos; _stringBuffer.Position = 0; while (true) { switch (_chars[charPos++]) { case '\0': if (_charsUsed == charPos - 1) { charPos--; if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0) { _charPos = charPos; throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } } break; case '\\': _charPos = charPos; if (!await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false)) { throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } // start of escape sequence int escapeStartPos = charPos - 1; char currentChar = _chars[charPos]; charPos++; char writeChar; switch (currentChar) { case 'b': writeChar = '\b'; break; case 't': writeChar = '\t'; break; case 'n': writeChar = '\n'; break; case 'f': writeChar = '\f'; break; case 'r': writeChar = '\r'; break; case '\\': writeChar = '\\'; break; case '"': case '\'': case '/': writeChar = currentChar; break; case 'u': _charPos = charPos; writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false); if (StringUtils.IsLowSurrogate(writeChar)) { // low surrogate with no preceding high surrogate; this char is replaced writeChar = UnicodeReplacementChar; } else if (StringUtils.IsHighSurrogate(writeChar)) { bool anotherHighSurrogate; // loop for handling situations where there are multiple consecutive high surrogates do { anotherHighSurrogate = false; // potential start of a surrogate pair if (await EnsureCharsAsync(2, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u') { char highSurrogate = writeChar; _charPos += 2; writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false); if (StringUtils.IsLowSurrogate(writeChar)) { // a valid surrogate pair! } else if (StringUtils.IsHighSurrogate(writeChar)) { // another high surrogate; replace current and start check over highSurrogate = UnicodeReplacementChar; anotherHighSurrogate = true; } else { // high surrogate not followed by low surrogate; original char is replaced highSurrogate = UnicodeReplacementChar; } EnsureBufferNotEmpty(); WriteCharToBuffer(highSurrogate, lastWritePosition, escapeStartPos); lastWritePosition = _charPos; } else { // there are not enough remaining chars for the low surrogate or is not follow by unicode sequence // replace high surrogate and continue on as usual writeChar = UnicodeReplacementChar; } } while (anotherHighSurrogate); } charPos = _charPos; break; default: _charPos = charPos; throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar)); } EnsureBufferNotEmpty(); WriteCharToBuffer(writeChar, lastWritePosition, escapeStartPos); lastWritePosition = charPos; break; case StringUtils.CarriageReturn: _charPos = charPos - 1; await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false); charPos = _charPos; break; case StringUtils.LineFeed: _charPos = charPos - 1; ProcessLineFeed(); charPos = _charPos; break; case '"': case '\'': if (_chars[charPos - 1] == quote) { FinishReadStringIntoBuffer(charPos - 1, initialPosition, lastWritePosition); return; } break; } } } private Task ProcessCarriageReturnAsync(bool append, CancellationToken cancellationToken) { _charPos++; Task<bool> task = EnsureCharsAsync(1, append, cancellationToken); if (task.Status == TaskStatus.RanToCompletion) { SetNewLine(task.Result); return AsyncUtils.CompletedTask; } return ProcessCarriageReturnAsync(task); } private async Task ProcessCarriageReturnAsync(Task<bool> task) { SetNewLine(await task.ConfigureAwait(false)); } private async Task<char> ParseUnicodeAsync(CancellationToken cancellationToken) { return ConvertUnicode(await EnsureCharsAsync(4, true, cancellationToken).ConfigureAwait(false)); } private Task<bool> EnsureCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken) { if (_charPos + relativePosition < _charsUsed) { return AsyncUtils.True; } if (_isEndOfFile) { return AsyncUtils.False; } return ReadCharsAsync(relativePosition, append, cancellationToken); } private async Task<bool> ReadCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken) { int charsRequired = _charPos + relativePosition - _charsUsed + 1; // it is possible that the TextReader doesn't return all data at once // repeat read until the required text is returned or the reader is out of content do { int charsRead = await ReadDataAsync(append, charsRequired, cancellationToken).ConfigureAwait(false); // no more content if (charsRead == 0) { return false; } charsRequired -= charsRead; } while (charsRequired > 0); return true; } private async Task<bool> ParseObjectAsync(CancellationToken cancellationToken) { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0) { return false; } } else { _charPos++; } break; case '}': SetToken(JsonToken.EndObject); _charPos++; return true; case '/': await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false); return true; case StringUtils.CarriageReturn: await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: if (char.IsWhiteSpace(currentChar)) { // eat _charPos++; } else { return await ParsePropertyAsync(cancellationToken).ConfigureAwait(false); } break; } } } private async Task ParseCommentAsync(bool setToken, CancellationToken cancellationToken) { // should have already parsed / character before reaching this method _charPos++; if (!await EnsureCharsAsync(1, false, cancellationToken).ConfigureAwait(false)) { throw JsonReaderException.Create(this, "Unexpected end while parsing comment."); } bool singlelineComment; if (_chars[_charPos] == '*') { singlelineComment = false; } else if (_chars[_charPos] == '/') { singlelineComment = true; } else { throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } _charPos++; int initialPosition = _charPos; while (true) { switch (_chars[_charPos]) { case '\0': if (_charsUsed == _charPos) { if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0) { if (!singlelineComment) { throw JsonReaderException.Create(this, "Unexpected end while parsing comment."); } EndComment(setToken, initialPosition, _charPos); return; } } else { _charPos++; } break; case '*': _charPos++; if (!singlelineComment) { if (await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false)) { if (_chars[_charPos] == '/') { EndComment(setToken, initialPosition, _charPos - 1); _charPos++; return; } } } break; case StringUtils.CarriageReturn: if (singlelineComment) { EndComment(setToken, initialPosition, _charPos); return; } await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false); break; case StringUtils.LineFeed: if (singlelineComment) { EndComment(setToken, initialPosition, _charPos); return; } ProcessLineFeed(); break; default: _charPos++; break; } } } private async Task EatWhitespaceAsync(CancellationToken cancellationToken) { while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (_charsUsed == _charPos) { if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0) { return; } } else { _charPos++; } break; case StringUtils.CarriageReturn: await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; default: if (currentChar == ' ' || char.IsWhiteSpace(currentChar)) { _charPos++; } else { return; } break; } } } private async Task ParseStringAsync(char quote, ReadType readType, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); _charPos++; ShiftBufferIfNeeded(); await ReadStringIntoBufferAsync(quote, cancellationToken).ConfigureAwait(false); ParseReadString(quote, readType); } private async Task<bool> MatchValueAsync(string value, CancellationToken cancellationToken) { return MatchValue(await EnsureCharsAsync(value.Length - 1, true, cancellationToken).ConfigureAwait(false), value); } private async Task<bool> MatchValueWithTrailingSeparatorAsync(string value, CancellationToken cancellationToken) { // will match value and then move to the next character, checking that it is a separator character if (!await MatchValueAsync(value, cancellationToken).ConfigureAwait(false)) { return false; } if (!await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false)) { return true; } return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0'; } private async Task MatchAndSetAsync(string value, JsonToken newToken, object tokenValue, CancellationToken cancellationToken) { if (await MatchValueWithTrailingSeparatorAsync(value, cancellationToken).ConfigureAwait(false)) { SetToken(newToken, tokenValue); } else { throw JsonReaderException.Create(this, "Error parsing " + newToken.ToString().ToLowerInvariant() + " value."); } } private Task ParseTrueAsync(CancellationToken cancellationToken) { return MatchAndSetAsync(JsonConvert.True, JsonToken.Boolean, true, cancellationToken); } private Task ParseFalseAsync(CancellationToken cancellationToken) { return MatchAndSetAsync(JsonConvert.False, JsonToken.Boolean, false, cancellationToken); } private Task ParseNullAsync(CancellationToken cancellationToken) { return MatchAndSetAsync(JsonConvert.Null, JsonToken.Null, null, cancellationToken); } private async Task ParseConstructorAsync(CancellationToken cancellationToken) { if (await MatchValueWithTrailingSeparatorAsync("new", cancellationToken).ConfigureAwait(false)) { await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false); int initialPosition = _charPos; int endPosition; while (true) { char currentChar = _chars[_charPos]; if (currentChar == '\0') { if (_charsUsed == _charPos) { if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0) { throw JsonReaderException.Create(this, "Unexpected end while parsing constructor."); } } else { endPosition = _charPos; _charPos++; break; } } else if (char.IsLetterOrDigit(currentChar)) { _charPos++; } else if (currentChar == StringUtils.CarriageReturn) { endPosition = _charPos; await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false); break; } else if (currentChar == StringUtils.LineFeed) { endPosition = _charPos; ProcessLineFeed(); break; } else if (char.IsWhiteSpace(currentChar)) { endPosition = _charPos; _charPos++; break; } else if (currentChar == '(') { endPosition = _charPos; break; } else { throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } _stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition); string constructorName = _stringReference.ToString(); await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false); if (_chars[_charPos] != '(') { throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } _charPos++; ClearRecentString(); SetToken(JsonToken.StartConstructor, constructorName); } else { throw JsonReaderException.Create(this, "Unexpected content while parsing JSON."); } } private async Task<object> ParseNumberNaNAsync(ReadType readType, CancellationToken cancellationToken) { return ParseNumberNaN(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NaN, cancellationToken).ConfigureAwait(false)); } private async Task<object> ParseNumberPositiveInfinityAsync(ReadType readType, CancellationToken cancellationToken) { return ParseNumberPositiveInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.PositiveInfinity, cancellationToken).ConfigureAwait(false)); } private async Task<object> ParseNumberNegativeInfinityAsync(ReadType readType, CancellationToken cancellationToken) { return ParseNumberNegativeInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NegativeInfinity, cancellationToken).ConfigureAwait(false)); } private async Task ParseNumberAsync(ReadType readType, CancellationToken cancellationToken) { ShiftBufferIfNeeded(); char firstChar = _chars[_charPos]; int initialPosition = _charPos; await ReadNumberIntoBufferAsync(cancellationToken).ConfigureAwait(false); ParseReadNumber(readType, firstChar, initialPosition); } private Task ParseUndefinedAsync(CancellationToken cancellationToken) { return MatchAndSetAsync(JsonConvert.Undefined, JsonToken.Undefined, null, cancellationToken); } private async Task<bool> ParsePropertyAsync(CancellationToken cancellationToken) { char firstChar = _chars[_charPos]; char quoteChar; if (firstChar == '"' || firstChar == '\'') { _charPos++; quoteChar = firstChar; ShiftBufferIfNeeded(); await ReadStringIntoBufferAsync(quoteChar, cancellationToken).ConfigureAwait(false); } else if (ValidIdentifierChar(firstChar)) { quoteChar = '\0'; ShiftBufferIfNeeded(); await ParseUnquotedPropertyAsync(cancellationToken).ConfigureAwait(false); } else { throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } string propertyName; if (NameTable != null) { propertyName = NameTable.Get(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length) // no match in name table ?? _stringReference.ToString(); } else { propertyName = _stringReference.ToString(); } await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false); if (_chars[_charPos] != ':') { throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } _charPos++; SetToken(JsonToken.PropertyName, propertyName); _quoteChar = quoteChar; ClearRecentString(); return true; } private async Task ReadNumberIntoBufferAsync(CancellationToken cancellationToken) { int charPos = _charPos; while (true) { char currentChar = _chars[charPos]; if (currentChar == '\0') { _charPos = charPos; if (_charsUsed == charPos) { if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0) { return; } } else { return; } } else if (ReadNumberCharIntoBuffer(currentChar, charPos)) { return; } else { charPos++; } } } private async Task ParseUnquotedPropertyAsync(CancellationToken cancellationToken) { int initialPosition = _charPos; // parse unquoted property name until whitespace or colon while (true) { char currentChar = _chars[_charPos]; if (currentChar == '\0') { if (_charsUsed == _charPos) { if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0) { throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name."); } continue; } _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); return; } if (ReadUnquotedPropertyReportIfDone(currentChar, initialPosition)) { return; } } } private async Task<bool> ReadNullCharAsync(CancellationToken cancellationToken) { if (_charsUsed == _charPos) { if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0) { _isEndOfFile = true; return true; } } else { _charPos++; } return false; } private async Task HandleNullAsync(CancellationToken cancellationToken) { if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false)) { if (_chars[_charPos + 1] == 'u') { await ParseNullAsync(cancellationToken).ConfigureAwait(false); return; } _charPos += 2; throw CreateUnexpectedCharacterException(_chars[_charPos - 1]); } _charPos = _charsUsed; throw CreateUnexpectedEndException(); } private async Task ReadFinishedAsync(CancellationToken cancellationToken) { if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false)) { await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false); if (_isEndOfFile) { SetToken(JsonToken.None); return; } if (_chars[_charPos] == '/') { await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false); } else { throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } } SetToken(JsonToken.None); } private async Task<object> ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken) { EnsureBuffer(); switch (_currentState) { case State.PostValue: if (await ParsePostValueAsync(true, cancellationToken)) { return null; } goto case State.Start; case State.Start: case State.Property: case State.Array: case State.ArrayStart: case State.Constructor: case State.ConstructorStart: while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false)) { SetToken(JsonToken.None, null, false); return null; } break; case '"': case '\'': await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false); return FinishReadQuotedStringValue(readType); case '-': if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I') { return ParseNumberNegativeInfinity(readType); } else { await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false); return Value; } case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (readType != ReadType.ReadAsString) { _charPos++; throw CreateUnexpectedCharacterException(currentChar); } await ParseNumberAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false); return Value; case 't': case 'f': if (readType != ReadType.ReadAsString) { _charPos++; throw CreateUnexpectedCharacterException(currentChar); } string expected = currentChar == 't' ? JsonConvert.True : JsonConvert.False; if (!await MatchValueWithTrailingSeparatorAsync(expected, cancellationToken).ConfigureAwait(false)) { throw CreateUnexpectedCharacterException(_chars[_charPos]); } SetToken(JsonToken.String, expected); return expected; case 'I': return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false); case 'N': return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false); case 'n': await HandleNullAsync(cancellationToken).ConfigureAwait(false); return null; case '/': await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(currentChar); case StringUtils.CarriageReturn: await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(currentChar)) { throw CreateUnexpectedCharacterException(currentChar); } // eat break; } } case State.Finished: await ReadFinishedAsync(cancellationToken).ConfigureAwait(false); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); } } private async Task<object> ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken) { EnsureBuffer(); switch (_currentState) { case State.PostValue: if (await ParsePostValueAsync(true, cancellationToken)) { return null; } goto case State.Start; case State.Start: case State.Property: case State.Array: case State.ArrayStart: case State.Constructor: case State.ConstructorStart: while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false)) { SetToken(JsonToken.None, null, false); return null; } break; case '"': case '\'': await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false); return FinishReadQuotedNumber(readType); case 'n': await HandleNullAsync(cancellationToken).ConfigureAwait(false); return null; case 'N': return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false); case 'I': return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false); case '-': if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I') { return await ParseNumberNegativeInfinityAsync(readType, cancellationToken).ConfigureAwait(false); } else { await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false); return Value; } case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false); return Value; case '/': await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(currentChar); case StringUtils.CarriageReturn: await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(currentChar)) { throw CreateUnexpectedCharacterException(currentChar); } // eat break; } } case State.Finished: await ReadFinishedAsync(cancellationToken).ConfigureAwait(false); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); } } /// <summary> /// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="bool"/>. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/> /// property returns the <see cref="Nullable{T}"/> of <see cref="bool"/>. This result will be <c>null</c> at the end of an array.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoReadAsBooleanAsync(cancellationToken) : base.ReadAsBooleanAsync(cancellationToken); } internal async Task<bool?> DoReadAsBooleanAsync(CancellationToken cancellationToken) { EnsureBuffer(); switch (_currentState) { case State.PostValue: if (await ParsePostValueAsync(true, cancellationToken)) { return null; } goto case State.Start; case State.Start: case State.Property: case State.Array: case State.ArrayStart: case State.Constructor: case State.ConstructorStart: while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false)) { SetToken(JsonToken.None, null, false); return null; } break; case '"': case '\'': await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false); return ReadBooleanString(_stringReference.ToString()); case 'n': await HandleNullAsync(cancellationToken).ConfigureAwait(false); return null; case '-': case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false); bool b; #if HAVE_BIG_INTEGER if (Value is BigInteger) { b = (BigInteger)Value != 0; } else #endif { b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); } SetToken(JsonToken.Boolean, b, false); return b; case 't': case 'f': bool isTrue = currentChar == 't'; if (!await MatchValueWithTrailingSeparatorAsync(isTrue ? JsonConvert.True : JsonConvert.False, cancellationToken).ConfigureAwait(false)) { throw CreateUnexpectedCharacterException(_chars[_charPos]); } SetToken(JsonToken.Boolean, isTrue); return isTrue; case '/': await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(currentChar); case StringUtils.CarriageReturn: await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(currentChar)) { throw CreateUnexpectedCharacterException(currentChar); } // eat break; } } case State.Finished: await ReadFinishedAsync(cancellationToken).ConfigureAwait(false); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); } } /// <summary> /// Asynchronously reads the next JSON token from the source as a <see cref="byte"/>[]. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/> /// property returns the <see cref="byte"/>[]. This result will be <c>null</c> at the end of an array.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task<byte[]> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoReadAsBytesAsync(cancellationToken) : base.ReadAsBytesAsync(cancellationToken); } internal async Task<byte[]> DoReadAsBytesAsync(CancellationToken cancellationToken) { EnsureBuffer(); bool isWrapped = false; switch (_currentState) { case State.PostValue: if (await ParsePostValueAsync(true, cancellationToken)) { return null; } goto case State.Start; case State.Start: case State.Property: case State.Array: case State.ArrayStart: case State.Constructor: case State.ConstructorStart: while (true) { char currentChar = _chars[_charPos]; switch (currentChar) { case '\0': if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false)) { SetToken(JsonToken.None, null, false); return null; } break; case '"': case '\'': await ParseStringAsync(currentChar, ReadType.ReadAsBytes, cancellationToken).ConfigureAwait(false); byte[] data = (byte[])Value; if (isWrapped) { await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, data, false); } return data; case '{': _charPos++; SetToken(JsonToken.StartObject); await ReadIntoWrappedTypeObjectAsync(cancellationToken).ConfigureAwait(false); isWrapped = true; break; case '[': _charPos++; SetToken(JsonToken.StartArray); return await ReadArrayIntoByteArrayAsync(cancellationToken).ConfigureAwait(false); case 'n': await HandleNullAsync(cancellationToken).ConfigureAwait(false); return null; case '/': await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(currentChar); case StringUtils.CarriageReturn: await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false); break; case StringUtils.LineFeed: ProcessLineFeed(); break; case ' ': case StringUtils.Tab: // eat _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(currentChar)) { throw CreateUnexpectedCharacterException(currentChar); } // eat break; } } case State.Finished: await ReadFinishedAsync(cancellationToken).ConfigureAwait(false); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); } } private async Task ReadIntoWrappedTypeObjectAsync(CancellationToken cancellationToken) { await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false); if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName) { await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } /// <summary> /// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/> /// property returns the <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This result will be <c>null</c> at the end of an array.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoReadAsDateTimeAsync(cancellationToken) : base.ReadAsDateTimeAsync(cancellationToken); } internal async Task<DateTime?> DoReadAsDateTimeAsync(CancellationToken cancellationToken) { return (DateTime?)await ReadStringValueAsync(ReadType.ReadAsDateTime, cancellationToken).ConfigureAwait(false); } /// <summary> /// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/> /// property returns the <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This result will be <c>null</c> at the end of an array.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoReadAsDateTimeOffsetAsync(cancellationToken) : base.ReadAsDateTimeOffsetAsync(cancellationToken); } internal async Task<DateTimeOffset?> DoReadAsDateTimeOffsetAsync(CancellationToken cancellationToken) { return (DateTimeOffset?)await ReadStringValueAsync(ReadType.ReadAsDateTimeOffset, cancellationToken).ConfigureAwait(false); } /// <summary> /// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="decimal"/>. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/> /// property returns the <see cref="Nullable{T}"/> of <see cref="decimal"/>. This result will be <c>null</c> at the end of an array.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoReadAsDecimalAsync(cancellationToken) : base.ReadAsDecimalAsync(cancellationToken); } internal async Task<decimal?> DoReadAsDecimalAsync(CancellationToken cancellationToken) { return (decimal?)await ReadNumberValueAsync(ReadType.ReadAsDecimal, cancellationToken).ConfigureAwait(false); } /// <summary> /// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="double"/>. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/> /// property returns the <see cref="Nullable{T}"/> of <see cref="double"/>. This result will be <c>null</c> at the end of an array.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoReadAsDoubleAsync(cancellationToken) : base.ReadAsDoubleAsync(cancellationToken); } internal async Task<double?> DoReadAsDoubleAsync(CancellationToken cancellationToken) { return (double?)await ReadNumberValueAsync(ReadType.ReadAsDouble, cancellationToken).ConfigureAwait(false); } /// <summary> /// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="int"/>. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/> /// property returns the <see cref="Nullable{T}"/> of <see cref="int"/>. This result will be <c>null</c> at the end of an array.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoReadAsInt32Async(cancellationToken) : base.ReadAsInt32Async(cancellationToken); } internal async Task<int?> DoReadAsInt32Async(CancellationToken cancellationToken) { return (int?)await ReadNumberValueAsync(ReadType.ReadAsInt32, cancellationToken).ConfigureAwait(false); } /// <summary> /// Asynchronously reads the next JSON token from the source as a <see cref="string"/>. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/> /// property returns the <see cref="string"/>. This result will be <c>null</c> at the end of an array.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task<string> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoReadAsStringAsync(cancellationToken) : base.ReadAsStringAsync(cancellationToken); } internal async Task<string> DoReadAsStringAsync(CancellationToken cancellationToken) { return (string)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false); } } } #endif
/* ** $Id: ldo.c,v 2.38.1.3 2008/01/18 22:31:22 roberto Exp $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Threading; #if XBOX using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; #endif namespace SharpLua { using lua_Integer = System.Int32; using ptrdiff_t = System.Int32; using TValue = Lua.lua_TValue; using StkId = Lua.lua_TValue; using lu_byte = System.Byte; using ZIO = Lua.Zio; public partial class Lua { public static void luaD_checkstack(LuaState L, int n) { if ((L.stack_last - L.top) <= n) luaD_growstack(L, n); else { #if HARDSTACKTESTS luaD_reallocstack(L, L.stacksize - EXTRA_STACK - 1); #endif } } public static void incr_top(LuaState L) { luaD_checkstack(L, 1); StkId.inc(ref L.top); } // in the original C code these values save and restore the stack by number of bytes. marshalling sizeof // isn't that straightforward in managed languages, so i implement these by index instead. public static int savestack(LuaState L, StkId p) { return p; } public static StkId restorestack(LuaState L, int n) { return L.stack[n]; } public static int saveci(LuaState L, CallInfo p) { return p - L.base_ci; } public static CallInfo restoreci(LuaState L, int n) { return L.base_ci[n]; } /* results from luaD_precall */ public const int PCRLUA = 0; /* initiated a call to a Lua function */ public const int PCRC = 1; /* did a call to a C function */ public const int PCRYIELD = 2; /* C funtion yielded */ /* type of protected functions, to be ran by `runprotected' */ public delegate void Pfunc(LuaState L, object ud); /* ** {====================================================== ** Error-recovery functions ** ======================================================= */ public delegate void luai_jmpbuf(lua_Integer b); /* chain list of long jump buffers */ public class lua_longjmp { public lua_longjmp previous; public luai_jmpbuf b; public volatile int status; /* error code */ }; public static void luaD_seterrorobj(LuaState L, int errcode, StkId oldtop) { switch (errcode) { case LUA_ERRMEM: { setsvalue2s(L, oldtop, luaS_newliteral(L, MEMERRMSG)); break; } case LUA_ERRERR: { setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); break; } case LUA_ERRSYNTAX: case LUA_ERRRUN: { setobjs2s(L, oldtop, L.top - 1); /* error message on current top */ break; } } L.top = oldtop + 1; } private static void restore_stack_limit(LuaState L) { lua_assert(L.stack_last == L.stacksize - EXTRA_STACK - 1); if (L.size_ci > LUAI_MAXCALLS) { /* there was an overflow? */ int inuse = L.ci - L.base_ci; if (inuse + 1 < LUAI_MAXCALLS) /* can `undo' overflow? */ luaD_reallocCI(L, LUAI_MAXCALLS); } } private static void resetstack(LuaState L, int status) { L.ci = L.base_ci[0]; L.base_ = L.ci.base_; luaF_close(L, L.base_); /* close eventual pending closures */ luaD_seterrorobj(L, status, L.base_); L.nCcalls = L.baseCcalls; L.allowhook = 1; restore_stack_limit(L); L.errfunc = 0; L.errorJmp = null; } public static void luaD_throw(LuaState L, int errcode) { if (L.errorJmp != null) { L.errorJmp.status = errcode; LUAI_THROW(L, L.errorJmp); } else { L.status = cast_byte(errcode); if (G(L).panic != null) { resetstack(L, errcode); lua_unlock(L); G(L).panic(L); } #if XBOX throw new ApplicationException(); #elif SILVERLIGHT throw new SystemException(); #else exit(EXIT_FAILURE); #endif } } public static int luaD_rawrunprotected(LuaState L, Pfunc f, object ud) { lua_longjmp lj = new lua_longjmp(); lj.status = 0; lj.previous = L.errorJmp; /* chain new error handler */ L.errorJmp = lj; /* LUAI_TRY(L, lj, f(L, ud) ); * */ #if CATCH_EXCEPTIONS try #endif { f(L, ud); } #if CATCH_EXCEPTIONS catch (LuaException ex) { Debug.WriteLine("Caught exception: " + ex.ToString()); Debug.WriteLine("Status: " + ex.c.status); if (lj.status == 0) lj.status = -1; } /*catch (Exception ex) { Debug.WriteLine("Caught exception: " + ex.ToString()); throw ex; //if (lj.status == 0) // lj.status = -1; }*/ #endif L.errorJmp = lj.previous; /* restore old error handler */ return lj.status; } /* }====================================================== */ private static void correctstack(LuaState L, TValue[] oldstack) { /* don't need to do this CallInfo ci; GCObject up; L.top = L.stack[L.top - oldstack]; for (up = L.openupval; up != null; up = up.gch.next) gco2uv(up).v = L.stack[gco2uv(up).v - oldstack]; for (ci = L.base_ci[0]; ci <= L.ci; CallInfo.inc(ref ci)) { ci.top = L.stack[ci.top - oldstack]; ci.base_ = L.stack[ci.base_ - oldstack]; ci.func = L.stack[ci.func - oldstack]; } L.base_ = L.stack[L.base_ - oldstack]; * */ } public static void luaD_reallocstack(LuaState L, int newsize) { TValue[] oldstack = L.stack; int realsize = newsize + 1 + EXTRA_STACK; lua_assert(L.stack_last == L.stacksize - EXTRA_STACK - 1); luaM_reallocvector(L, ref L._stack, L.stacksize, realsize/*, TValue*/); L.stacksize = realsize; L.stack_last = L.stack[newsize]; correctstack(L, oldstack); } public static void luaD_reallocCI(LuaState L, int newsize) { CallInfo oldci = L.base_ci[0]; luaM_reallocvector(L, ref L._base_ci, L.size_ci, newsize/*, CallInfo*/); L.size_ci = newsize; L.ci = L.base_ci[L.ci - oldci]; L.end_ci = L.base_ci[L.size_ci - 1]; } public static void luaD_growstack(LuaState L, int n) { if (n <= L.stacksize) /* double size is enough? */ luaD_reallocstack(L, 2 * L.stacksize); else luaD_reallocstack(L, L.stacksize + n); } private static CallInfo growCI(LuaState L) { if (L.size_ci > LUAI_MAXCALLS) /* overflow while handling overflow? */ luaD_throw(L, LUA_ERRERR); else { luaD_reallocCI(L, 2 * L.size_ci); if (L.size_ci > LUAI_MAXCALLS) luaG_runerror(L, "stack overflow"); } CallInfo.inc(ref L._ci); return L.ci; } public static void luaD_callhook(LuaState L, int event_, int line) { lua_Hook hook = L.hook; if ((hook != null) && (L.allowhook != 0)) { ptrdiff_t top = savestack(L, L.top); ptrdiff_t ci_top = savestack(L, L.ci.top); lua_Debug ar = new lua_Debug(); ar.event_ = event_; ar.currentline = line; if (event_ == LUA_HOOKTAILRET) ar.i_ci = 0; /* tail call; no debug information about it */ else ar.i_ci = L.ci - L.base_ci; luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ L.ci.top = L.top + LUA_MINSTACK; lua_assert(L.ci.top <= L.stack_last); L.allowhook = 0; /* cannot call hooks inside a hook */ lua_unlock(L); hook(L, ar); lua_lock(L); lua_assert(L.allowhook == 0); L.allowhook = 1; L.ci.top = restorestack(L, ci_top); L.top = restorestack(L, top); } } private static StkId adjust_varargs(LuaState L, Proto p, int actual) { int i; int nfixargs = p.numparams; Table htab = null; StkId base_, fixed_; for (; actual < nfixargs; ++actual) setnilvalue(StkId.inc(ref L.top)); #if LUA_COMPAT_VARARG if ((p.is_vararg & VARARG_NEEDSARG) != 0) { /* compat. with old-style vararg? */ int nvar = actual - nfixargs; /* number of extra arguments */ lua_assert(p.is_vararg & VARARG_HASARG); luaC_checkGC(L); luaD_checkstack(L, p.maxstacksize); htab = luaH_new(L, nvar, 1); /* create `arg' table */ for (i = 0; i < nvar; i++) /* put extra arguments into `arg' table */ setobj2n(L, luaH_setnum(L, htab, i + 1), L.top - nvar + i); /* store counter in field `n' */ setnvalue(luaH_setstr(L, htab, luaS_newliteral(L, "n")), cast_num(nvar)); } #endif /* move fixed parameters to final position */ fixed_ = L.top - actual; /* first fixed argument */ base_ = L.top; /* final position of first argument */ for (i = 0; i < nfixargs; i++) { setobjs2s(L, StkId.inc(ref L.top), fixed_ + i); setnilvalue(fixed_ + i); } /* add `arg' parameter */ if (htab != null) { StkId top = L.top; StkId.inc(ref L.top); sethvalue(L, top, htab); lua_assert(iswhite(obj2gco(htab))); } return base_; } static StkId tryfuncTM(LuaState L, StkId func) { /*const*/ TValue tm = luaT_gettmbyobj(L, func, TMS.TM_CALL); StkId p; ptrdiff_t funcr = savestack(L, func); if (!ttisfunction(tm)) luaG_typeerror(L, func, "call"); /* Open a hole inside the stack at `func' */ for (p = L.top; p > func; StkId.dec(ref p)) setobjs2s(L, p, p - 1); incr_top(L); func = restorestack(L, funcr); /* previous call may change stack */ setobj2s(L, func, tm); /* tag method is the new function to be called */ return func; } public static CallInfo inc_ci(LuaState L) { if (L.ci == L.end_ci) return growCI(L); // (condhardstacktests(luaD_reallocCI(L, L.size_ci)), ++L.ci)) CallInfo.inc(ref L._ci); return L.ci; } public static int luaD_precall(LuaState L, StkId func, int nresults) { LClosure cl; ptrdiff_t funcr; if (!ttisfunction(func)) /* `func' is not a function? */ func = tryfuncTM(L, func); /* check the `function' tag method */ funcr = savestack(L, func); cl = clvalue(func).l; L.ci.savedpc = InstructionPtr.Assign(L.savedpc); if (cl.isC == 0) { /* Lua function? prepare its call */ CallInfo ci; StkId st, base_; Proto p = cl.p; luaD_checkstack(L, p.maxstacksize); func = restorestack(L, funcr); if (p.is_vararg == 0) { /* no varargs? */ base_ = L.stack[func + 1]; if (L.top > base_ + p.numparams) L.top = base_ + p.numparams; } else { /* vararg function */ int nargs = L.top - func - 1; base_ = adjust_varargs(L, p, nargs); func = restorestack(L, funcr); /* previous call may change the stack */ } ci = inc_ci(L); /* now `enter' new function */ ci.func = func; L.base_ = ci.base_ = base_; ci.top = L.base_ + p.maxstacksize; lua_assert(ci.top <= L.stack_last); L.savedpc = new InstructionPtr(p.code, 0); /* starting point */ ci.tailcalls = 0; ci.nresults = nresults; for (st = L.top; st < ci.top; StkId.inc(ref st)) setnilvalue(st); L.top = ci.top; if ((L.hookmask & LUA_MASKCALL) != 0) { InstructionPtr.inc(ref L._savedpc); /* hooks assume 'pc' is already incremented */ luaD_callhook(L, LUA_HOOKCALL, -1); InstructionPtr.dec(ref L._savedpc); /* correct 'pc' */ } return PCRLUA; } else { /* if is a C function, call it */ CallInfo ci; int n; luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ ci = inc_ci(L); /* now `enter' new function */ ci.func = restorestack(L, funcr); L.base_ = ci.base_ = ci.func + 1; ci.top = L.top + LUA_MINSTACK; lua_assert(ci.top <= L.stack_last); ci.nresults = nresults; if ((L.hookmask & LUA_MASKCALL) != 0) luaD_callhook(L, LUA_HOOKCALL, -1); lua_unlock(L); n = curr_func(L).c.f(L); /* do the actual call */ lua_lock(L); if (n < 0) /* yielding? */ return PCRYIELD; else { luaD_poscall(L, L.top - n); return PCRC; } } } private static StkId callrethooks(LuaState L, StkId firstResult) { ptrdiff_t fr = savestack(L, firstResult); /* next call may change stack */ luaD_callhook(L, LUA_HOOKRET, -1); if (f_isLua(L.ci)) { /* Lua function? */ while (((L.hookmask & LUA_MASKRET) != 0) && (L.ci.tailcalls-- != 0)) /* tail calls */ luaD_callhook(L, LUA_HOOKTAILRET, -1); } return restorestack(L, fr); } public static int luaD_poscall(LuaState L, StkId firstResult) { StkId res; int wanted, i; CallInfo ci; if ((L.hookmask & LUA_MASKRET) != 0) firstResult = callrethooks(L, firstResult); ci = CallInfo.dec(ref L._ci); res = ci.func; /* res == final position of 1st result */ wanted = ci.nresults; L.base_ = (ci - 1).base_; /* restore base */ L.savedpc = InstructionPtr.Assign((ci - 1).savedpc); /* restore savedpc */ /* move results to correct place */ for (i = wanted; i != 0 && firstResult < L.top; i--) { setobjs2s(L, res, firstResult); res = res + 1; firstResult = firstResult + 1; } while (i-- > 0) setnilvalue(StkId.inc(ref res)); L.top = res; return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */ } /* ** Call a function (C or Lua). The function to be called is at *func. ** The arguments are on the stack, right after the function. ** When returns, all the results are on the stack, starting at the original ** function position. */ private static void luaD_call(LuaState L, StkId func, int nResults) { if (++L.nCcalls >= LUAI_MAXCCALLS) { if (L.nCcalls == LUAI_MAXCCALLS) { Debug.WriteLine("C stack overflow"); luaG_runerror(L, "C stack overflow"); } else if (L.nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS >> 3))) luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ } if (luaD_precall(L, func, nResults) == PCRLUA) /* is a Lua function? */ luaV_execute(L, 1); /* call it */ L.nCcalls--; luaC_checkGC(L); } private static void resume(LuaState L, object ud) { StkId firstArg = (StkId)ud; CallInfo ci = L.ci; if (L.status == 0) { /* start coroutine? */ lua_assert(ci == L.base_ci[0] && firstArg > L.base_); if (luaD_precall(L, firstArg - 1, LUA_MULTRET) != PCRLUA) return; } else { /* resuming from previous yield */ lua_assert(L.status == LUA_YIELD); L.status = 0; if (!f_isLua(ci)) { /* `common' yield? */ /* finish interrupted execution of `OP_CALL' */ lua_assert(GET_OPCODE((ci - 1).savedpc[-1]) == OpCode.OP_CALL || GET_OPCODE((ci - 1).savedpc[-1]) == OpCode.OP_TAILCALL); if (luaD_poscall(L, firstArg) != 0) /* complete it... */ L.top = L.ci.top; /* and correct top if not multiple results */ } else /* yielded inside a hook: just continue its execution */ L.base_ = L.ci.base_; } luaV_execute(L, L.ci - L.base_ci); } private static int resume_error(LuaState L, CharPtr msg) { L.top = L.ci.base_; setsvalue2s(L, L.top, luaS_new(L, msg)); incr_top(L); lua_unlock(L); return LUA_ERRRUN; } public static int lua_resume(LuaState L, int nargs) { int status; lua_lock(L); if (L.status != LUA_YIELD && (L.status != 0 || (L.ci != L.base_ci[0]))) return resume_error(L, "cannot resume non-suspended coroutine"); if (L.nCcalls >= LUAI_MAXCCALLS) return resume_error(L, "C stack overflow"); luai_userstateresume(L, nargs); lua_assert(L.errfunc == 0); L.baseCcalls = ++L.nCcalls; status = luaD_rawrunprotected(L, resume, L.top - nargs); if (status != 0) { /* error? */ L.status = cast_byte(status); /* mark thread as `dead' */ luaD_seterrorobj(L, status, L.top); L.ci.top = L.top; } else { lua_assert(L.nCcalls == L.baseCcalls); status = L.status; } --L.nCcalls; lua_unlock(L); return status; } public static int lua_yield(LuaState L, int nresults) { luai_userstateyield(L, nresults); lua_lock(L); if (L.nCcalls > L.baseCcalls) luaG_runerror(L, "attempt to yield across metamethod/C-call boundary"); L.base_ = L.top - nresults; /* protect stack slots below */ L.status = LUA_YIELD; lua_unlock(L); return -1; } public static int luaD_pcall(LuaState L, Pfunc func, object u, ptrdiff_t old_top, ptrdiff_t ef) { int status; ushort oldnCcalls = L.nCcalls; ptrdiff_t old_ci = saveci(L, L.ci); lu_byte old_allowhooks = L.allowhook; ptrdiff_t old_errfunc = L.errfunc; L.errfunc = ef; status = luaD_rawrunprotected(L, func, u); if (status != 0) { /* an error occurred? */ StkId oldtop = restorestack(L, old_top); luaF_close(L, oldtop); /* close eventual pending closures */ luaD_seterrorobj(L, status, oldtop); L.nCcalls = oldnCcalls; L.ci = restoreci(L, old_ci); L.base_ = L.ci.base_; L.savedpc = InstructionPtr.Assign(L.ci.savedpc); L.allowhook = old_allowhooks; restore_stack_limit(L); } L.errfunc = old_errfunc; return status; } /* static Proto NewParser(LuaState L, ZIO z, Mbuffer buff, CharPtr name) { string s = ""; while (z.n-- > 0) s += z.p[0]; Lexer l = new Lexer(); Parser p = new Parser(l.Lex(s)); Ast.Chunk c = p.Parse(); return new Compiler.Compiler().Compile(c, name.ToString()); } */ /* ** Execute a protected parser. */ public class SParser { /* data to `f_parser' */ public ZIO z; public Mbuffer buff = new Mbuffer(); /* buffer to be used by the scanner */ public CharPtr name; }; private static void f_parser(LuaState L, object ud) { int i; Proto tf; Closure cl; SParser p = (SParser)ud; int c = luaZ_lookahead(p.z); luaC_checkGC(L); tf = (c == LUA_SIGNATURE[0]) ? luaU_undump(L, p.z, p.buff, p.name) : //NewParser(L, p.z, p.buff, p.name); luaY_parser(L, p.z, p.buff, p.name); cl = luaF_newLclosure(L, tf.nups, hvalue(gt(L))); cl.l.p = tf; for (i = 0; i < tf.nups; i++) /* initialize eventual upvalues */ cl.l.upvals[i] = luaF_newupval(L); setclvalue(L, L.top, cl); incr_top(L); } public static int luaD_protectedparser(LuaState L, ZIO z, CharPtr name) { SParser p = new SParser(); int status; p.z = z; p.name = new CharPtr(name); luaZ_initbuffer(L, p.buff); status = luaD_pcall(L, f_parser, p, savestack(L, L.top), L.errfunc); luaZ_freebuffer(L, p.buff); return status; } } }
using System; using System.Collections; using System.Globalization; using System.Reflection; using System.Runtime.Remoting; namespace Hydra.Framework { // //********************************************************************** /// <summary> /// Helper methods with regard to objects, types, properties, etc. /// </summary> /// <remarks> /// <p> /// Not intended to be used directly by applications. /// </p> /// </remarks> //********************************************************************** // public sealed class ObjectUtils { #region Constants // //********************************************************************** /// <summary> /// An empty object array. /// </summary> //********************************************************************** // public static readonly object[] EmptyObjects = new object[] { }; #endregion #region Constructors // //********************************************************************** /// <summary> /// Creates a new instance of the <see cref="Hydra.Framework.ObjectUtils"/> class. /// </summary> /// <remarks> /// <p> /// This is a utility class, and as such exposes no public constructors. /// </p> /// </remarks> //********************************************************************** // private ObjectUtils() { } #endregion #region Methods // //********************************************************************** /// <summary> /// Convenience method to instantiate a <see cref="System.Type"/> using /// its no-arg constructor. /// </summary> /// <param name="type">The <see cref="System.Type"/> to instantiate</param> /// <returns> /// A new instance of the <see cref="System.Type"/>. /// </returns> /// <remarks> /// <p> /// As this method doesn't try to instantiate <see cref="System.Type"/>s /// by name, it should avoid <see cref="System.Type"/> loading issues. /// </p> /// </remarks> /// <exception cref="System.Exception"> /// If the <see cref="System.Type"/> Cannot be instantiated. /// </exception> /// <exception cref="System.Exception"> /// If the <paramref name="type"/> is <see langword="null"/>, or if the /// invocation of the <paramref name="type"/>s default (no-arg) constructor /// fails (due to invalid arguments, insufficient permissions, etc). /// </exception> //********************************************************************** // public static object InstantiateType(Type type) { if (type == null) { throw new System.Exception("Cannot instantiate a null Type."); } if (type.IsInterface) { throw new System.Exception( string.Format(CultureInfo.InvariantCulture, "Cannot instantiate an interface {0}.", type)); } if (type.IsAbstract) { throw new System.Exception( string.Format(CultureInfo.InvariantCulture, "Cannot instantiate an abstract class {0}.", type)); } ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if (constructor == null) { throw new System.Exception( string.Format(CultureInfo.InvariantCulture, "Cannot instantiate a class that does not have a public no-argument constructor [{0}].", type)); } return ObjectUtils.InstantiateType(constructor, ObjectUtils.EmptyObjects); } // //********************************************************************** /// <summary> /// Convenience method to instantiate a <see cref="System.Type"/> using /// the given constructor. /// </summary> /// <param name="constructor">The constructor to use for the instantiation.</param> /// <param name="arguments">The arguments to be passed to the constructor.</param> /// <returns>A new instance.</returns> /// <remarks> /// <p> /// As this method doesn't try to instantiate <see cref="System.Type"/>s /// by name, it should avoid <see cref="System.Type"/> loading issues. /// </p> /// </remarks> /// <exception cref="System.Exception"> /// If the <paramref name="constructor"/> is <see langword="null"/>, or if the /// invocation of the <paramref name="constructor"/> fails (due to invalid /// arguments, insufficient permissions, etc). /// </exception> //********************************************************************** // public static object InstantiateType(ConstructorInfo constructor, object[] arguments) { if (constructor == null) { throw new System.Exception( "Cannot instantiate Type using a null constructor argument; " + "does the Type have a no-arg constructor? Is the Type an interface?"); } if (constructor.DeclaringType.ContainsGenericParameters) { throw new System.Exception( string.Format(CultureInfo.InvariantCulture, "Cannot instantiate an open generic type [{0}].", constructor.DeclaringType)); } try { return constructor.Invoke(arguments); } catch (Exception ex) { Type ctorType = constructor.DeclaringType; throw new System.Exception( string.Format(CultureInfo.InvariantCulture, "Cannot instantiate Type [{0}] using ctor [{1}] : '{2}'", ctorType, constructor, ex.Message), ex); } } // //********************************************************************** /// <summary> /// Checks whether the supplied <paramref name="instance"/> is not a transparent proxy and is /// assignable to the supplied <paramref name="type"/>. /// </summary> /// <param name="type">The target <see cref="System.Type"/> to be checked.</param> /// <param name="instance">The value that should be assigned to the type.</param> /// <returns> /// <see langword="true"/> if the supplied <paramref name="instance"/> is not a /// transparent proxy and is assignable to the supplied <paramref name="type"/>. /// </returns> /// <remarks> /// <p> /// Neccessary when dealing with server-activated remote objects, because the /// object is of the type TransparentProxy and regular <c>is</c> testing for assignable /// types does not work. /// </p> /// <p> /// Transparent proxy instances always return <see langword="true"/> when tested /// with the <c>'is'</c> operator (C#). This method only checks if the object /// is assignable to the type if it is not a transparent proxy. /// </p> /// </remarks> //********************************************************************** // public static bool IsAssignableAndNotTransparentProxy(Type type, object instance) { if (!RemotingServices.IsTransparentProxy(instance)) { return IsAssignable(type, instance); } return false; } // //********************************************************************** /// <summary> /// Determine if the given <see cref="System.Type"/> is assignable from the /// given value, assuming setting by reflection. /// </summary> /// <param name="type">The target <see cref="System.Type"/>.</param> /// <param name="obj">The value that should be assigned to the type.</param> /// <returns> /// True if the type is assignable from the value. /// </returns> /// <remarks> /// <p> /// Considers primitive wrapper classes as assignable to the /// corresponding primitive types. /// </p> /// <p> /// For example used in an object factory's constructor resolution. /// </p> /// </remarks> //********************************************************************** // public static bool IsAssignable(Type type, object obj) { return (type.IsInstanceOfType(obj) || (!type.IsPrimitive && obj == null) || (type.Equals(typeof(bool)) && obj is Boolean) || (type.Equals(typeof(byte)) && obj is Byte) || (type.Equals(typeof(char)) && obj is Char) || (type.Equals(typeof(sbyte)) && obj is SByte) || (type.Equals(typeof(int)) && obj is Int32) || (type.Equals(typeof(short)) && obj is Int16) || (type.Equals(typeof(long)) && obj is Int64) || (type.Equals(typeof(float)) && obj is Single) || (type.Equals(typeof(double)) && obj is Double)); } // //********************************************************************** /// <summary> /// Check if the given <see cref="System.Type"/> represents a /// "simple" property, /// i.e. a primitive, a <see cref="System.String"/>, a /// <see cref="System.Type"/>, or a corresponding array. /// </summary> /// <param name="type">The <see cref="System.Type"/> to check.</param> /// <returns> /// <c>true</c> if [is simple property] [the specified type]; otherwise, <c>false</c>. /// </returns> /// <remarks> /// <p> /// Used to determine properties to check for a "simple" dependency-check. /// </p> /// </remarks> //********************************************************************** // public static bool IsSimpleProperty(Type type) { return type.IsPrimitive || type.Equals(typeof(string)) || type.Equals(typeof(string[])) || IsPrimitiveArray(type) || type.Equals(typeof(Type)) || type.Equals(typeof(Type[])); } // //********************************************************************** /// <summary> /// Check if the given class represents a primitive array, /// i.e. boolean, byte, char, short, int, long, float, or double. /// </summary> /// <param name="type">The type.</param> /// <returns> /// <c>true</c> if [is primitive array] [the specified type]; otherwise, <c>false</c>. /// </returns> //********************************************************************** // public static bool IsPrimitiveArray(Type type) { return typeof(bool[]).Equals(type) || typeof(sbyte[]).Equals(type) || typeof(char[]).Equals(type) || typeof(short[]).Equals(type) || typeof(int[]).Equals(type) || typeof(long[]).Equals(type) || typeof(float[]).Equals(type) || typeof(double[]).Equals(type); } // //********************************************************************** /// <summary> /// Resolves the supplied type name into a <see cref="System.Type"/> /// instance. /// </summary> /// <param name="typeName">The (possibly partially assembly qualified) name of a /// <see cref="System.Type"/>.</param> /// <returns> /// A resolved <see cref="System.Type"/> instance. /// </returns> /// <remarks> /// <p> /// If you require special <see cref="System.Type"/> resolution, do /// <b>not</b> use this method, but rather instantiate /// your own <see cref="Spring.Util.TypeResolver"/>. /// </p> /// </remarks> /// <exception cref="System.TypeLoadException"> /// If the type cannot be resolved. /// </exception> //********************************************************************** // public static Type ResolveType(string typeName) { Type type = internalTypeResolver.Resolve(typeName); return type; } // //********************************************************************** /// <summary> /// Determine if the given objects are equal, returning <see langword="true"/> /// if both are <see langword="null"/> respectively <see langword="false"/> /// if only one is <see langword="null"/>. /// </summary> /// <param name="o1">The first object to compare.</param> /// <param name="o2">The second object to compare.</param> /// <returns> /// <see langword="true"/> if the given objects are equal. /// </returns> //********************************************************************** // public static bool NullSafeEquals(object o1, object o2) { return (o1 == o2 || (o1 != null && o1.Equals(o2))); } // //********************************************************************** /// <summary> /// Returns the first element in the supplied <paramref name="enumerator"/>. /// </summary> /// <param name="enumerator">The <see cref="System.Collections.IEnumerator"/> to use to enumerate /// elements.</param> /// <returns> /// The first element in the supplied <paramref name="enumerator"/>. /// </returns> /// <exception cref="System.IndexOutOfRangeException"> /// If the supplied <paramref name="enumerator"/> did not have any elements. /// </exception> //********************************************************************** // public static object EnumerateFirstElement(IEnumerator enumerator) { return ObjectUtils.EnumerateElementAtIndex(enumerator, 0); } // //********************************************************************** /// <summary> /// Returns the first element in the supplied <paramref name="enumerable"/>. /// </summary> /// <param name="enumerable">The <see cref="System.Collections.IEnumerable"/> to use to enumerate /// elements.</param> /// <returns> /// The first element in the supplied <paramref name="enumerable"/>. /// </returns> /// <exception cref="System.IndexOutOfRangeException"> /// If the supplied <paramref name="enumerable"/> did not have any elements. /// </exception> /// <exception cref="System.ArgumentNullException"> /// If the supplied <paramref name="enumerable"/> is <see langword="null"/>. /// </exception> //********************************************************************** // public static object EnumerateFirstElement(IEnumerable enumerable) { if (enumerable == null) throw new ArgumentNullException("enumerable"); return ObjectUtils.EnumerateElementAtIndex(enumerable.GetEnumerator(), 0); } // //********************************************************************** /// <summary> /// Returns the element at the specified index using the supplied /// <paramref name="enumerator"/>. /// </summary> /// <param name="enumerator">The <see cref="System.Collections.IEnumerator"/> to use to enumerate /// elements until the supplied <paramref name="index"/> is reached.</param> /// <param name="index">The index of the element in the enumeration to return.</param> /// <returns> /// The element at the specified index using the supplied /// <paramref name="enumerator"/>. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// If the supplied <paramref name="index"/> was less than zero, or the /// supplied <paramref name="enumerator"/> did not contain enough elements /// to be able to reach the supplied <paramref name="index"/>. /// </exception> //********************************************************************** // public static object EnumerateElementAtIndex(IEnumerator enumerator, int index) { if (index < 0) { throw new ArgumentOutOfRangeException(); } object element = null; int i = 0; while (enumerator.MoveNext()) { element = enumerator.Current; if (++i > index) { break; } } if (i < index) { throw new ArgumentOutOfRangeException(); } return element; } // //********************************************************************** /// <summary> /// Returns the element at the specified index using the supplied /// <paramref name="enumerable"/>. /// </summary> /// <param name="enumerable">The <see cref="System.Collections.IEnumerable"/> to use to enumerate /// elements until the supplied <paramref name="index"/> is reached.</param> /// <param name="index">The index of the element in the enumeration to return.</param> /// <returns> /// The element at the specified index using the supplied /// <paramref name="enumerable"/>. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// If the supplied <paramref name="index"/> was less than zero, or the /// supplied <paramref name="enumerable"/> did not contain enough elements /// to be able to reach the supplied <paramref name="index"/>. /// </exception> /// <exception cref="System.ArgumentNullException"> /// If the supplied <paramref name="enumerable"/> is <see langword="null"/>. /// </exception> //********************************************************************** // public static object EnumerateElementAtIndex(IEnumerable enumerable, int index) { if (enumerable == null) throw new ArgumentNullException("enumerable"); return ObjectUtils.EnumerateElementAtIndex(enumerable.GetEnumerator(), index); } #endregion #region Fields // //********************************************************************** /// <summary> /// /// </summary> //********************************************************************** // private static readonly ITypeResolver internalTypeResolver = new CachedTypeResolver(new TypeResolver()); #endregion } }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver; using MongoDB.Driver.GeoJsonObjectModel; using MongoDB.Driver.Linq; using Newtonsoft.Json; using OCM.API.Common; using OCM.API.Common.Model; using OCM.API.Common.Model.Extended; using OCM.Core.Settings; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; namespace OCM.Core.Data { public class MirrorStatus { public HttpStatusCode StatusCode { get; set; } public string Description { get; set; } public long TotalPOIInCache { get; set; } public long TotalPOIInDB { get; set; } public DateTime LastUpdated { get; set; } public long NumPOILastUpdated { get; set; } public long NumDistinctPOIs { get; set; } public long MaxBatchSize { get; set; } public string Server { get; set; } public string ContentHash { get; set; } public DateTime? LastPOIUpdate { get; set; } public DateTime? LastPOICreated { get; set; } public int MaxPOIId { get; set; } } public class BenchmarkResult { public string Description { get; set; } public long TimeMS { get; set; } } public class POIMongoDB : OCM.API.Common.Model.ChargePoint { [JsonIgnore] public GeoJsonPoint<GeoJson2DGeographicCoordinates> SpatialPosition { get; set; } public static POIMongoDB FromChargePoint(OCM.API.Common.Model.ChargePoint cp, POIMongoDB poi = null) { if (poi == null) poi = new POIMongoDB(); poi.AddressInfo = cp.AddressInfo; poi.Chargers = cp.Chargers; poi.Connections = cp.Connections; poi.DataProvider = cp.DataProvider; poi.DataProviderID = cp.DataProviderID; poi.DataProvidersReference = cp.DataProvidersReference; poi.DataQualityLevel = cp.DataQualityLevel; if (cp.DateCreated != null) { poi.DateCreated = (DateTime?)DateTime.SpecifyKind(cp.DateCreated.Value, DateTimeKind.Utc); } if (cp.DateLastConfirmed != null) { poi.DateLastConfirmed = (DateTime?)DateTime.SpecifyKind(cp.DateLastConfirmed.Value, DateTimeKind.Utc); } if (cp.DateLastStatusUpdate != null) { poi.DateLastStatusUpdate = (DateTime?)DateTime.SpecifyKind(cp.DateLastStatusUpdate.Value, DateTimeKind.Utc); } if (cp.DatePlanned != null) { poi.DatePlanned = (DateTime?)DateTime.SpecifyKind(cp.DatePlanned.Value, DateTimeKind.Utc); } poi.GeneralComments = cp.GeneralComments; poi.ID = cp.ID; poi.MediaItems = cp.MediaItems; poi.MetadataTags = cp.MetadataTags; poi.MetadataValues = cp.MetadataValues; poi.NumberOfPoints = cp.NumberOfPoints; poi.NumberOfPoints = cp.NumberOfPoints; poi.OperatorID = cp.OperatorID; poi.OperatorInfo = cp.OperatorInfo; poi.OperatorsReference = cp.OperatorsReference; poi.ParentChargePointID = cp.ParentChargePointID; poi.StatusType = cp.StatusType; poi.StatusTypeID = cp.StatusTypeID; poi.SubmissionStatus = cp.SubmissionStatus; poi.SubmissionStatusTypeID = cp.SubmissionStatusTypeID; poi.UsageCost = cp.UsageCost; poi.UsageType = cp.UsageType; poi.UsageTypeID = cp.UsageTypeID; poi.UserComments = cp.UserComments; poi.LevelOfDetail = cp.LevelOfDetail; poi.UUID = cp.UUID; return poi; } } public class CacheProviderMongoDB { private const int DefaultPolylineSearchDistanceKM = 5; private const int DefaultLatLngSearchDistanceKM = 1000; private MongoClient client = null; private IMongoDatabase database = null; private MirrorStatus status = null; private static readonly object _mutex = new object(); private static volatile CacheProviderMongoDB _instance = null; private static CoreSettings _settings; public static CacheProviderMongoDB CreateDefaultInstance(CoreSettings settings) { _settings = settings; return DefaultInstance; } public static bool IsDefaultInstanceInitialized { get { if (_settings == null || _instance == null) { return false; } else { return true; } } } public static CacheProviderMongoDB DefaultInstance { get { if (_instance == null) { lock (_mutex) { if (_instance == null) { if (_settings == null) throw new Exception("Cache Provider Default Instance requires init using CreateDefaultInstance"); _instance = new CacheProviderMongoDB(); _instance.EnsureMongoDBIndexes(); } } } return _instance; } } public CacheProviderMongoDB() { try { if (!BsonClassMap.IsClassMapRegistered(typeof(POIMongoDB))) { // register deserialization class map for ChargePoint BsonClassMap.RegisterClassMap<POIMongoDB>(cm => { cm.AutoMap(); cm.SetIgnoreExtraElements(true); }); } if (!BsonClassMap.IsClassMapRegistered(typeof(OCM.API.Common.Model.ChargePoint))) { // register deserialization class map for ChargePoint BsonClassMap.RegisterClassMap<OCM.API.Common.Model.ChargePoint>(cm => { cm.AutoMap(); cm.SetIgnoreExtraElements(true); }); } if (!BsonClassMap.IsClassMapRegistered(typeof(OCM.API.Common.Model.CoreReferenceData))) { // register deserialization class map for ChargePoint BsonClassMap.RegisterClassMap<OCM.API.Common.Model.CoreReferenceData>(cm => { cm.AutoMap(); cm.SetIgnoreExtraElements(true); }); } if (!BsonClassMap.IsClassMapRegistered(typeof(MirrorStatus))) { // register deserialization class map for ChargePoint BsonClassMap.RegisterClassMap<MirrorStatus>(cm => { cm.AutoMap(); cm.SetIgnoreExtraElements(true); }); } if (!BsonClassMap.IsClassMapRegistered(typeof(CountryExtendedInfo))) { // register deserialization class map for ChargePoint BsonClassMap.RegisterClassMap<CountryExtendedInfo>(cm => { cm.AutoMap(); cm.SetIgnoreExtraElements(true); }); } } catch (Exception) { ; ; } client = new MongoClient(_settings.MongoDBSettings.ConnectionString); database = client.GetDatabase(_settings.MongoDBSettings.DatabaseName); status = GetMirrorStatus(false, false).Result; if (status.StatusCode == HttpStatusCode.ExpectationFailed && _settings.IsCacheOnlyMode) { throw new Exception("MongoDB Cache Unavailable. Check configuration settings for connection string. ::" + status.Description); } } public IMongoCollection<POIMongoDB> GetPOICollection() { return database.GetCollection<POIMongoDB>("poi"); } public async Task RemoveAllPOI(IEnumerable<OCM.API.Common.Model.ChargePoint> poiList, IMongoCollection<POIMongoDB> poiCollection) { foreach (var poi in poiList) { await poiCollection.DeleteManyAsync(p => p.ID == poi.ID); } } public async Task InsertAllPOI(IEnumerable<OCM.API.Common.Model.ChargePoint> poiList, IMongoCollection<POIMongoDB> poiCollection) { var mongoDBPoiList = new List<POIMongoDB>(); foreach (var poi in poiList) { var newPoi = POIMongoDB.FromChargePoint(poi); if (newPoi.AddressInfo != null) { newPoi.SpatialPosition = new GeoJsonPoint<GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(newPoi.AddressInfo.Longitude, newPoi.AddressInfo.Latitude)); } mongoDBPoiList.Add(newPoi); } await poiCollection.InsertManyAsync(mongoDBPoiList); } public async Task<List<OCM.API.Common.Model.ChargePoint>> GetPOIListToUpdate(OCMEntities dataModel, CacheUpdateStrategy updateStrategy, CoreReferenceData refData, int pageIndex = 0, int pageSize = 0) { // create if not exists if (database.GetCollection<BsonDocument>("poi") == null) { database.CreateCollection("poi"); } IQueryable<Data.ChargePoint> dataList = dataModel.ChargePoints .Include(a1 => a1.AddressInfo) .ThenInclude(a => a.Country) .Include(a1 => a1.ConnectionInfos) .Include(a1 => a1.MetadataValues) .ThenInclude(m => m.MetadataFieldOption) .Include(a1 => a1.UserComments) .ThenInclude(c => c.User) .Include(a1 => a1.UserComments) .Include(a1 => a1.MediaItems) .ThenInclude(c => c.User) .OrderBy(o => o.Id); if (pageSize > 0) { dataList = dataList.Skip(pageIndex * pageSize).Take(pageSize); } dataList = dataList.AsNoTracking(); //incremental update based on POI Id - up to 100 results at a time if (updateStrategy == CacheUpdateStrategy.Incremental) { var poiCollection = database.GetCollection<POIMongoDB>("poi"); var maxPOI = await poiCollection.AsQueryable().OrderByDescending(s => s.DateLastStatusUpdate).FirstAsync(); int maxId = 0; if (maxPOI != null) { maxId = maxPOI.ID; } //from max poi we have in mirror to next 100 results in order of ID dataList = dataList.Where(o => o.Id > maxId).Take(100); var poiList = new List<OCM.API.Common.Model.ChargePoint>(); foreach (var cp in dataList) { poiList.Add(OCM.API.Common.Model.Extensions.ChargePoint.FromDataModel(cp, true, true, true, true, refData)); } return poiList; } //update based on POI last modified since last status update if (updateStrategy == CacheUpdateStrategy.Modified) { var poiCollection = database.GetCollection<POIMongoDB>("poi"); var maxPOI = await poiCollection.AsQueryable().OrderByDescending(s => s.DateLastStatusUpdate).FirstAsync(); DateTime? dateLastModified = null; if (maxPOI != null) { dateLastModified = maxPOI.DateLastStatusUpdate.Value.AddMinutes(-10); } //determine POI updated since last status update we have in cache var stopwatch = Stopwatch.StartNew(); dataList = dataList.Where(o => o.DateLastStatusUpdate > dateLastModified); stopwatch.Stop(); System.Diagnostics.Debug.WriteLine($"POI List retrieved in {stopwatch.Elapsed.TotalSeconds } seconds"); var poiList = new List<OCM.API.Common.Model.ChargePoint>(); stopwatch.Restart(); foreach (var cp in dataList) { poiList.Add(OCM.API.Common.Model.Extensions.ChargePoint.FromDataModel(cp, true, true, true, true, refData)); } System.Diagnostics.Debug.WriteLine($"POI List model prepared in {stopwatch.Elapsed.TotalSeconds } seconds"); return poiList; } if (updateStrategy == CacheUpdateStrategy.All) { var stopwatch = Stopwatch.StartNew(); // get data list, include navigation properties to improve query performance var list = await dataList.ToListAsync(); stopwatch.Stop(); System.Diagnostics.Debug.WriteLine($"POI List retrieved in {stopwatch.Elapsed.TotalSeconds } seconds"); stopwatch.Restart(); var poiList = new List<OCM.API.Common.Model.ChargePoint>(); foreach (var cp in list) { poiList.Add(OCM.API.Common.Model.Extensions.ChargePoint.FromDataModel(cp, true, true, true, true, refData)); if (poiList.Count % 100 == 0) { System.Diagnostics.Debug.WriteLine($"POIs processed { poiList.Count} in {stopwatch.Elapsed.TotalSeconds } seconds"); } } System.Diagnostics.Debug.WriteLine($"POI List model prepared in {stopwatch.Elapsed.TotalSeconds } seconds"); return poiList; } return null; } public async Task<MirrorStatus> RefreshCachedPOI(int poiId) { var refData = await new ReferenceDataManager().GetCoreReferenceDataAsync(); var dataModel = new OCMEntities(); var poiModel = dataModel.ChargePoints.FirstOrDefault(p => p.Id == poiId); var poiCollection = database.GetCollection<POIMongoDB>("poi"); if (poiModel != null) { var cachePOI = POIMongoDB.FromChargePoint(OCM.API.Common.Model.Extensions.ChargePoint.FromDataModel(poiModel, refData)); if (cachePOI.AddressInfo != null) { cachePOI.SpatialPosition = new GeoJsonPoint<GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(cachePOI.AddressInfo.Longitude, cachePOI.AddressInfo.Latitude)); } // replace/insert POI await poiCollection.ReplaceOneAsync(q => q.ID == poiId, cachePOI, new ReplaceOptions { IsUpsert = true }); } else { //poi not present in master DB, we've removed it from cache var removeResult = poiCollection.DeleteMany(q => q.ID == poiId); System.Diagnostics.Debug.WriteLine("POIs removed from cache [" + poiId + "]:" + removeResult.DeletedCount); } long numPOIInMasterDB = dataModel.ChargePoints.LongCount(); return await RefreshMirrorStatus(await poiCollection.EstimatedDocumentCountAsync(), 1, numPOIInMasterDB); } /// <summary> /// Ensure all MongoDB indexes are being set up. /// </summary> /// <returns></returns> protected void EnsureMongoDBIndexes() { var poiCollection = database.GetCollection<POIMongoDB>("poi"); poiCollection.Indexes.CreateOne(Builders<POIMongoDB>.IndexKeys.Geo2DSphere("SpatialPosition")); // bounding box queries (geoWithin > geometry > polygon) //poiCollection.CreateIndex(IndexKeys.GeoSpatial("SpatialPosition.coordinates")); // bounding box queries //poiCollection.CreateIndex(IndexKeys<POIMongoDB>.GeoSpatialSpherical(x => x.SpatialPosition)); // distance queries poiCollection.Indexes.CreateOne(Builders<POIMongoDB>.IndexKeys.Descending(x => x.DateLastStatusUpdate)); poiCollection.Indexes.CreateOne(Builders<POIMongoDB>.IndexKeys.Descending(x => x.DateCreated)); poiCollection.Indexes.CreateOne(Builders<POIMongoDB>.IndexKeys.Descending(x => x.ID)); } /// <summary> /// Perform full or partial repopulation of POI Mirror in MongoDB /// </summary> /// <returns></returns> public async Task<MirrorStatus> PopulatePOIMirror(CacheUpdateStrategy updateStrategy, ILogger logger = null) { bool preserveExistingPOIs = true; EnsureMongoDBIndexes(); // cache will refresh either from the source database or via a master API if (!_settings.IsCacheOnlyMode) { using (var dataModel = new Data.OCMEntities()) { if (database.GetCollection<BsonDocument>("poi") == null) { database.CreateCollection("poi"); } if (updateStrategy != CacheUpdateStrategy.All) { if (database.GetCollection<BsonDocument>("reference") == null) { database.CreateCollection("reference"); } if (database.GetCollection<BsonDocument>("status") == null) { database.CreateCollection("status"); } if (database.GetCollection<BsonDocument>("poi") == null) { database.CreateCollection("poi"); } } else { // by default we remove all POIs before refreshing from master preserveExistingPOIs = false; } CoreReferenceData coreRefData; using (var refDataManager = new ReferenceDataManager()) { coreRefData = await refDataManager.GetCoreReferenceDataAsync(new APIRequestParams { AllowDataStoreDB = true, AllowMirrorDB = false }); } if (coreRefData != null) { var reference = database.GetCollection<CoreReferenceData>("reference"); await reference.ReplaceOneAsync(f => f.ConnectionTypes != null, coreRefData, new ReplaceOptions { IsUpsert = true }); } var batchSize = 1000; List<API.Common.Model.ChargePoint> poiList; var poiCollection = database.GetCollection<POIMongoDB>("poi"); if (updateStrategy != CacheUpdateStrategy.All) { poiList = await GetPOIListToUpdate(dataModel, updateStrategy, coreRefData); if (poiList != null && poiList.Any()) { await RemoveAllPOI(poiList, poiCollection); await Task.Delay(300); await InsertAllPOI(poiList, poiCollection); } } else { // full refresh await poiCollection.DeleteManyAsync(p => p.ID > 0); await Task.Delay(300); var pageIndex = 0; var pageSize = 1000; var total = 0; //get batch of poi to insert var sw = Stopwatch.StartNew(); poiList = await GetPOIListToUpdate(dataModel, updateStrategy, coreRefData, pageIndex, pageSize); while (poiList.Count > 0) { logger?.LogInformation($"Inserting batch {pageIndex}"); System.Diagnostics.Debug.WriteLine($"Inserting batch {pageIndex} :: {pageIndex * pageSize}"); await InsertAllPOI(poiList, poiCollection); pageIndex++; total += poiList.Count; poiList = await GetPOIListToUpdate(dataModel, updateStrategy, coreRefData, pageIndex, pageSize); } //poiCollection.Indexes.ReIndex(); sw.Stop(); GC.Collect(); System.Diagnostics.Debug.WriteLine($"Rebuild of complete cache took {sw.Elapsed.TotalSeconds}s"); } long numPOIInMasterDB = dataModel.ChargePoints.LongCount(); return await RefreshMirrorStatus(await poiCollection.EstimatedDocumentCountAsync(), 1, numPOIInMasterDB); } } else { // cache must refresh from master API var baseUrl = _settings.DataSourceAPIBaseUrl; using (var apiClient = new OCM.API.Client.OCMClient(baseUrl, _settings.ApiKeys.OCMApiKey, logger)) { // check sync status compared to master API var syncStatus = await apiClient.GetSystemStatusAsync(); syncStatus.DataHash ??= ""; if (syncStatus != null) { var poiCollection = database.GetCollection<POIMongoDB>("poi"); bool isRefDataSyncRequired = false; DateTime? lastUpdated = null; DateTime? lastCreated = null; int maxIdCached = 0; if (await poiCollection.EstimatedDocumentCountAsync() == 0) { // no data, starting a new mirror updateStrategy = CacheUpdateStrategy.All; isRefDataSyncRequired = true; } else { var queryablePOICollection = poiCollection.AsQueryable(); lastUpdated = queryablePOICollection.Max(i => i.DateLastStatusUpdate); lastCreated = queryablePOICollection.Max(i => i.DateCreated); maxIdCached = queryablePOICollection.Max(i => i.ID); if (maxIdCached < syncStatus.MaxPOIId) { // if our max id is less than the master, we still have some catching up to do so sync on ID first updateStrategy = CacheUpdateStrategy.All; preserveExistingPOIs = true; } // existing data, sync may be required var hashItems = syncStatus.DataHash.Split(";"); var hashChecks = syncStatus.DataHash.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select(part => part.Split("::")) .ToDictionary(split => split[0], split => split[1]); var localHash = GetCacheContentHash(); localHash ??= ""; var localHashChecks = localHash.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select(part => part.Split("::")) .ToDictionary(split => split[0], split => split[1]); if (!hashChecks.ContainsKey("reference") || !localHashChecks.ContainsKey("reference")) { isRefDataSyncRequired = true; } else if (hashChecks["reference"] != localHashChecks["reference"]) { isRefDataSyncRequired = true; } } // updates are required to reference data or POI list if (isRefDataSyncRequired || lastUpdated != syncStatus.POIDataLastModified || lastCreated != syncStatus.POIDataLastCreated || updateStrategy == CacheUpdateStrategy.All) { var numPOIUpdated = 0L; var dateLastSync = syncStatus.POIDataLastModified; if (isRefDataSyncRequired) { // sync reference data CoreReferenceData coreRefData = await apiClient.GetCoreReferenceDataAsync(); if (coreRefData != null) { var reference = database.GetCollection<CoreReferenceData>("reference"); await reference.ReplaceOneAsync(f => f.ConnectionTypes != null, coreRefData, new ReplaceOptions { IsUpsert = true }); } } if (lastUpdated != syncStatus.POIDataLastModified || lastCreated != syncStatus.POIDataLastCreated || updateStrategy == CacheUpdateStrategy.All) { var poiFilter = new API.Client.SearchFilters { MaxResults = _settings.MongoDBSettings.CacheSyncBatchSize, ModifiedSince = lastUpdated, SortBy = "modified_asc", IncludeUserComments = true, Verbose = true, SubmissionStatusTypeIDs = new int[] { 0 } }; if (updateStrategy != CacheUpdateStrategy.All) { if (lastCreated < lastUpdated) { poiFilter.ModifiedSince = lastCreated; } } else { poiFilter.ModifiedSince = null; poiFilter.SortBy = "id_asc"; poiFilter.GreaterThanId = maxIdCached; } // sync POI list var poiList = await apiClient.GetPOIListAsync(poiFilter); if (poiList != null && poiList.Any()) { if (!preserveExistingPOIs) { if (updateStrategy == CacheUpdateStrategy.All) { await poiCollection.DeleteManyAsync(p => p.ID > 0); } else { await RemoveAllPOI(poiList, poiCollection); } } Thread.Sleep(300); await InsertAllPOI(poiList, poiCollection); if (updateStrategy == CacheUpdateStrategy.All) { // poiCollection.ReIndex(); } numPOIUpdated = poiList.LongCount(); } } var poiCount = await poiCollection.EstimatedDocumentCountAsync(); var status = await RefreshMirrorStatus(poiCount, numPOIUpdated, poiCount, dateLastSync); status.MaxBatchSize = _settings.MongoDBSettings.CacheSyncBatchSize; return status; } } } } // nothing to update return await GetMirrorStatus(false, false, false); } private async Task<MirrorStatus> RefreshMirrorStatus( long cachePOICollectionCount, long numPOIUpdated, long numPOIInMasterDB, DateTime? poiLastUpdate = null, DateTime? poiLastCreated = null ) { var statusCollection = database.GetCollection<MirrorStatus>("status"); //new status MirrorStatus status = new MirrorStatus(); status.Description = "MongoDB Cache of Open Charge Map POI Database"; status.LastUpdated = DateTime.UtcNow; status.TotalPOIInCache = cachePOICollectionCount; status.TotalPOIInDB = numPOIInMasterDB; status.StatusCode = HttpStatusCode.OK; status.NumPOILastUpdated = numPOIUpdated; if (poiLastUpdate != null) status.LastPOIUpdate = poiLastUpdate; if (poiLastCreated != null) status.LastPOICreated = poiLastCreated; await statusCollection.ReplaceOneAsync(s => s.LastUpdated > DateTime.MinValue, status, new ReplaceOptions { IsUpsert = true }); return status; } private string GetCacheContentHash() { var cols = new string[] { "poi", "reference", "countryinfo" }; /* var hashCommand = new Command<BsonDocumentCommand> { { "dbHash", 1 }, { "collections", BsonArray.Create(cols) } }; var dbHashResults = database.RunCommand(hashCommand); if (dbHashResults.Ok) { var collectionHashes = dbHashResults.Response.GetElement("collections").Value.AsBsonDocument.Elements .OrderBy(i => i.Name) .Select(i => i.Name + "::" + i.Value.AsString) .ToArray(); return String.Join(";", collectionHashes); } else { return null; }*/ return null; } public async Task<MirrorStatus> GetMirrorStatus(bool includeDupeCheck, bool includeDBCheck = true, bool includeContentHash = false) { try { var statusCollection = database.GetCollection<MirrorStatus>("status"); var currentStatus = await statusCollection.AsQueryable().FirstOrDefaultAsync(); if (currentStatus == null) { return new MirrorStatus { StatusCode = HttpStatusCode.NotFound, Description = "Cache is offline (not yet generated)" }; } if (includeContentHash) { currentStatus.ContentHash = GetCacheContentHash(); } if (includeDBCheck) { using (var db = new OCMEntities()) { currentStatus.TotalPOIInDB = await db.ChargePoints.LongCountAsync(); currentStatus.LastPOIUpdate = await db.ChargePoints.MaxAsync(i => i.DateLastStatusUpdate); currentStatus.LastPOICreated = await db.ChargePoints.MaxAsync(i => i.DateCreated); currentStatus.MaxPOIId = await db.ChargePoints.MaxAsync(i => i.Id); } } else { var poiCollection = database.GetCollection<POIMongoDB>("poi"); currentStatus.TotalPOIInDB = await poiCollection.EstimatedDocumentCountAsync(); currentStatus.LastPOIUpdate = poiCollection.AsQueryable().Max(p => p.DateLastStatusUpdate); currentStatus.LastPOICreated = poiCollection.AsQueryable().Max(p => p.DateCreated); currentStatus.MaxPOIId = poiCollection.AsQueryable().Max(p => p.ID); } if (includeDupeCheck) { //perform check to see if number of distinct ids!= number of pois var poiCollection = database.GetCollection<POIMongoDB>("poi"); currentStatus.NumDistinctPOIs = await poiCollection.AsQueryable().DistinctBy(d => d.ID).CountAsync(); } var serverInfo = client.Settings.Servers.FirstOrDefault(); currentStatus.Server = $"{serverInfo.Host}:{serverInfo.Port}"; return currentStatus; } catch (Exception exp) { return new MirrorStatus { StatusCode = HttpStatusCode.NotFound, Description = "Cache is offline:" + exp.ToString() }; } } public List<CountryExtendedInfo> GetExtendedCountryInfo() { try { var results = database.GetCollection<CountryExtendedInfo>("countryinfo"); return results.AsQueryable().ToList(); } catch (Exception) { return null; } } public async Task<bool> IsCacheReady() { if (status != null && (_settings.MongoDBSettings.MaxCacheAgeMinutes == 0 || status.LastUpdated.AddMinutes(_settings.MongoDBSettings.MaxCacheAgeMinutes) > DateTime.UtcNow)) { return true; } else { status = await GetMirrorStatus(false, false); return status.NumDistinctPOIs > 0; } } public async Task<CoreReferenceData> GetCoreReferenceData(APIRequestParams filter) { try { if (await IsCacheReady()) { var refDataCollection = database.GetCollection<CoreReferenceData>("reference"); var refData = refDataCollection.AsQueryable().FirstOrDefault(); if (filter.CountryIDs != null && filter.CountryIDs.Any()) { // need to filter results based on usage by country var poiCollection = database.GetCollection<POIMongoDB>("poi").AsQueryable(); var connectionsInCountry = poiCollection.Where(poi => poi.AddressInfo.CountryID != null && filter.CountryIDs.Contains((int)poi.AddressInfo.CountryID) && (poi.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Imported_Published || poi.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Submitted_Published) && poi.Connections.Any() ) .Select(p => new { CountryID = p.AddressInfo.CountryID, ConnectionTypes = p.Connections.Select(t => t.ConnectionTypeID) }) .SelectMany(p => p.ConnectionTypes, (i, c) => new { CountryId = i.CountryID, ConnectionTypeId = c }) .ToArray() .Distinct(); refData.ConnectionTypes.RemoveAll(a => !connectionsInCountry.Any(r => r.ConnectionTypeId == a.ID)); // filter on operators present within given countries var operatorsInCountry = poiCollection.Where(poi => poi.AddressInfo.CountryID != null && filter.CountryIDs.Contains((int)poi.AddressInfo.CountryID) && (poi.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Imported_Published || poi.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Submitted_Published) && poi.OperatorID != null) .Select(p => new { CountryId = p.AddressInfo.CountryID, OperatorId = p.OperatorID }) .ToArray() .Distinct(); refData.Operators.RemoveAll(a => !operatorsInCountry.Any(r => r.OperatorId == a.ID)); } return refData; } } catch (Exception exp) { System.Diagnostics.Debug.WriteLine(exp.ToString()); ; ; } return null; } /// <summary> /// returns cached POI details if cache is not older than ageMinutes /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task<OCM.API.Common.Model.ChargePoint> GetPOI(int id) { if (await IsCacheReady()) { var poiCollection = database.GetCollection<OCM.API.Common.Model.ChargePoint>("poi").AsQueryable(); return poiCollection.FirstOrDefault(p => p.ID == id); } else { return null; } } public IEnumerable<OCM.API.Common.Model.ChargePoint> GetPOIList(APIRequestParams settings) { return GetPOIListAsync(settings).Result; } public async Task<IEnumerable<OCM.API.Common.Model.ChargePoint>> GetPOIListAsync(APIRequestParams filter) { if (!await IsCacheReady()) { System.Diagnostics.Debug.Print("MongoDB cache is outdated, returning null result."); return null; } var stopwatch = Stopwatch.StartNew(); int maxResults = filter.MaxResults; bool requiresDistance = false; GeoJsonPoint<GeoJson2DGeographicCoordinates> searchPoint = null; if (filter.Latitude != null && filter.Longitude != null) { requiresDistance = true; searchPoint = GeoJson.Point(GeoJson.Geographic((double)filter.Longitude, (double)filter.Latitude)); } else { searchPoint = GeoJson.Point(GeoJson.Geographic(0, 0)); } //if distance filter provided in miles, convert to KM before use if (filter.DistanceUnit == OCM.API.Common.Model.DistanceUnit.Miles && filter.Distance != null) { filter.Distance = GeoManager.ConvertMilesToKM((double)filter.Distance); } //either filter by named country code or by country id list if (filter.CountryCode != null) { var referenceData = await GetCoreReferenceData(new APIRequestParams { }); var filterCountry = referenceData.Countries.FirstOrDefault(c => c.ISOCode.ToUpper() == filter.CountryCode.ToUpper()); if (filterCountry != null) { filter.CountryIDs = new int[] { filterCountry.ID }; } } ///////////////////////////////////// if (database != null) { System.Diagnostics.Debug.Print($"MongoDB cache building query @ {stopwatch.ElapsedMilliseconds}ms"); var collection = database.GetCollection<POIMongoDB>("poi"); IQueryable<POIMongoDB> poiList = collection.AsQueryable(); System.Diagnostics.Debug.Print($"MongoDB got poiList as Queryable @ {stopwatch.ElapsedMilliseconds}ms"); //filter by points along polyline, bounding box or polygon if ( (filter.Polyline != null && filter.Polyline.Any()) || (filter.BoundingBox != null && filter.BoundingBox.Any()) || (filter.Polygon != null && filter.Polygon.Any()) ) { //override lat.long specified in search, use polyline or bounding box instead filter.Latitude = null; filter.Longitude = null; //filter by location within polyline expanded to a polygon IEnumerable<LatLon> searchPolygon = null; if (filter.Polyline != null && filter.Polyline.Any()) { if (filter.Distance == null) filter.Distance = DefaultPolylineSearchDistanceKM; searchPolygon = OCM.Core.Util.PolylineEncoder.SearchPolygonFromPolyLine(filter.Polyline, (double)filter.Distance); } else if (filter.BoundingBox != null && filter.BoundingBox.Any()) { // bounding box points could be in any order, so normalise here: var polyPoints = Core.Util.PolylineEncoder.ConvertPointsToBoundingBox(filter.BoundingBox) .Coordinates .Select(p => new LatLon { Latitude = p.Y, Longitude = p.X }).ToList(); searchPolygon = polyPoints; } else if (filter.Polygon != null && filter.Polygon.Any()) { //searchPolygon = filter.Polygon; searchPolygon = OCM.Core.Util.PolylineEncoder.SearchPolygonFromPoints(filter.Polygon); } var geoCoords = searchPolygon.Select(t => new GeoJson2DGeographicCoordinates((double)t.Longitude, (double)t.Latitude)); var linearRing = new GeoJsonLinearRingCoordinates<GeoJson2DGeographicCoordinates>(geoCoords.ToArray()); var geometry = new GeoJsonPolygon<GeoJson2DGeographicCoordinates>(new GeoJsonPolygonCoordinates<GeoJson2DGeographicCoordinates>(linearRing)); var polygonQueryBson = geometry.ToBsonDocument(); var crsDoc = BsonDocument.Parse("{ type: \"name\", properties: { name: \"urn:x-mongodb:crs:strictwinding:EPSG:"+ GeoManager.StandardSRID+ "\" } }"); polygonQueryBson.Add("crs", crsDoc); var geoJson = polygonQueryBson.ToJson(); // var geoFilter = Builders<POIMongoDB>.Filter.GeoWithin(x => x.SpatialPosition, polygonQueryBson); var geoQuery = "{\"SpatialPosition\": {\"$geoWithin\": {\"$geometry\": " + geoJson + " } } }"; var geoBson = BsonDocument.Parse(geoQuery); poiList = (await collection.Find(geoBson).ToListAsync()).AsQueryable(); } else if (requiresDistance) { //filter by distance from lat/lon first if (filter.Distance == null) filter.Distance = DefaultLatLngSearchDistanceKM; var geoFilter = Builders<POIMongoDB>.Filter.NearSphere(p => p.SpatialPosition, searchPoint, (double)filter.Distance * 1000); poiList = (await collection.Find(geoFilter).ToListAsync()).AsQueryable(); } poiList = ApplyQueryFilters(filter, poiList); System.Diagnostics.Debug.Print($"MongoDB executing query @ {stopwatch.ElapsedMilliseconds}ms"); IQueryable<API.Common.Model.ChargePoint> results = null; if (!requiresDistance || (filter.Latitude == null || filter.Longitude == null)) { //distance is not required or can't be provided System.Diagnostics.Debug.Print($"MongoDB starting query to list @ {stopwatch.ElapsedMilliseconds}ms"); if (filter.SortBy == "created_asc") { results = poiList.OrderBy(p => p.DateCreated).Take(filter.MaxResults).AsQueryable(); } else if (filter.SortBy == "modified_asc") { results = poiList.OrderBy(p => p.DateLastStatusUpdate).Take(filter.MaxResults).AsQueryable(); } else if (filter.SortBy == "id_asc") { results = poiList.OrderBy(p => p.ID).Take(filter.MaxResults).AsQueryable(); } else { if (filter.BoundingBox == null || !filter.BoundingBox.Any()) { poiList = poiList.OrderByDescending(p => p.ID); } // In boundingbox more, if no sorting was requested by the user, // do not perform any sorting for performance reasons. results = poiList.Take(filter.MaxResults).AsQueryable(); } System.Diagnostics.Debug.Print($"MongoDB finished query to list @ {stopwatch.ElapsedMilliseconds}ms"); } else { //distance is required, calculate and populate in results results = poiList.ToArray().AsQueryable(); //populate distance foreach (var p in results) { p.AddressInfo.Distance = GeoManager.CalcDistance((double)filter.Latitude, (double)filter.Longitude, p.AddressInfo.Latitude, p.AddressInfo.Longitude, filter.DistanceUnit); p.AddressInfo.DistanceUnit = filter.DistanceUnit; } results = results.OrderBy(r => r.AddressInfo.Distance).Take(filter.MaxResults); } if (filter.IsCompactOutput) { System.Diagnostics.Debug.Print($"MongoDB begin conversion to compact output @ {stopwatch.ElapsedMilliseconds}ms"); // we will be mutating the results so need to convert to object we can update if (!(results is Array)) { results = results.ToArray().AsQueryable(); } System.Diagnostics.Debug.Print($"MongoDB converted to array @ {stopwatch.ElapsedMilliseconds}ms"); // dehydrate POI object by removing navigation properties which are based on reference data. Client can then rehydrate using reference data, saving on data transfer KB // TODO: find faster method or replace with custom serialization foreach (var p in results) { //need to null reference data objects so they are not included in output. caution required here to ensure compact output via SQL is same as Cache DB output p.DataProvider = null; p.OperatorInfo = null; p.UsageType = null; p.StatusType = null; p.SubmissionStatus = null; p.AddressInfo.Country = null; if (p.Connections != null) { foreach (var c in p.Connections) { c.ConnectionType = null; c.CurrentType = null; c.Level = null; c.StatusType = null; } } if (!filter.IncludeComments) { p.UserComments = null; p.MediaItems = null; } if (p.UserComments != null) { foreach (var c in p.UserComments) { c.CheckinStatusType = null; c.CommentType = null; } } } } stopwatch.Stop(); System.Diagnostics.Debug.WriteLine("Cache Provider POI Total Query Time:" + stopwatch.ElapsedMilliseconds + "ms"); var output = results.ToList(); return output; } else { return null; } } public static IQueryable<POIMongoDB> ApplyQueryFilters(APIRequestParams filter, IQueryable<POIMongoDB> poiList) { int greaterThanId = 0; // workaround mongodb linq conversion bug if (filter.GreaterThanId.HasValue) greaterThanId = filter.GreaterThanId.Value; if (filter.OperatorIDs?.Any() == true) { poiList = poiList.Where(c => c.OperatorID != null && filter.OperatorIDs.Contains((int)c.OperatorID)); } if (filter.SubmissionStatusTypeID == null) { // default to published submissions poiList = poiList.Where(c => c.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Imported_Published || c.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Submitted_Published); } else if (filter.SubmissionStatusTypeID > 0) { //specific submission status poiList = poiList.Where(c => c.SubmissionStatusTypeID == filter.SubmissionStatusTypeID); } else if (filter.SubmissionStatusTypeID == 0) { //use all pois regardless of submission status } // exclude any delisted POIs poiList = poiList.Where(c => c.SubmissionStatusTypeID != (int)StandardSubmissionStatusTypes.Delisted_NotPublicInformation); // deprecated filter by operator name if (filter.OperatorName != null) { poiList = poiList.Where(c => c.OperatorInfo.Title == filter.OperatorName); } if (filter.IsOpenData != null) { poiList = poiList.Where(c => (filter.IsOpenData == true && c.DataProvider.IsOpenDataLicensed == true) || (filter.IsOpenData == false && c.DataProvider.IsOpenDataLicensed != true)); } if (filter.GreaterThanId.HasValue == true) { poiList = poiList.Where(c => filter.GreaterThanId.HasValue && c.ID > greaterThanId); } // depreceated filter by dataprovider name if (filter.DataProviderName != null) { poiList = poiList.Where(c => c.DataProvider.Title == filter.DataProviderName); } if (filter.CountryIDs?.Any() == true) { poiList = poiList.Where(c => c.AddressInfo.CountryID != null && filter.CountryIDs.Contains((int)c.AddressInfo.CountryID)); } if (filter.ChargePointIDs?.Any() == true) { poiList = poiList.Where(c => filter.ChargePointIDs.Contains((int)c.ID)); } if (filter.UsageTypeIDs?.Any() == true) { poiList = poiList.Where(c => c.UsageTypeID != null && filter.UsageTypeIDs.Contains((int)c.UsageTypeID)); } if (filter.StatusTypeIDs?.Any() == true) { poiList = poiList.Where(c => c.StatusTypeID != null && filter.StatusTypeIDs.Contains((int)c.StatusTypeID)); } // exclude any decomissioned items poiList = poiList.Where(c => c.StatusTypeID != (int)StandardStatusTypes.RemovedDecomissioned); if (filter.DataProviderIDs?.Any() == true) { poiList = poiList.Where(c => c.DataProviderID != null && filter.DataProviderIDs.Contains((int)c.DataProviderID)); } if (filter.Postcodes?.Any() == true) { poiList = poiList.Where(c => filter.Postcodes.Contains(c.AddressInfo.Postcode)); } if (filter.ChangesFromDate != null) { poiList = poiList.Where(c => c.DateLastStatusUpdate >= filter.ChangesFromDate.Value); } if (filter.CreatedFromDate != null) { poiList = poiList.Where(c => c.DateCreated >= filter.CreatedFromDate.Value); } //where level of detail is greater than 1 we decide how much to return based on the given level of detail (1-10) Level 10 will return the least amount of data and is suitable for a global overview if (filter.LevelOfDetail > 1) { //return progressively less matching results (across whole data set) as requested Level Of Detail gets higher if (filter.LevelOfDetail > 3) { filter.LevelOfDetail = 1; //highest priority LOD } else { filter.LevelOfDetail = 2; //include next level priority items } poiList = poiList.Where(c => c.LevelOfDetail <= filter.LevelOfDetail); } //apply connectionInfo filters, all filters must match a distinct connection within the charge point, rather than any filter matching any connectioninfo if (filter.ConnectionType != null) { poiList = poiList.Where(c => c.Connections.Any(conn => conn.ConnectionType.Title == filter.ConnectionType)); } if (filter.MinPowerKW != null) { poiList = poiList.Where(c => c.Connections.Any(conn => conn.PowerKW >= filter.MinPowerKW)); } if (filter.MaxPowerKW != null) { poiList = poiList.Where(c => c.Connections.Any(conn => conn.PowerKW <= filter.MaxPowerKW)); } if (filter.ConnectionTypeIDs?.Any() == true) { poiList = poiList.Where(c => c.Connections.Any(conn => conn.ConnectionTypeID != null && filter.ConnectionTypeIDs.Contains((int)conn.ConnectionTypeID))); } if (filter.LevelIDs?.Any() == true) { poiList = poiList.Where(c => c.Connections.Any(conn => conn.LevelID != null && filter.LevelIDs.Contains((int)conn.LevelID))); } poiList = poiList.Where(c => c.AddressInfo != null); return poiList; } public async Task<List<BenchmarkResult>> PerformPOIQueryBenchmark(int numQueries, string mode = "country") { List<BenchmarkResult> results = new List<BenchmarkResult>(); for (int i = 0; i < numQueries; i++) { BenchmarkResult result = new BenchmarkResult(); try { result.Description = "Cached POI Query [" + mode + "] " + i; APIRequestParams filter = new APIRequestParams(); filter.MaxResults = 100; if (mode == "country") { filter.CountryCode = "NL"; } else if (mode == "distance") { filter.Latitude = 57.10604; filter.Longitude = -2.62214; filter.Distance = 50; filter.DistanceUnit = DistanceUnit.Miles; } else { var r = new Random(100).NextDouble(); filter.BoundingBox = new List<LatLon> { new LatLon { Latitude = -32.27537992647112 + (r / 100), Longitude = 114.88498474200799 + (r / 100) }, new LatLon { Latitude = -31.664884896457338 + (r / 100), Longitude = 116.45335732240358 + (r / 100) } }; filter.DistanceUnit = DistanceUnit.Miles; } var stopwatch = Stopwatch.StartNew(); var poiList = await this.GetPOIListAsync(filter); stopwatch.Stop(); result.Description += " results:" + poiList.ToArray().Count(); result.TimeMS = stopwatch.ElapsedMilliseconds; } catch (Exception exp) { result.Description += " Failed:" + exp.ToString(); } results.Add(result); } return results; } } public static class EfExtensions { // https://expertcodeblog.wordpress.com/2018/02/19/net-core-2-0-resolve-error-the-source-iqueryable-doesnt-implement-iasyncenumerable/ public static Task<List<TSource>> ToListAsyncSafe<TSource>( this IQueryable<TSource> source) { if (source == null) throw new ArgumentNullException(nameof(source)); if (!(source is IAsyncEnumerable<TSource>)) return Task.FromResult(source.ToList()); return source.ToListAsync(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Reactive.Linq; using Avalonia.Collections; using Avalonia.Controls.Generators; using Avalonia.Controls.Primitives; using Avalonia.Controls.Utils; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Interactivity; using Avalonia.Threading; using Avalonia.VisualTree; namespace Avalonia.Controls { /// <summary> /// Displays a hierarchical tree of data. /// </summary> public class TreeView : ItemsControl, ICustomKeyboardNavigation { /// <summary> /// Defines the <see cref="AutoScrollToSelectedItem"/> property. /// </summary> public static readonly StyledProperty<bool> AutoScrollToSelectedItemProperty = SelectingItemsControl.AutoScrollToSelectedItemProperty.AddOwner<TreeView>(); /// <summary> /// Defines the <see cref="SelectedItem"/> property. /// </summary> public static readonly DirectProperty<TreeView, object> SelectedItemProperty = SelectingItemsControl.SelectedItemProperty.AddOwner<TreeView>( o => o.SelectedItem, (o, v) => o.SelectedItem = v); /// <summary> /// Defines the <see cref="SelectedItems"/> property. /// </summary> public static readonly DirectProperty<TreeView, IList> SelectedItemsProperty = ListBox.SelectedItemsProperty.AddOwner<TreeView>( o => o.SelectedItems, (o, v) => o.SelectedItems = v); /// <summary> /// Defines the <see cref="SelectionMode"/> property. /// </summary> public static readonly StyledProperty<SelectionMode> SelectionModeProperty = ListBox.SelectionModeProperty.AddOwner<TreeView>(); private static readonly IList Empty = Array.Empty<object>(); private object _selectedItem; private IList _selectedItems; private bool _syncingSelectedItems; /// <summary> /// Initializes static members of the <see cref="TreeView"/> class. /// </summary> static TreeView() { // HACK: Needed or SelectedItem property will not be found in Release build. } /// <summary> /// Occurs when the control's selection changes. /// </summary> public event EventHandler<SelectionChangedEventArgs> SelectionChanged { add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value); remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value); } /// <summary> /// Gets the <see cref="ITreeItemContainerGenerator"/> for the tree view. /// </summary> public new ITreeItemContainerGenerator ItemContainerGenerator => (ITreeItemContainerGenerator)base.ItemContainerGenerator; /// <summary> /// Gets or sets a value indicating whether to automatically scroll to newly selected items. /// </summary> public bool AutoScrollToSelectedItem { get => GetValue(AutoScrollToSelectedItemProperty); set => SetValue(AutoScrollToSelectedItemProperty, value); } /// <summary> /// Gets or sets the selection mode. /// </summary> public SelectionMode SelectionMode { get => GetValue(SelectionModeProperty); set => SetValue(SelectionModeProperty, value); } /// <summary> /// Gets or sets the selected item. /// </summary> /// <remarks> /// Note that setting this property only currently works if the item is expanded to be visible. /// To select non-expanded nodes use `Selection.SelectedIndex`. /// </remarks> public object SelectedItem { get => _selectedItem; set { var selectedItems = SelectedItems; SetAndRaise(SelectedItemProperty, ref _selectedItem, value); if (value != null) { if (selectedItems.Count != 1 || selectedItems[0] != value) { SelectSingleItem(value); } } else if (SelectedItems.Count > 0) { SelectedItems.Clear(); } } } /// <summary> /// Gets or sets the selected items. /// </summary> public IList SelectedItems { get { if (_selectedItems == null) { _selectedItems = new AvaloniaList<object>(); SubscribeToSelectedItems(); } return _selectedItems; } set { if (value?.IsFixedSize == true || value?.IsReadOnly == true) { throw new NotSupportedException( "Cannot use a fixed size or read-only collection as SelectedItems."); } UnsubscribeFromSelectedItems(); _selectedItems = value ?? new AvaloniaList<object>(); SubscribeToSelectedItems(); } } /// <summary> /// Expands the specified <see cref="TreeViewItem"/> all descendent <see cref="TreeViewItem"/>s. /// </summary> /// <param name="item">The item to expand.</param> public void ExpandSubTree(TreeViewItem item) { item.IsExpanded = true; var panel = item.Presenter.Panel; if (panel != null) { foreach (var child in panel.Children) { if (child is TreeViewItem treeViewItem) { ExpandSubTree(treeViewItem); } } } } /// <summary> /// Selects all items in the <see cref="TreeView"/>. /// </summary> /// <remarks> /// Note that this method only selects nodes currently visible due to their parent nodes /// being expanded: it does not expand nodes. /// </remarks> public void SelectAll() { SynchronizeItems(SelectedItems, ItemContainerGenerator.Index.Items); } /// <summary> /// Deselects all items in the <see cref="TreeView"/>. /// </summary> public void UnselectAll() { SelectedItems.Clear(); } /// <summary> /// Subscribes to the <see cref="SelectedItems"/> CollectionChanged event, if any. /// </summary> private void SubscribeToSelectedItems() { if (_selectedItems is INotifyCollectionChanged incc) { incc.CollectionChanged += SelectedItemsCollectionChanged; } SelectedItemsCollectionChanged( _selectedItems, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } private void SelectSingleItem(object item) { _syncingSelectedItems = true; SelectedItems.Clear(); SelectedItems.Add(item); _syncingSelectedItems = false; SetAndRaise(SelectedItemProperty, ref _selectedItem, item); } /// <summary> /// Called when the <see cref="SelectedItems"/> CollectionChanged event is raised. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> private void SelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { IList added = null; IList removed = null; switch (e.Action) { case NotifyCollectionChangedAction.Add: SelectedItemsAdded(e.NewItems.Cast<object>().ToArray()); if (AutoScrollToSelectedItem) { var container = (TreeViewItem)ItemContainerGenerator.Index.ContainerFromItem(e.NewItems[0]); container?.BringIntoView(); } added = e.NewItems; break; case NotifyCollectionChangedAction.Remove: if (!_syncingSelectedItems) { if (SelectedItems.Count == 0) { SelectedItem = null; } else { var selectedIndex = SelectedItems.IndexOf(_selectedItem); if (selectedIndex == -1) { var old = _selectedItem; _selectedItem = SelectedItems[0]; RaisePropertyChanged(SelectedItemProperty, old, _selectedItem); } } } foreach (var item in e.OldItems) { MarkItemSelected(item, false); } removed = e.OldItems; break; case NotifyCollectionChangedAction.Reset: foreach (IControl container in ItemContainerGenerator.Index.Containers) { MarkContainerSelected(container, false); } if (SelectedItems.Count > 0) { SelectedItemsAdded(SelectedItems); added = SelectedItems; } else if (!_syncingSelectedItems) { SelectedItem = null; } break; case NotifyCollectionChangedAction.Replace: foreach (var item in e.OldItems) { MarkItemSelected(item, false); } foreach (var item in e.NewItems) { MarkItemSelected(item, true); } if (SelectedItem != SelectedItems[0] && !_syncingSelectedItems) { var oldItem = SelectedItem; var item = SelectedItems[0]; _selectedItem = item; RaisePropertyChanged(SelectedItemProperty, oldItem, item); } added = e.NewItems; removed = e.OldItems; break; } if (added?.Count > 0 || removed?.Count > 0) { var changed = new SelectionChangedEventArgs( SelectingItemsControl.SelectionChangedEvent, removed ?? Empty, added ?? Empty); RaiseEvent(changed); } } private void MarkItemSelected(object item, bool selected) { var container = ItemContainerGenerator.Index.ContainerFromItem(item); MarkContainerSelected(container, selected); } private void SelectedItemsAdded(IList items) { if (items.Count == 0) { return; } foreach (object item in items) { MarkItemSelected(item, true); } if (SelectedItem == null && !_syncingSelectedItems) { SetAndRaise(SelectedItemProperty, ref _selectedItem, items[0]); } } /// <summary> /// Unsubscribes from the <see cref="SelectedItems"/> CollectionChanged event, if any. /// </summary> private void UnsubscribeFromSelectedItems() { if (_selectedItems is INotifyCollectionChanged incc) { incc.CollectionChanged -= SelectedItemsCollectionChanged; } } (bool handled, IInputElement next) ICustomKeyboardNavigation.GetNext(IInputElement element, NavigationDirection direction) { if (direction == NavigationDirection.Next || direction == NavigationDirection.Previous) { if (!this.IsVisualAncestorOf(element)) { var result = _selectedItem != null ? ItemContainerGenerator.Index.ContainerFromItem(_selectedItem) : ItemContainerGenerator.ContainerFromIndex(0); return (result != null, result); // SelectedItem may not be in the treeview. } return (true, null); } return (false, null); } /// <inheritdoc/> protected override IItemContainerGenerator CreateItemContainerGenerator() { var result = new TreeItemContainerGenerator<TreeViewItem>( this, TreeViewItem.HeaderProperty, TreeViewItem.ItemTemplateProperty, TreeViewItem.ItemsProperty, TreeViewItem.IsExpandedProperty); result.Index.Materialized += ContainerMaterialized; return result; } /// <inheritdoc/> protected override void OnGotFocus(GotFocusEventArgs e) { if (e.NavigationMethod == NavigationMethod.Directional) { e.Handled = UpdateSelectionFromEventSource( e.Source, true, (e.KeyModifiers & KeyModifiers.Shift) != 0); } } protected override void OnKeyDown(KeyEventArgs e) { var direction = e.Key.ToNavigationDirection(); if (direction?.IsDirectional() == true && !e.Handled) { if (SelectedItem != null) { var next = GetContainerInDirection( GetContainerFromEventSource(e.Source), direction.Value, true); if (next != null) { FocusManager.Instance.Focus(next, NavigationMethod.Directional); e.Handled = true; } } else { SelectedItem = ElementAt(Items, 0); } } if (!e.Handled) { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>(); bool Match(List<KeyGesture> gestures) => gestures.Any(g => g.Matches(e)); if (this.SelectionMode == SelectionMode.Multiple && Match(keymap.SelectAll)) { SelectAll(); e.Handled = true; } } } private TreeViewItem GetContainerInDirection( TreeViewItem from, NavigationDirection direction, bool intoChildren) { IItemContainerGenerator parentGenerator = GetParentContainerGenerator(from); if (parentGenerator == null) { return null; } var index = parentGenerator.IndexFromContainer(from); var parent = from.Parent as ItemsControl; TreeViewItem result = null; switch (direction) { case NavigationDirection.Up: if (index > 0) { var previous = (TreeViewItem)parentGenerator.ContainerFromIndex(index - 1); result = previous.IsExpanded && previous.ItemCount > 0 ? (TreeViewItem)previous.ItemContainerGenerator.ContainerFromIndex(previous.ItemCount - 1) : previous; } else { result = from.Parent as TreeViewItem; } break; case NavigationDirection.Down: if (from.IsExpanded && intoChildren && from.ItemCount > 0) { result = (TreeViewItem)from.ItemContainerGenerator.ContainerFromIndex(0); } else if (index < parent?.ItemCount - 1) { result = (TreeViewItem)parentGenerator.ContainerFromIndex(index + 1); } else if (parent is TreeViewItem parentItem) { return GetContainerInDirection(parentItem, direction, false); } break; } return result; } /// <inheritdoc/> protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (e.Source is IVisual source) { var point = e.GetCurrentPoint(source); if (point.Properties.IsLeftButtonPressed || point.Properties.IsRightButtonPressed) { e.Handled = UpdateSelectionFromEventSource( e.Source, true, (e.KeyModifiers & KeyModifiers.Shift) != 0, (e.KeyModifiers & KeyModifiers.Control) != 0, point.Properties.IsRightButtonPressed); } } } /// <summary> /// Updates the selection for an item based on user interaction. /// </summary> /// <param name="container">The container.</param> /// <param name="select">Whether the item should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> /// <param name="rightButton">Whether the event is a right-click.</param> protected void UpdateSelectionFromContainer( IControl container, bool select = true, bool rangeModifier = false, bool toggleModifier = false, bool rightButton = false) { var item = ItemContainerGenerator.Index.ItemFromContainer(container); if (item == null) { return; } IControl selectedContainer = null; if (SelectedItem != null) { selectedContainer = ItemContainerGenerator.Index.ContainerFromItem(SelectedItem); } var mode = SelectionMode; var toggle = toggleModifier || (mode & SelectionMode.Toggle) != 0; var multi = (mode & SelectionMode.Multiple) != 0; var range = multi && selectedContainer != null && rangeModifier; if (rightButton) { if (!SelectedItems.Contains(item)) { SelectSingleItem(item); } } else if (!toggle && !range) { SelectSingleItem(item); } else if (multi && range) { SynchronizeItems( SelectedItems, GetItemsInRange(selectedContainer as TreeViewItem, container as TreeViewItem)); } else { var i = SelectedItems.IndexOf(item); if (i != -1) { SelectedItems.Remove(item); } else { if (multi) { SelectedItems.Add(item); } else { SelectedItem = item; } } } } private static IItemContainerGenerator GetParentContainerGenerator(TreeViewItem item) { if (item == null) { return null; } switch (item.Parent) { case TreeView treeView: return treeView.ItemContainerGenerator; case TreeViewItem treeViewItem: return treeViewItem.ItemContainerGenerator; default: return null; } } /// <summary> /// Find which node is first in hierarchy. /// </summary> /// <param name="treeView">Search root.</param> /// <param name="nodeA">Nodes to find.</param> /// <param name="nodeB">Node to find.</param> /// <returns>Found first node.</returns> private static TreeViewItem FindFirstNode(TreeView treeView, TreeViewItem nodeA, TreeViewItem nodeB) { return FindInContainers(treeView.ItemContainerGenerator, nodeA, nodeB); } private static TreeViewItem FindInContainers(ITreeItemContainerGenerator containerGenerator, TreeViewItem nodeA, TreeViewItem nodeB) { IEnumerable<ItemContainerInfo> containers = containerGenerator.Containers; foreach (ItemContainerInfo container in containers) { TreeViewItem node = FindFirstNode(container.ContainerControl as TreeViewItem, nodeA, nodeB); if (node != null) { return node; } } return null; } private static TreeViewItem FindFirstNode(TreeViewItem node, TreeViewItem nodeA, TreeViewItem nodeB) { if (node == null) { return null; } TreeViewItem match = node == nodeA ? nodeA : node == nodeB ? nodeB : null; if (match != null) { return match; } return FindInContainers(node.ItemContainerGenerator, nodeA, nodeB); } /// <summary> /// Returns all items that belong to containers between <paramref name="from"/> and <paramref name="to"/>. /// The range is inclusive. /// </summary> /// <param name="from">From container.</param> /// <param name="to">To container.</param> private List<object> GetItemsInRange(TreeViewItem from, TreeViewItem to) { var items = new List<object>(); if (from == null || to == null) { return items; } TreeViewItem firstItem = FindFirstNode(this, from, to); if (firstItem == null) { return items; } bool wasReversed = false; if (firstItem == to) { var temp = from; from = to; to = temp; wasReversed = true; } TreeViewItem node = from; while (node != to) { var item = ItemContainerGenerator.Index.ItemFromContainer(node); if (item != null) { items.Add(item); } node = GetContainerInDirection(node, NavigationDirection.Down, true); } var toItem = ItemContainerGenerator.Index.ItemFromContainer(to); if (toItem != null) { items.Add(toItem); } if (wasReversed) { items.Reverse(); } return items; } /// <summary> /// Updates the selection based on an event that may have originated in a container that /// belongs to the control. /// </summary> /// <param name="eventSource">The control that raised the event.</param> /// <param name="select">Whether the container should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> /// <param name="rightButton">Whether the event is a right-click.</param> /// <returns> /// True if the event originated from a container that belongs to the control; otherwise /// false. /// </returns> protected bool UpdateSelectionFromEventSource( IInteractive eventSource, bool select = true, bool rangeModifier = false, bool toggleModifier = false, bool rightButton = false) { var container = GetContainerFromEventSource(eventSource); if (container != null) { UpdateSelectionFromContainer(container, select, rangeModifier, toggleModifier, rightButton); return true; } return false; } /// <summary> /// Tries to get the container that was the source of an event. /// </summary> /// <param name="eventSource">The control that raised the event.</param> /// <returns>The container or null if the event did not originate in a container.</returns> protected TreeViewItem GetContainerFromEventSource(IInteractive eventSource) { var item = ((IVisual)eventSource).GetSelfAndVisualAncestors() .OfType<TreeViewItem>() .FirstOrDefault(); if (item != null) { if (item.ItemContainerGenerator.Index == ItemContainerGenerator.Index) { return item; } } return null; } /// <summary> /// Called when a new item container is materialized, to set its selected state. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> private void ContainerMaterialized(object sender, ItemContainerEventArgs e) { var selectedItem = SelectedItem; if (selectedItem == null) { return; } foreach (var container in e.Containers) { if (container.Item == selectedItem) { ((TreeViewItem)container.ContainerControl).IsSelected = true; if (AutoScrollToSelectedItem) { Dispatcher.UIThread.Post(container.ContainerControl.BringIntoView); } break; } } } /// <summary> /// Sets a container's 'selected' class or <see cref="ISelectable.IsSelected"/>. /// </summary> /// <param name="container">The container.</param> /// <param name="selected">Whether the control is selected</param> private void MarkContainerSelected(IControl container, bool selected) { if (container == null) { return; } if (container is ISelectable selectable) { selectable.IsSelected = selected; } else { container.Classes.Set(":selected", selected); } } /// <summary> /// Makes a list of objects equal another (though doesn't preserve order). /// </summary> /// <param name="items">The items collection.</param> /// <param name="desired">The desired items.</param> private static void SynchronizeItems(IList items, IEnumerable<object> desired) { var list = items.Cast<object>().ToList(); var toRemove = list.Except(desired).ToList(); var toAdd = desired.Except(list).ToList(); foreach (var i in toRemove) { items.Remove(i); } foreach (var i in toAdd) { items.Add(i); } } } }
#if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif using System; using System.Runtime.InteropServices; namespace Godot { /// <summary> /// Axis-Aligned Bounding Box. AABB consists of a position, a size, and /// several utility functions. It is typically used for fast overlap tests. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct AABB : IEquatable<AABB> { private Vector3 _position; private Vector3 _size; /// <summary> /// Beginning corner. Typically has values lower than End. /// </summary> /// <value>Directly uses a private field.</value> public Vector3 Position { get { return _position; } set { _position = value; } } /// <summary> /// Size from Position to End. Typically all components are positive. /// If the size is negative, you can use <see cref="Abs"/> to fix it. /// </summary> /// <value>Directly uses a private field.</value> public Vector3 Size { get { return _size; } set { _size = value; } } /// <summary> /// Ending corner. This is calculated as <see cref="Position"/> plus /// <see cref="Size"/>. Setting this value will change the size. /// </summary> /// <value>Getting is equivalent to `value = Position + Size`, setting is equivalent to `Size = value - Position`.</value> public Vector3 End { get { return _position + _size; } set { _size = value - _position; } } /// <summary> /// Returns an AABB with equivalent position and size, modified so that /// the most-negative corner is the origin and the size is positive. /// </summary> /// <returns>The modified AABB.</returns> public AABB Abs() { Vector3 end = End; Vector3 topLeft = new Vector3(Mathf.Min(_position.x, end.x), Mathf.Min(_position.y, end.y), Mathf.Min(_position.z, end.z)); return new AABB(topLeft, _size.Abs()); } /// <summary> /// Returns true if this AABB completely encloses another one. /// </summary> /// <param name="with">The other AABB that may be enclosed.</param> /// <returns>A bool for whether or not this AABB encloses `b`.</returns> public bool Encloses(AABB with) { Vector3 src_min = _position; Vector3 src_max = _position + _size; Vector3 dst_min = with._position; Vector3 dst_max = with._position + with._size; return src_min.x <= dst_min.x && src_max.x > dst_max.x && src_min.y <= dst_min.y && src_max.y > dst_max.y && src_min.z <= dst_min.z && src_max.z > dst_max.z; } /// <summary> /// Returns this AABB expanded to include a given point. /// </summary> /// <param name="point">The point to include.</param> /// <returns>The expanded AABB.</returns> public AABB Expand(Vector3 point) { Vector3 begin = _position; Vector3 end = _position + _size; if (point.x < begin.x) { begin.x = point.x; } if (point.y < begin.y) { begin.y = point.y; } if (point.z < begin.z) { begin.z = point.z; } if (point.x > end.x) { end.x = point.x; } if (point.y > end.y) { end.y = point.y; } if (point.z > end.z) { end.z = point.z; } return new AABB(begin, end - begin); } /// <summary> /// Returns the area of the AABB. /// </summary> /// <returns>The area.</returns> public real_t GetArea() { return _size.x * _size.y * _size.z; } /// <summary> /// Gets the position of one of the 8 endpoints of the AABB. /// </summary> /// <param name="idx">Which endpoint to get.</param> /// <returns>An endpoint of the AABB.</returns> public Vector3 GetEndpoint(int idx) { switch (idx) { case 0: return new Vector3(_position.x, _position.y, _position.z); case 1: return new Vector3(_position.x, _position.y, _position.z + _size.z); case 2: return new Vector3(_position.x, _position.y + _size.y, _position.z); case 3: return new Vector3(_position.x, _position.y + _size.y, _position.z + _size.z); case 4: return new Vector3(_position.x + _size.x, _position.y, _position.z); case 5: return new Vector3(_position.x + _size.x, _position.y, _position.z + _size.z); case 6: return new Vector3(_position.x + _size.x, _position.y + _size.y, _position.z); case 7: return new Vector3(_position.x + _size.x, _position.y + _size.y, _position.z + _size.z); default: throw new ArgumentOutOfRangeException(nameof(idx), String.Format("Index is {0}, but a value from 0 to 7 is expected.", idx)); } } /// <summary> /// Returns the normalized longest axis of the AABB. /// </summary> /// <returns>A vector representing the normalized longest axis of the AABB.</returns> public Vector3 GetLongestAxis() { var axis = new Vector3(1f, 0f, 0f); real_t max_size = _size.x; if (_size.y > max_size) { axis = new Vector3(0f, 1f, 0f); max_size = _size.y; } if (_size.z > max_size) { axis = new Vector3(0f, 0f, 1f); } return axis; } /// <summary> /// Returns the <see cref="Vector3.Axis"/> index of the longest axis of the AABB. /// </summary> /// <returns>A <see cref="Vector3.Axis"/> index for which axis is longest.</returns> public Vector3.Axis GetLongestAxisIndex() { var axis = Vector3.Axis.X; real_t max_size = _size.x; if (_size.y > max_size) { axis = Vector3.Axis.Y; max_size = _size.y; } if (_size.z > max_size) { axis = Vector3.Axis.Z; } return axis; } /// <summary> /// Returns the scalar length of the longest axis of the AABB. /// </summary> /// <returns>The scalar length of the longest axis of the AABB.</returns> public real_t GetLongestAxisSize() { real_t max_size = _size.x; if (_size.y > max_size) max_size = _size.y; if (_size.z > max_size) max_size = _size.z; return max_size; } /// <summary> /// Returns the normalized shortest axis of the AABB. /// </summary> /// <returns>A vector representing the normalized shortest axis of the AABB.</returns> public Vector3 GetShortestAxis() { var axis = new Vector3(1f, 0f, 0f); real_t max_size = _size.x; if (_size.y < max_size) { axis = new Vector3(0f, 1f, 0f); max_size = _size.y; } if (_size.z < max_size) { axis = new Vector3(0f, 0f, 1f); } return axis; } /// <summary> /// Returns the <see cref="Vector3.Axis"/> index of the shortest axis of the AABB. /// </summary> /// <returns>A <see cref="Vector3.Axis"/> index for which axis is shortest.</returns> public Vector3.Axis GetShortestAxisIndex() { var axis = Vector3.Axis.X; real_t max_size = _size.x; if (_size.y < max_size) { axis = Vector3.Axis.Y; max_size = _size.y; } if (_size.z < max_size) { axis = Vector3.Axis.Z; } return axis; } /// <summary> /// Returns the scalar length of the shortest axis of the AABB. /// </summary> /// <returns>The scalar length of the shortest axis of the AABB.</returns> public real_t GetShortestAxisSize() { real_t max_size = _size.x; if (_size.y < max_size) max_size = _size.y; if (_size.z < max_size) max_size = _size.z; return max_size; } /// <summary> /// Returns the support point in a given direction. /// This is useful for collision detection algorithms. /// </summary> /// <param name="dir">The direction to find support for.</param> /// <returns>A vector representing the support.</returns> public Vector3 GetSupport(Vector3 dir) { Vector3 half_extents = _size * 0.5f; Vector3 ofs = _position + half_extents; return ofs + new Vector3( dir.x > 0f ? -half_extents.x : half_extents.x, dir.y > 0f ? -half_extents.y : half_extents.y, dir.z > 0f ? -half_extents.z : half_extents.z); } /// <summary> /// Returns a copy of the AABB grown a given amount of units towards all the sides. /// </summary> /// <param name="by">The amount to grow by.</param> /// <returns>The grown AABB.</returns> public AABB Grow(real_t by) { var res = this; res._position.x -= by; res._position.y -= by; res._position.z -= by; res._size.x += 2.0f * by; res._size.y += 2.0f * by; res._size.z += 2.0f * by; return res; } /// <summary> /// Returns true if the AABB is flat or empty, or false otherwise. /// </summary> /// <returns>A bool for whether or not the AABB has area.</returns> public bool HasNoArea() { return _size.x <= 0f || _size.y <= 0f || _size.z <= 0f; } /// <summary> /// Returns true if the AABB has no surface (no size), or false otherwise. /// </summary> /// <returns>A bool for whether or not the AABB has area.</returns> public bool HasNoSurface() { return _size.x <= 0f && _size.y <= 0f && _size.z <= 0f; } /// <summary> /// Returns true if the AABB contains a point, or false otherwise. /// </summary> /// <param name="point">The point to check.</param> /// <returns>A bool for whether or not the AABB contains `point`.</returns> public bool HasPoint(Vector3 point) { if (point.x < _position.x) return false; if (point.y < _position.y) return false; if (point.z < _position.z) return false; if (point.x > _position.x + _size.x) return false; if (point.y > _position.y + _size.y) return false; if (point.z > _position.z + _size.z) return false; return true; } /// <summary> /// Returns the intersection of this AABB and `b`. /// </summary> /// <param name="with">The other AABB.</param> /// <returns>The clipped AABB.</returns> public AABB Intersection(AABB with) { Vector3 src_min = _position; Vector3 src_max = _position + _size; Vector3 dst_min = with._position; Vector3 dst_max = with._position + with._size; Vector3 min, max; if (src_min.x > dst_max.x || src_max.x < dst_min.x) { return new AABB(); } min.x = src_min.x > dst_min.x ? src_min.x : dst_min.x; max.x = src_max.x < dst_max.x ? src_max.x : dst_max.x; if (src_min.y > dst_max.y || src_max.y < dst_min.y) { return new AABB(); } min.y = src_min.y > dst_min.y ? src_min.y : dst_min.y; max.y = src_max.y < dst_max.y ? src_max.y : dst_max.y; if (src_min.z > dst_max.z || src_max.z < dst_min.z) { return new AABB(); } min.z = src_min.z > dst_min.z ? src_min.z : dst_min.z; max.z = src_max.z < dst_max.z ? src_max.z : dst_max.z; return new AABB(min, max - min); } /// <summary> /// Returns true if the AABB overlaps with `b` /// (i.e. they have at least one point in common). /// /// If `includeBorders` is true, they will also be considered overlapping /// if their borders touch, even without intersection. /// </summary> /// <param name="with">The other AABB to check for intersections with.</param> /// <param name="includeBorders">Whether or not to consider borders.</param> /// <returns>A bool for whether or not they are intersecting.</returns> public bool Intersects(AABB with, bool includeBorders = false) { if (includeBorders) { if (_position.x > with._position.x + with._size.x) return false; if (_position.x + _size.x < with._position.x) return false; if (_position.y > with._position.y + with._size.y) return false; if (_position.y + _size.y < with._position.y) return false; if (_position.z > with._position.z + with._size.z) return false; if (_position.z + _size.z < with._position.z) return false; } else { if (_position.x >= with._position.x + with._size.x) return false; if (_position.x + _size.x <= with._position.x) return false; if (_position.y >= with._position.y + with._size.y) return false; if (_position.y + _size.y <= with._position.y) return false; if (_position.z >= with._position.z + with._size.z) return false; if (_position.z + _size.z <= with._position.z) return false; } return true; } /// <summary> /// Returns true if the AABB is on both sides of `plane`. /// </summary> /// <param name="plane">The plane to check for intersection.</param> /// <returns>A bool for whether or not the AABB intersects the plane.</returns> public bool IntersectsPlane(Plane plane) { Vector3[] points = { new Vector3(_position.x, _position.y, _position.z), new Vector3(_position.x, _position.y, _position.z + _size.z), new Vector3(_position.x, _position.y + _size.y, _position.z), new Vector3(_position.x, _position.y + _size.y, _position.z + _size.z), new Vector3(_position.x + _size.x, _position.y, _position.z), new Vector3(_position.x + _size.x, _position.y, _position.z + _size.z), new Vector3(_position.x + _size.x, _position.y + _size.y, _position.z), new Vector3(_position.x + _size.x, _position.y + _size.y, _position.z + _size.z) }; bool over = false; bool under = false; for (int i = 0; i < 8; i++) { if (plane.DistanceTo(points[i]) > 0) { over = true; } else { under = true; } } return under && over; } /// <summary> /// Returns true if the AABB intersects the line segment between `from` and `to`. /// </summary> /// <param name="from">The start of the line segment.</param> /// <param name="to">The end of the line segment.</param> /// <returns>A bool for whether or not the AABB intersects the line segment.</returns> public bool IntersectsSegment(Vector3 from, Vector3 to) { real_t min = 0f; real_t max = 1f; for (int i = 0; i < 3; i++) { real_t segFrom = from[i]; real_t segTo = to[i]; real_t boxBegin = _position[i]; real_t boxEnd = boxBegin + _size[i]; real_t cmin, cmax; if (segFrom < segTo) { if (segFrom > boxEnd || segTo < boxBegin) { return false; } real_t length = segTo - segFrom; cmin = segFrom < boxBegin ? (boxBegin - segFrom) / length : 0f; cmax = segTo > boxEnd ? (boxEnd - segFrom) / length : 1f; } else { if (segTo > boxEnd || segFrom < boxBegin) { return false; } real_t length = segTo - segFrom; cmin = segFrom > boxEnd ? (boxEnd - segFrom) / length : 0f; cmax = segTo < boxBegin ? (boxBegin - segFrom) / length : 1f; } if (cmin > min) { min = cmin; } if (cmax < max) { max = cmax; } if (max < min) { return false; } } return true; } /// <summary> /// Returns a larger AABB that contains this AABB and `b`. /// </summary> /// <param name="with">The other AABB.</param> /// <returns>The merged AABB.</returns> public AABB Merge(AABB with) { Vector3 beg1 = _position; Vector3 beg2 = with._position; var end1 = new Vector3(_size.x, _size.y, _size.z) + beg1; var end2 = new Vector3(with._size.x, with._size.y, with._size.z) + beg2; var min = new Vector3( beg1.x < beg2.x ? beg1.x : beg2.x, beg1.y < beg2.y ? beg1.y : beg2.y, beg1.z < beg2.z ? beg1.z : beg2.z ); var max = new Vector3( end1.x > end2.x ? end1.x : end2.x, end1.y > end2.y ? end1.y : end2.y, end1.z > end2.z ? end1.z : end2.z ); return new AABB(min, max - min); } /// <summary> /// Constructs an AABB from a position and size. /// </summary> /// <param name="position">The position.</param> /// <param name="size">The size, typically positive.</param> public AABB(Vector3 position, Vector3 size) { _position = position; _size = size; } /// <summary> /// Constructs an AABB from a position, width, height, and depth. /// </summary> /// <param name="position">The position.</param> /// <param name="width">The width, typically positive.</param> /// <param name="height">The height, typically positive.</param> /// <param name="depth">The depth, typically positive.</param> public AABB(Vector3 position, real_t width, real_t height, real_t depth) { _position = position; _size = new Vector3(width, height, depth); } /// <summary> /// Constructs an AABB from x, y, z, and size. /// </summary> /// <param name="x">The position's X coordinate.</param> /// <param name="y">The position's Y coordinate.</param> /// <param name="z">The position's Z coordinate.</param> /// <param name="size">The size, typically positive.</param> public AABB(real_t x, real_t y, real_t z, Vector3 size) { _position = new Vector3(x, y, z); _size = size; } /// <summary> /// Constructs an AABB from x, y, z, width, height, and depth. /// </summary> /// <param name="x">The position's X coordinate.</param> /// <param name="y">The position's Y coordinate.</param> /// <param name="z">The position's Z coordinate.</param> /// <param name="width">The width, typically positive.</param> /// <param name="height">The height, typically positive.</param> /// <param name="depth">The depth, typically positive.</param> public AABB(real_t x, real_t y, real_t z, real_t width, real_t height, real_t depth) { _position = new Vector3(x, y, z); _size = new Vector3(width, height, depth); } public static bool operator ==(AABB left, AABB right) { return left.Equals(right); } public static bool operator !=(AABB left, AABB right) { return !left.Equals(right); } public override bool Equals(object obj) { if (obj is AABB) { return Equals((AABB)obj); } return false; } public bool Equals(AABB other) { return _position == other._position && _size == other._size; } /// <summary> /// Returns true if this AABB and `other` are approximately equal, by running /// <see cref="Vector3.IsEqualApprox(Vector3)"/> on each component. /// </summary> /// <param name="other">The other AABB to compare.</param> /// <returns>Whether or not the AABBs are approximately equal.</returns> public bool IsEqualApprox(AABB other) { return _position.IsEqualApprox(other._position) && _size.IsEqualApprox(other._size); } public override int GetHashCode() { return _position.GetHashCode() ^ _size.GetHashCode(); } public override string ToString() { return $"{_position}, {_size}"; } public string ToString(string format) { return $"{_position.ToString(format)}, {_size.ToString(format)}"; } } }
using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Net; using Svg.Transforms; namespace Svg { /// <summary> /// Represents and SVG image /// </summary> [SvgElement("image")] public class SvgImage : SvgVisualElement { /// <summary> /// Initializes a new instance of the <see cref="SvgImage"/> class. /// </summary> public SvgImage() { Width = new SvgUnit(0.0f); Height = new SvgUnit(0.0f); } private GraphicsPath _path; /// <summary> /// Gets an <see cref="SvgPoint"/> representing the top left point of the rectangle. /// </summary> public SvgPoint Location { get { return new SvgPoint(X, Y); } } /// <summary> /// Gets or sets the aspect of the viewport. /// </summary> /// <value></value> [SvgAttribute("preserveAspectRatio")] public SvgAspectRatio AspectRatio { get { return this.Attributes.GetAttribute<SvgAspectRatio>("preserveAspectRatio"); } set { this.Attributes["preserveAspectRatio"] = value; } } [SvgAttribute("x")] public virtual SvgUnit X { get { return this.Attributes.GetAttribute<SvgUnit>("x"); } set { this.Attributes["x"] = value; } } [SvgAttribute("y")] public virtual SvgUnit Y { get { return this.Attributes.GetAttribute<SvgUnit>("y"); } set { this.Attributes["y"] = value; } } [SvgAttribute("width")] public virtual SvgUnit Width { get { return this.Attributes.GetAttribute<SvgUnit>("width"); } set { this.Attributes["width"] = value; } } [SvgAttribute("height")] public virtual SvgUnit Height { get { return this.Attributes.GetAttribute<SvgUnit>("height"); } set { this.Attributes["height"] = value; } } [SvgAttribute("href", SvgAttributeAttribute.XLinkNamespace)] public virtual string Href { get { return this.Attributes.GetAttribute<string>("href"); } set { this.Attributes["href"] = value; } } /// <summary> /// Gets the bounds of the element. /// </summary> /// <value>The bounds.</value> public override RectangleF Bounds { get { return TransformedBounds(new RectangleF(this.Location.ToDeviceValue(null, this), new SizeF(this.Width.ToDeviceValue(null, UnitRenderingType.Horizontal, this), this.Height.ToDeviceValue(null, UnitRenderingType.Vertical, this)))); } } /// <summary> /// Gets the <see cref="GraphicsPath"/> for this element. /// </summary> public override GraphicsPath Path(ISvgRenderer renderer) { if (_path == null) { // Same size of rectangle can suffice to provide bounds of the image var rectangle = new RectangleF(Location.ToDeviceValue(renderer, this), SvgUnit.GetDeviceSize(Width, Height, renderer, this)); _path = new GraphicsPath(); _path.StartFigure(); _path.AddRectangle(rectangle); _path.CloseFigure(); } return _path; } /// <summary> /// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="Graphics"/> object. /// </summary> protected override void Render(ISvgRenderer renderer) { if (!Visible || !Displayable) return; if (Width.Value > 0.0f && Height.Value > 0.0f && this.Href != null) { var img = GetImage(); if (img != null) { RectangleF srcRect; var bmp = img as Image; var svg = img as SvgFragment; if (bmp != null) { srcRect = new RectangleF(0, 0, bmp.Width, bmp.Height); } else if (svg != null) { srcRect = new RectangleF(new PointF(0, 0), svg.GetDimensions()); } else { return; } var destClip = new RectangleF(this.Location.ToDeviceValue(renderer, this), new SizeF(Width.ToDeviceValue(renderer, UnitRenderingType.Horizontal, this), Height.ToDeviceValue(renderer, UnitRenderingType.Vertical, this))); RectangleF destRect = destClip; this.PushTransforms(renderer); renderer.SetClip(new Region(destClip), CombineMode.Intersect); this.SetClip(renderer); SvgAspectRatio aspectRatio = AspectRatio ?? new SvgAspectRatio(SvgPreserveAspectRatio.xMidYMid); if (aspectRatio.Align != SvgPreserveAspectRatio.none) { var fScaleX = destClip.Width / srcRect.Width; var fScaleY = destClip.Height / srcRect.Height; var xOffset = 0.0f; var yOffset = 0.0f; if (aspectRatio.Slice) { fScaleX = Math.Max(fScaleX, fScaleY); fScaleY = Math.Max(fScaleX, fScaleY); } else { fScaleX = Math.Min(fScaleX, fScaleY); fScaleY = Math.Min(fScaleX, fScaleY); } switch (aspectRatio.Align) { case SvgPreserveAspectRatio.xMinYMin: break; case SvgPreserveAspectRatio.xMidYMin: xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2; break; case SvgPreserveAspectRatio.xMaxYMin: xOffset = (destClip.Width - srcRect.Width * fScaleX); break; case SvgPreserveAspectRatio.xMinYMid: yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatio.xMidYMid: xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2; yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatio.xMaxYMid: xOffset = (destClip.Width - srcRect.Width * fScaleX); yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatio.xMinYMax: yOffset = (destClip.Height - srcRect.Height * fScaleY); break; case SvgPreserveAspectRatio.xMidYMax: xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2; yOffset = (destClip.Height - srcRect.Height * fScaleY); break; case SvgPreserveAspectRatio.xMaxYMax: xOffset = (destClip.Width - srcRect.Width * fScaleX); yOffset = (destClip.Height - srcRect.Height * fScaleY); break; } destRect = new RectangleF(destClip.X + xOffset, destClip.Y + yOffset, srcRect.Width * fScaleX, srcRect.Height * fScaleY); } if (bmp != null) { if(Opacity==1F) renderer.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel); else renderer.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel, Opacity); bmp.Dispose(); } else if (svg != null) { var currOffset = new PointF(renderer.Transform.OffsetX, renderer.Transform.OffsetY); renderer.TranslateTransform(-currOffset.X, -currOffset.Y); renderer.ScaleTransform(destRect.Width / srcRect.Width, destRect.Height / srcRect.Height); renderer.TranslateTransform(currOffset.X + destRect.X, currOffset.Y + destRect.Y); renderer.SetBoundable(new GenericBoundable(srcRect)); svg.RenderElement(renderer); renderer.PopBoundable(); } this.ResetClip(renderer); this.PopTransforms(renderer); } // TODO: cache images... will need a shared context for this // TODO: support preserveAspectRatio, etc } } public object GetImage() { return this.GetImage(this.Href); } public object GetImage(string uriString) { string safeUriString; if (uriString.Length > 65519) { //Uri MaxLength is 65519 (https://msdn.microsoft.com/en-us/library/z6c2z492.aspx) safeUriString = uriString.Substring(0, 65519); } else { safeUriString = uriString; } try { var uri = new Uri(safeUriString, UriKind.RelativeOrAbsolute); // handle data/uri embedded images (http://en.wikipedia.org/wiki/Data_URI_scheme) if (uri.IsAbsoluteUri && uri.Scheme == "data") { int dataIdx = uriString.IndexOf(",") + 1; if (dataIdx <= 0 || dataIdx + 1 > uriString.Length) throw new Exception("Invalid data URI"); // we're assuming base64, as ascii encoding would be *highly* unsusual for images // also assuming it's png or jpeg mimetype byte[] imageBytes = Convert.FromBase64String(uriString.Substring(dataIdx)); using (var stream = new MemoryStream(imageBytes)) { return Image.FromStream(stream); } } if (!uri.IsAbsoluteUri) { uri = new Uri(OwnerDocument.BaseUri, uri); } // should work with http: and file: protocol urls var httpRequest = WebRequest.Create(uri); using (WebResponse webResponse = httpRequest.GetResponse()) { using (var stream = webResponse.GetResponseStream()) { if (stream.CanSeek) { stream.Position = 0; } if (uri.LocalPath.EndsWith(".svg", StringComparison.InvariantCultureIgnoreCase)) { var doc = SvgDocument.Open<SvgDocument>(stream); doc.BaseUri = uri; return doc; } else { return Bitmap.FromStream(stream); } } } } catch (Exception ex) { Trace.TraceError("Error loading image: '{0}', error: {1} ", uriString, ex.Message); return null; } } protected static MemoryStream BufferToMemoryStream(Stream input) { byte[] buffer = new byte[4 * 1024]; int len; MemoryStream ms = new MemoryStream(); while ((len = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, len); } ms.Seek(0, SeekOrigin.Begin); return ms; } public override SvgElement DeepCopy() { return DeepCopy<SvgImage>(); } public override SvgElement DeepCopy<T>() { var newObj = base.DeepCopy<T>() as SvgImage; newObj.Height = this.Height; newObj.Width = this.Width; newObj.X = this.X; newObj.Y = this.Y; newObj.Href = this.Href; return newObj; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using Microsoft.Scripting; #if FEATURE_CORE_DLR using MSAst = System.Linq.Expressions; using System.Linq.Expressions; #else using MSAst = Microsoft.Scripting.Ast; #endif using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Ast; using Microsoft.Scripting.Interpreter; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; namespace IronPython.Compiler.Ast { using Ast = MSAst.Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; public abstract class Node : MSAst.Expression { private ScopeStatement _parent; private IndexSpan _span; internal static readonly MSAst.BlockExpression EmptyBlock = Ast.Block(AstUtils.Empty()); internal static readonly MSAst.Expression[] EmptyExpression = new MSAst.Expression[0]; internal static MSAst.ParameterExpression FunctionStackVariable = Ast.Variable(typeof(List<FunctionStack>), "$funcStack"); internal static readonly MSAst.LabelTarget GeneratorLabel = Ast.Label(typeof(object), "$generatorLabel"); private static MSAst.ParameterExpression _lineNumberUpdated = Ast.Variable(typeof(bool), "$lineUpdated"); private static readonly MSAst.ParameterExpression _lineNoVar = Ast.Parameter(typeof(int), "$lineNo"); protected Node() { } #region Public API public ScopeStatement Parent { get { return _parent; } set { _parent = value; } } public void SetLoc(PythonAst globalParent, int start, int end) { _span = new IndexSpan(start, end > start ? end - start : start); _parent = globalParent; } public void SetLoc(PythonAst globalParent, IndexSpan span) { _span = span; _parent = globalParent; } public IndexSpan IndexSpan { get { return _span; } set { _span = value; } } public SourceLocation Start { get { return GlobalParent.IndexToLocation(StartIndex); } } public SourceLocation End { get { return GlobalParent.IndexToLocation(EndIndex); } } public int EndIndex { get { return _span.End; } set { _span = new IndexSpan(_span.Start, value - _span.Start); } } public int StartIndex { get { return _span.Start; } set { _span = new IndexSpan(value, 0); } } internal SourceLocation IndexToLocation(int index) { if (index == -1) { return SourceLocation.Invalid; } var locs = GlobalParent._lineLocations; int match = Array.BinarySearch(locs, index); if (match < 0) { // If our index = -1, it means we're on the first line. if (match == -1) { return new SourceLocation(index, 1, index + 1); } // If we couldn't find an exact match for this line number, get the nearest // matching line number less than this one match = ~match - 1; } return new SourceLocation(index, match + 2, index - locs[match] + 1); } public SourceSpan Span { get { return new SourceSpan(Start, End); } } public abstract void Walk(PythonWalker walker); public virtual string NodeName { get { return GetType().Name; } } #endregion #region Base Class Overrides /// <summary> /// Returns true if the node can throw, false otherwise. Used to determine /// whether or not we need to update the current dynamic stack info. /// </summary> internal virtual bool CanThrow { get { return true; } } public override bool CanReduce { get { return true; } } public override MSAst.ExpressionType NodeType { get { return MSAst.ExpressionType.Extension; } } public override string ToString() { return GetType().Name; } #endregion #region Internal APIs internal PythonAst GlobalParent { get { Node cur = this; while (!(cur is PythonAst)) { Debug.Assert(cur != null); cur = cur.Parent; } return (PythonAst)cur; } } internal bool EmitDebugSymbols { get { return GlobalParent.EmitDebugSymbols; } } internal bool StripDocStrings { get { return GlobalParent.PyContext.PythonOptions.StripDocStrings; } } internal bool Optimize { get { return GlobalParent.PyContext.PythonOptions.Optimize; } } internal virtual string GetDocumentation(Statement/*!*/ stmt) { if (StripDocStrings) { return null; } return stmt.Documentation; } #endregion #region Transformation Helpers internal static MSAst.Expression[] ToObjectArray(IList<Expression> expressions) { MSAst.Expression[] to = new MSAst.Expression[expressions.Count]; for (int i = 0; i < expressions.Count; i++) { to[i] = AstUtils.Convert(expressions[i], typeof(object)); } return to; } internal static MSAst.Expression TransformOrConstantNull(Expression expression, Type/*!*/ type) { if (expression == null) { return AstUtils.Constant(null, type); } else { return AstUtils.Convert(expression, type); } } internal MSAst.Expression TransformAndDynamicConvert(Expression expression, Type/*!*/ type) { Debug.Assert(expression != null); MSAst.Expression res = expression; // Do we need conversion? if (!CanAssign(type, expression.Type)) { // ensure we're reduced before we check for dynamic expressions. var reduced = expression.Reduce(); if (reduced is LightDynamicExpression) { reduced = reduced.Reduce(); } // Add conversion step to the AST MSAst.DynamicExpression ae = reduced as MSAst.DynamicExpression; ReducableDynamicExpression rde = reduced as ReducableDynamicExpression; if ((ae != null && ae.Binder is PythonBinaryOperationBinder) || (rde != null && rde.Binder is PythonBinaryOperationBinder)) { // create a combo site which does the conversion PythonBinaryOperationBinder binder; IList<MSAst.Expression> args; if (ae != null) { binder = (PythonBinaryOperationBinder)ae.Binder; args = ArrayUtils.ToArray(ae.Arguments); } else { binder = (PythonBinaryOperationBinder)rde.Binder; args = rde.Args; } ParameterMappingInfo[] infos = new ParameterMappingInfo[args.Count]; for (int i = 0; i < infos.Length; i++) { infos[i] = ParameterMappingInfo.Parameter(i); } res = Expression.Dynamic( GlobalParent.PyContext.BinaryOperationRetType( binder, GlobalParent.PyContext.Convert( type, ConversionResultKind.ExplicitCast ) ), type, args ); } else { res = GlobalParent.Convert( type, ConversionResultKind.ExplicitCast, reduced ); } } return res; } internal static bool CanAssign(Type/*!*/ to, Type/*!*/ from) { return to.IsAssignableFrom(from) && (to.IsValueType == from.IsValueType); } internal static MSAst.Expression/*!*/ ConvertIfNeeded(MSAst.Expression/*!*/ expression, Type/*!*/ type) { Debug.Assert(expression != null); // Do we need conversion? if (!CanAssign(type, expression.Type)) { // Add conversion step to the AST expression = AstUtils.Convert(expression, type); } return expression; } internal static MSAst.Expression TransformMaybeSingleLineSuite(Statement body, SourceLocation prevStart) { if (body.GlobalParent.IndexToLocation(body.StartIndex).Line != prevStart.Line) { return body; } MSAst.Expression res = body.Reduce(); res = RemoveDebugInfo(prevStart.Line, res); if (res.Type != typeof(void)) { res = AstUtils.Void(res); } return res; } internal static MSAst.Expression RemoveDebugInfo(int prevStart, MSAst.Expression res) { MSAst.BlockExpression block = res as MSAst.BlockExpression; if (block != null && block.Expressions.Count > 0) { MSAst.DebugInfoExpression dbgInfo = block.Expressions[0] as MSAst.DebugInfoExpression; // body on the same line as an if, don't generate a 2nd sequence point if (dbgInfo != null && dbgInfo.StartLine == prevStart) { // we remove the debug info based upon how it's generated in DebugStatement.AddDebugInfo which is // the helper method which adds the debug info. if (block.Type == typeof(void)) { Debug.Assert(block.Expressions.Count == 3); Debug.Assert(block.Expressions[2] is MSAst.DebugInfoExpression && ((MSAst.DebugInfoExpression)block.Expressions[2]).IsClear); res = block.Expressions[1]; } else { Debug.Assert(block.Expressions.Count == 4); Debug.Assert(block.Expressions[3] is MSAst.DebugInfoExpression && ((MSAst.DebugInfoExpression)block.Expressions[2]).IsClear); Debug.Assert(block.Expressions[1] is MSAst.BinaryExpression && ((MSAst.BinaryExpression)block.Expressions[2]).NodeType == MSAst.ExpressionType.Assign); res = ((MSAst.BinaryExpression)block.Expressions[1]).Right; } } } return res; } /// <summary> /// Creates a method frame for tracking purposes and enforces recursion /// </summary> internal static MSAst.Expression AddFrame(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body) { return new FramedCodeExpression(localContext, codeObject, body); } /// <summary> /// Removes the frames from generated code for when we're compiling the tracing delegate /// which will track the frames it's self. /// </summary> internal static MSAst.Expression RemoveFrame(MSAst.Expression expression) { return new FramedCodeVisitor().Visit(expression); } class FramedCodeVisitor : ExpressionVisitor { public override MSAst.Expression Visit(MSAst.Expression node) { FramedCodeExpression framedCode = node as FramedCodeExpression; if (framedCode != null) { return framedCode.Body; } return base.Visit(node); } } sealed class FramedCodeExpression : MSAst.Expression { private readonly MSAst.Expression _localContext, _codeObject, _body; public FramedCodeExpression(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body) { _localContext = localContext; _codeObject = codeObject; _body = body; } public override ExpressionType NodeType { get { return ExpressionType.Extension; } } public MSAst.Expression Body { get { return _body; } } public override MSAst.Expression Reduce() { return AstUtils.Try( Ast.Assign( FunctionStackVariable, Ast.Call( AstMethods.PushFrame, _localContext, _codeObject ) ), _body ).Finally( Ast.Call( FunctionStackVariable, typeof(List<FunctionStack>).GetMethod("RemoveAt"), Ast.Add( Ast.Property( FunctionStackVariable, "Count" ), Ast.Constant(-1) ) ) ); } public override Type Type { get { return _body.Type; } } public override bool CanReduce { get { return true; } } protected override MSAst.Expression VisitChildren(ExpressionVisitor visitor) { var localContext = visitor.Visit(_localContext); var codeObject = visitor.Visit(_codeObject); var body = visitor.Visit(_body); if (localContext != _localContext || _codeObject != codeObject || body != _body) { return new FramedCodeExpression(localContext, codeObject, body); } return this; } } internal static MSAst.Expression/*!*/ MakeAssignment(MSAst.ParameterExpression/*!*/ variable, MSAst.Expression/*!*/ right) { return Ast.Assign(variable, AstUtils.Convert(right, variable.Type)); } internal MSAst.Expression MakeAssignment(MSAst.ParameterExpression variable, MSAst.Expression right, SourceSpan span) { return GlobalParent.AddDebugInfoAndVoid(Ast.Assign(variable, AstUtils.Convert(right, variable.Type)), span); } internal static MSAst.Expression/*!*/ AssignValue(MSAst.Expression/*!*/ expression, MSAst.Expression value) { Debug.Assert(expression != null); Debug.Assert(value != null); IPythonVariableExpression pyGlobal = expression as IPythonVariableExpression; if (pyGlobal != null) { return pyGlobal.Assign(value); } return Ast.Assign(expression, value); } internal static MSAst.Expression/*!*/ Delete(MSAst.Expression/*!*/ expression) { IPythonVariableExpression pyGlobal = expression as IPythonVariableExpression; if (pyGlobal != null) { return pyGlobal.Delete(); } return Ast.Assign(expression, Ast.Field(null, typeof(Uninitialized).GetField("Instance"))); } #endregion #region Basic Line Number Infrastructure /// <summary> /// A temporary variable to track if the current line number has been emitted via the fault update block. /// /// For example consider: /// /// try: /// raise Exception() /// except Exception, e: /// # do something here /// raise /// /// At "do something here" we need to have already emitted the line number, when we re-raise we shouldn't add it /// again. If we handled the exception then we should have set the bool back to false. /// /// We also sometimes directly check _lineNoUpdated to avoid creating this unless we have nested exceptions. /// </summary> internal static MSAst.ParameterExpression/*!*/ LineNumberUpdated { get { return _lineNumberUpdated; } } internal static MSAst.Expression UpdateLineNumber(int line) { return Ast.Assign(LineNumberExpression, AstUtils.Constant(line)); } internal static MSAst.Expression UpdateLineUpdated(bool updated) { return Ast.Assign(LineNumberUpdated, AstUtils.Constant(updated)); } internal static MSAst.Expression PushLineUpdated(bool updated, MSAst.ParameterExpression saveCurrent) { return MSAst.Expression.Block( Ast.Assign(saveCurrent, LineNumberUpdated), Ast.Assign(LineNumberUpdated, AstUtils.Constant(updated)) ); } internal static MSAst.Expression PopLineUpdated(MSAst.ParameterExpression saveCurrent) { return Ast.Assign(LineNumberUpdated, saveCurrent); } /// <summary> /// A temporary variable to track the current line number /// </summary> internal static MSAst.ParameterExpression/*!*/ LineNumberExpression { get { return _lineNoVar; } } #endregion } }
// // SiteTest.cs - NUnit Test Cases for Site // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2004 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Globalization; using System.Security; using System.Security.Permissions; using System.Security.Policy; namespace MonoTests.System.Security.Policy { [TestFixture] public class SiteTest : Assertion { [Test] [ExpectedException (typeof (ArgumentNullException))] public void Site_Null () { Site s = new Site (null); } [Test] [ExpectedException (typeof (ArgumentException))] public void Site_Empty () { Site s = new Site (String.Empty); } [Test] [ExpectedException (typeof (ArgumentException))] public void Site_FileUrl () { Site s = new Site ("file://mono/index.html"); } [Test] [ExpectedException (typeof (ArgumentException))] public void Site_AllGoMono () { Site s = new Site ("http://*.go-mono.com"); } [Test] [ExpectedException (typeof (ArgumentException))] public void Site_FullUrlWithPort () { Site s = new Site ("http://www.go-mono.com:8080/index.html"); } [Test] public void Site_GoMonoWebSite () { Site s = new Site ("www.go-mono.com"); AssertEquals ("Name", "www.go-mono.com", s.Name); #if NET_2_0 AssertEquals ("ToString", "<System.Security.Policy.Site version=\"1\">" + Environment.NewLine + "<Name>www.go-mono.com</Name>" + Environment.NewLine + "</System.Security.Policy.Site>" + Environment.NewLine, s.ToString ()); #else AssertEquals ("ToString", "<System.Security.Policy.Site version=\"1\">" + Environment.NewLine + " <Name>www.go-mono.com</Name>" + Environment.NewLine + "</System.Security.Policy.Site>" + Environment.NewLine, s.ToString ()); #endif Site s2 = (Site) s.Copy (); AssertEquals ("Copy.Name", s.Name, s2.Name); AssertEquals ("Copy.GetHashCode", s.GetHashCode (), s2.GetHashCode ()); SiteIdentityPermission sip = (SiteIdentityPermission) s.CreateIdentityPermission (null); AssertEquals ("CreateIdentityPermission", s.Name, sip.Site); Assert ("Equals", s.Equals (s2)); Site s3 = new Site ("go-mono.com"); Assert ("!Equals", !s.Equals (s3)); } [Test] public void Site_AllGoMonoSite () { Site s = new Site ("*.go-mono.com"); AssertEquals ("Name", "*.go-mono.com", s.Name); #if NET_2_0 AssertEquals ("ToString", "<System.Security.Policy.Site version=\"1\">" + Environment.NewLine + "<Name>*.go-mono.com</Name>" + Environment.NewLine + "</System.Security.Policy.Site>" + Environment.NewLine, s.ToString ()); #else AssertEquals ("ToString", "<System.Security.Policy.Site version=\"1\">" + Environment.NewLine + " <Name>*.go-mono.com</Name>" + Environment.NewLine + "</System.Security.Policy.Site>" + Environment.NewLine, s.ToString ()); #endif Site s2 = (Site) s.Copy (); AssertEquals ("Copy.Name", s.Name, s2.Name); AssertEquals ("Copy.GetHashCode", s.GetHashCode (), s2.GetHashCode ()); SiteIdentityPermission sip = (SiteIdentityPermission) s.CreateIdentityPermission (null); AssertEquals ("CreateIdentityPermission", s.Name, sip.Site); Assert ("Equals", s.Equals (s2)); Site s3 = new Site ("go-mono.com"); Assert ("!Equals", !s.Equals (s3)); } [Test] [ExpectedException (typeof (ArgumentException))] public void Site_GoMonoAllTLD () { Site s = new Site ("www.go-mono.*"); } [Test] [ExpectedException (typeof (ArgumentException))] public void Site_TwoStars () { Site s = new Site ("*.*.go-mono.com"); } [Test] public void EqualsCaseSensitive () { Site s1 = new Site ("*.go-mono.com"); Site s2 = new Site ("*.Go-Mono.com"); Assert ("CaseSensitive", s1.Equals (s2)); } [Test] public void EqualsPartial () { Site s1 = new Site ("www.go-mono.com"); Site s2 = new Site ("*.go-mono.com"); Assert ("Partial:1-2", !s1.Equals (s2)); Assert ("Partial:2-1", !s2.Equals (s1)); } [Test] public void EqualsNull () { Site s1 = new Site ("*.go-mono.com"); Assert ("EqualsNull", !s1.Equals (null)); } [Test] public void Site_LoneStar () { Site s = new Site ("*"); AssertEquals ("Name", "*", s.Name); #if NET_2_0 AssertEquals ("ToString", "<System.Security.Policy.Site version=\"1\">" + Environment.NewLine + "<Name>*</Name>" + Environment.NewLine + "</System.Security.Policy.Site>" + Environment.NewLine, s.ToString ()); #else AssertEquals ("ToString", "<System.Security.Policy.Site version=\"1\">" + Environment.NewLine + " <Name>*</Name>" + Environment.NewLine + "</System.Security.Policy.Site>" + Environment.NewLine, s.ToString ()); #endif Site s2 = (Site) s.Copy (); AssertEquals ("Copy.Name", s.Name, s2.Name); AssertEquals ("Copy.GetHashCode", s.GetHashCode (), s2.GetHashCode ()); SiteIdentityPermission sip = (SiteIdentityPermission) s.CreateIdentityPermission (null); AssertEquals ("CreateIdentityPermission", s.Name, sip.Site); Assert ("Equals", s.Equals (s2)); Site s3 = new Site ("go-mono.com"); Assert ("!Equals", !s.Equals (s3)); } [Test] public void AllChars () { for (int i=1; i < 256; i++) { bool actual = false; char c = Convert.ToChar (i); try { Site s = new Site (Convert.ToString (c)); actual = true; // Console.WriteLine ("GOOD: {0} - {1}", i, c); } catch { // Console.WriteLine ("FAIL: {0} - {1}", i, c); } bool result = ((i == 45) // - #if NET_2_0 || (i == 33) // ! || (i >= 35 && i <= 42) // #$%&'()* || (i >= 48 && i <= 57) // 0-9 || (i >= 94 && i <= 95) // ^_ || (i >= 97 && i <= 123) // a-z{ || (i >= 125 && i <= 126) // }~ #else || (i == 42) // * || (i >= 47 && i <= 57) // /,0-9 || (i == 95) // _ || (i >= 97 && i <= 122) // a-z #endif || (i >= 64 && i <= 90)); // @,A-Z Assert ("#"+i, (actual == result)); } } [Test] [ExpectedException (typeof (ArgumentNullException))] public void CreateFromUrl_Null () { Site.CreateFromUrl (null); } [Test] [ExpectedException (typeof (FormatException))] public void CreateFromUrl_Empty () { Site.CreateFromUrl (String.Empty); } string[] valid_urls = { "http://www.go-mono.com", "http://*.go-mono.com", "http://www.go-mono.com:8080/index.html", #if !NET_2_0 "file://mono/index.html", // file:// is supported as a site (1.0/1.1) #endif }; [Test] public void CreateFromUrl_Valid () { foreach (string url in valid_urls) { Site s = Site.CreateFromUrl (url); Assert (s.Name, (s.Name.ToUpper (CultureInfo.InvariantCulture).IndexOf ("MONO") != -1)); } } #if NET_2_0 string[] invalid_urls = { "file://mono/index.html", // file:// isn't supported as a site (2.0) }; [Test] public void CreateFromUrl_Invalid () { string msg = null; foreach (string url in invalid_urls) { try { Site.CreateFromUrl (url); msg = String.Format ("Expected ArgumentException for {0} but got none", url); } catch (ArgumentException) { } catch (Exception e) { msg = String.Format ("Expected ArgumentException for {0} but got: {1}", url, e); } finally { if (msg != null) { Fail (msg); msg = null; } } } } #endif } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.DocumentationComments; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISymbolExtensions2 { public static Glyph GetGlyph(this ISymbol symbol) { Glyph publicIcon; switch (symbol.Kind) { case SymbolKind.Alias: return ((IAliasSymbol)symbol).Target.GetGlyph(); case SymbolKind.Assembly: return Glyph.Assembly; case SymbolKind.ArrayType: return ((IArrayTypeSymbol)symbol).ElementType.GetGlyph(); case SymbolKind.DynamicType: return Glyph.ClassPublic; case SymbolKind.Event: publicIcon = Glyph.EventPublic; break; case SymbolKind.Field: var containingType = symbol.ContainingType; if (containingType != null && containingType.TypeKind == TypeKind.Enum) { return Glyph.EnumMember; } publicIcon = ((IFieldSymbol)symbol).IsConst ? Glyph.ConstantPublic : Glyph.FieldPublic; break; case SymbolKind.Label: return Glyph.Label; case SymbolKind.Local: return Glyph.Local; case SymbolKind.NamedType: case SymbolKind.ErrorType: { switch (((INamedTypeSymbol)symbol).TypeKind) { case TypeKind.Class: publicIcon = Glyph.ClassPublic; break; case TypeKind.Delegate: publicIcon = Glyph.DelegatePublic; break; case TypeKind.Enum: publicIcon = Glyph.EnumPublic; break; case TypeKind.Interface: publicIcon = Glyph.InterfacePublic; break; case TypeKind.Module: publicIcon = Glyph.ModulePublic; break; case TypeKind.Struct: publicIcon = Glyph.StructurePublic; break; case TypeKind.Error: return Glyph.Error; default: throw new ArgumentException(FeaturesResources.The_symbol_does_not_have_an_icon, nameof(symbol)); } break; } case SymbolKind.Method: { var methodSymbol = (IMethodSymbol)symbol; if (methodSymbol.MethodKind == MethodKind.UserDefinedOperator || methodSymbol.MethodKind == MethodKind.Conversion) { return Glyph.Operator; } else if (methodSymbol.IsExtensionMethod || methodSymbol.MethodKind == MethodKind.ReducedExtension) { publicIcon = Glyph.ExtensionMethodPublic; } else { publicIcon = Glyph.MethodPublic; } } break; case SymbolKind.Namespace: return Glyph.Namespace; case SymbolKind.NetModule: return Glyph.Assembly; case SymbolKind.Parameter: return symbol.IsValueParameter() ? Glyph.Keyword : Glyph.Parameter; case SymbolKind.PointerType: return ((IPointerTypeSymbol)symbol).PointedAtType.GetGlyph(); case SymbolKind.Property: { var propertySymbol = (IPropertySymbol)symbol; if (propertySymbol.IsWithEvents) { publicIcon = Glyph.FieldPublic; } else { publicIcon = Glyph.PropertyPublic; } } break; case SymbolKind.RangeVariable: return Glyph.RangeVariable; case SymbolKind.TypeParameter: return Glyph.TypeParameter; default: throw new ArgumentException(FeaturesResources.The_symbol_does_not_have_an_icon, nameof(symbol)); } switch (symbol.DeclaredAccessibility) { case Accessibility.Private: publicIcon += Glyph.ClassPrivate - Glyph.ClassPublic; break; case Accessibility.Protected: case Accessibility.ProtectedAndInternal: case Accessibility.ProtectedOrInternal: publicIcon += Glyph.ClassProtected - Glyph.ClassPublic; break; case Accessibility.Internal: publicIcon += Glyph.ClassInternal - Glyph.ClassPublic; break; } return publicIcon; } public static IEnumerable<TaggedText> GetDocumentationParts(this ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken) { var documentation = symbol.TypeSwitch( (IParameterSymbol parameter) => parameter.ContainingSymbol.OriginalDefinition.GetDocumentationComment(cancellationToken: cancellationToken).GetParameterText(symbol.Name), (ITypeParameterSymbol typeParam) => typeParam.ContainingSymbol.GetDocumentationComment(cancellationToken: cancellationToken).GetTypeParameterText(symbol.Name), (IMethodSymbol method) => GetMethodDocumentation(method), (IAliasSymbol alias) => alias.Target.GetDocumentationComment(cancellationToken: cancellationToken).SummaryText, _ => symbol.GetDocumentationComment(cancellationToken: cancellationToken).SummaryText); return documentation != null ? formatter.Format(documentation, semanticModel, position, CrefFormat) : SpecializedCollections.EmptyEnumerable<TaggedText>(); } public static Func<CancellationToken, IEnumerable<TaggedText>> GetDocumentationPartsFactory( this ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter) { return c => symbol.GetDocumentationParts(semanticModel, position, formatter, cancellationToken: c); } public static readonly SymbolDisplayFormat CrefFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static string GetMethodDocumentation(IMethodSymbol method) { switch (method.MethodKind) { case MethodKind.EventAdd: case MethodKind.EventRaise: case MethodKind.EventRemove: case MethodKind.PropertyGet: case MethodKind.PropertySet: return method.ContainingSymbol.GetDocumentationComment().SummaryText; default: return method.GetDocumentationComment().SummaryText; } } public static IList<SymbolDisplayPart> ToAwaitableParts(this ISymbol symbol, string awaitKeyword, string initializedVariableName, SemanticModel semanticModel, int position) { var spacePart = new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, " "); var parts = new List<SymbolDisplayPart>(); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, $"\r\n{WorkspacesResources.Usage_colon}\r\n ")); var returnType = symbol.InferAwaitableReturnType(semanticModel, position); returnType = returnType != null && returnType.SpecialType != SpecialType.System_Void ? returnType : null; if (returnType != null) { if (semanticModel.Language == "C#") { parts.AddRange(returnType.ToMinimalDisplayParts(semanticModel, position)); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.LocalName, null, initializedVariableName)); } else { parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "Dim")); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.LocalName, null, initializedVariableName)); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "as")); parts.Add(spacePart); parts.AddRange(returnType.ToMinimalDisplayParts(semanticModel, position)); } parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "=")); parts.Add(spacePart); } parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, awaitKeyword)); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.MethodName, symbol, symbol.Name)); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "(")); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, symbol.GetParameters().Any() ? "..." : "")); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, ")")); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, semanticModel.Language == "C#" ? ";" : "")); return parts; } public static ITypeSymbol InferAwaitableReturnType(this ISymbol symbol, SemanticModel semanticModel, int position) { var methodSymbol = symbol as IMethodSymbol; if (methodSymbol == null) { return null; } var returnType = methodSymbol.ReturnType; if (returnType == null) { return null; } var potentialGetAwaiters = semanticModel.LookupSymbols(position, container: returnType, name: WellKnownMemberNames.GetAwaiter, includeReducedExtensionMethods: true); var getAwaiters = potentialGetAwaiters.OfType<IMethodSymbol>().Where(x => !x.Parameters.Any()); if (!getAwaiters.Any()) { return null; } var getResults = getAwaiters.SelectMany(g => semanticModel.LookupSymbols(position, container: g.ReturnType, name: WellKnownMemberNames.GetResult)); var getResult = getResults.OfType<IMethodSymbol>().FirstOrDefault(g => !g.IsStatic); if (getResult == null) { return null; } return getResult.ReturnType; } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Windows.Forms; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Xml; using Axiom.Core; using Axiom.MathLib; using Axiom.Graphics; using Multiverse.ToolBox; namespace Multiverse.Tools.WorldEditor { class DirectionalLight : IWorldObject, IObjectOrientation, IObjectDelete { protected WorldEditor app; protected Boundary parent; protected Vector3 lightDirection; protected ColorEx diffuse; protected ColorEx specular; protected WorldTreeNode parentNode; protected WorldTreeNode node; protected DisplayObject displayObject; protected string name; protected float azimuth; protected float zenith; protected float origAzimuth; protected float origZenith; protected bool inScene = false; protected List<ToolStripButton> buttonBar; protected Quaternion orientation; public DirectionalLight(WorldEditor worldEditor, Boundary parent, Vector3 lightDir, ColorEx diff, ColorEx spec) { this.app = worldEditor; this.parent = parent; this.lightDirection = lightDir; this.diffuse = diff; this.specular = spec; this.name = String.Format("{0}-{1}", this.parent.Name, "DirectionalLight"); } public DirectionalLight(WorldEditor worldEditor, Boundary parent, XmlReader r) { this.app = worldEditor; this.parent = parent; fromXml(r); } #region IObjectOrientation members protected void UpdateOrientation() { Quaternion azimuthRotation = Quaternion.FromAngleAxis(MathUtil.DegreesToRadians(azimuth), Vector3.UnitY); Quaternion zenithRotation = Quaternion.FromAngleAxis(MathUtil.DegreesToRadians(-zenith), Vector3.UnitX); Matrix3 lightMatrix = (azimuthRotation * zenithRotation).ToRotationMatrix(); // Compute "position" of light (actually just reverse direction) Vector3 relativeLightPos = lightMatrix * Vector3.UnitZ; relativeLightPos.Normalize(); this.lightDirection = -relativeLightPos; Quaternion displayZenithRotation = Quaternion.FromAngleAxis(MathUtil.DegreesToRadians(-Zenith + 90), Vector3.UnitX); this.orientation = (azimuthRotation * displayZenithRotation); if (inScene) { this.displayObject.SetOrientation(orientation); } } public void SetDirection(float lightAzimuth, float lightZenith) { this.azimuth = lightAzimuth; this.zenith = lightZenith; UpdateOrientation(); } [BrowsableAttribute(false)] public Quaternion Orientation { get { // XXX - This is wrong, will need to update it at some point return orientation; } } [BrowsableAttribute(false)] public float Azimuth { get { return azimuth; } set { azimuth = value; UpdateOrientation(); } } [BrowsableAttribute(false)] public float Zenith { get { return zenith; } set { zenith = value; UpdateOrientation(); } } #endregion //IOjectOrientation Members [BrowsableAttribute(false)] public float OrigAzimuth { get { return origAzimuth; } set { origAzimuth = value; } } [BrowsableAttribute(false)] public float OrigZenith { get { return origZenith; } set { origZenith = value; } } [BrowsableAttribute(false)] public Vector3 LightDir { get { return lightDirection; } set { lightDirection = value; } } [EditorAttribute(typeof(ColorValueUITypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Diffuse color of the light (click [...] to use the color picker dialog to select a color)."), CategoryAttribute("Color")] public ColorEx Diffuse { get { return diffuse; } set { diffuse = value; } } [EditorAttribute(typeof(ColorValueUITypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Specular color of the light (click [...] to use the color picker dialog to select a color)."), CategoryAttribute("Color")] public ColorEx Specular { get { return specular; } set { specular = value; } } [DescriptionAttribute("Name of this directional light."), CategoryAttribute("Miscellaneous"), BrowsableAttribute(true)] public string Name { get { return name; } set { name = value; } } #region IWorldObject Members public void AddToTree(WorldTreeNode parentNode) { this.parentNode = parentNode; // add the Fog node node = app.MakeTreeNode(this, "Directional Light"); parentNode.Nodes.Add(node); CommandMenuBuilder menuBuilder = new CommandMenuBuilder(); menuBuilder.Add("Copy Description", "", app.copyToClipboardMenuButton_Click); menuBuilder.Add("Help", "Directional_Light", app.HelpClickHandler); menuBuilder.Add("Delete", new DeleteObjectCommandFactory(app, parent, this), app.DefaultCommandClickHandler); node.ContextMenuStrip = menuBuilder.Menu; buttonBar = menuBuilder.ButtonBar; } public void Clone(IWorldContainer copyParent) { DirectionalLight clone = new DirectionalLight(app, copyParent as Boundary, lightDirection, diffuse, specular); clone.Azimuth = azimuth; clone.Zenith = zenith; copyParent.Add(clone); } [BrowsableAttribute(false)] public string ObjectAsString { get { string objString = String.Format("Name:{0}\r\n", ObjectType); objString += String.Format("\tSpecular:\r\n"); objString += String.Format("\t\tR={0}\r\n", Specular.r); objString += String.Format("\t\tG={0}\r\n", Specular.g); objString += String.Format("\t\tB={0}\r\n", Specular.b); objString += String.Format("\tDiffuse:\r\n"); objString += String.Format("\t\tR={0}\r\n", Diffuse.r); objString += String.Format("\t\tG={0}\r\n", Diffuse.g); objString += String.Format("\t\tB={0}\r\n", Diffuse.b); objString += "\r\n"; return objString; } } [BrowsableAttribute(false)] public bool WorldViewSelectable { get { return false; } set { // This property is not relevent for this object. } } public void UpdateScene(UpdateTypes type, UpdateHint hint) { } [BrowsableAttribute(false)] public bool IsGlobal { get { return false; } } [BrowsableAttribute(false)] public bool IsTopLevel { get { return false; } } [BrowsableAttribute(false)] public List<ToolStripButton> ButtonBar { get { return buttonBar; } } [BrowsableAttribute(false)] public DisplayObject Display { get { return null; } } public void RemoveFromTree() { if (node.IsSelected) { node.UnSelect(); } parentNode.Nodes.Remove(node); parentNode = null; node = null; } [BrowsableAttribute(false)] public bool AcceptObjectPlacement { get { return false; } set { //not implemented for this type of object } } public void AddToScene() { float x = parent.FocusLocation.x; float z = parent.FocusLocation.z; Vector3 location = new Vector3(x, app.GetTerrainHeight(x, z) + 2000, z); displayObject = new DisplayObject(String.Format("{0}-{1}", parent.Name, "DirectionalLight"), app,"DirectionalLight", app.Scene, (app.Assets.assetFromName(app.Config.DirectionalLightMeshName)).AssetName, location, new Vector3(1, 1, 1), this.Orientation, null); inScene = true; UpdateOrientation(); if (displayObject.Entity.Mesh.TriangleIntersector == null) displayObject.Entity.Mesh.CreateTriangleIntersector(); } public void RemoveFromScene() { app.GlobalDirectionalLight = null; if (displayObject != null) { displayObject.Dispose(); } displayObject = null; inScene = false; } public void CheckAssets() { CheckAsset(app.Assets.assetFromName(app.Config.DirectionalLightMeshName).AssetName); } protected void CheckAsset(string name) { if ((name != null) && (name != "")) { if (!app.CheckAssetFileExists(name)) { app.AddMissingAsset(name); } } } public void ToXml(System.Xml.XmlWriter w) { w.WriteStartElement("DirectionalLight"); w.WriteAttributeString("Azimuth", this.azimuth.ToString()); w.WriteAttributeString("Zenith", this.zenith.ToString()); w.WriteStartElement("Direction"); w.WriteAttributeString("x", this.lightDirection.x.ToString()); w.WriteAttributeString("y", this.lightDirection.y.ToString()); w.WriteAttributeString("z", this.lightDirection.z.ToString()); w.WriteEndElement(); // End Direction w.WriteStartElement("Diffuse"); w.WriteAttributeString("R", this.diffuse.r.ToString()); w.WriteAttributeString("G", this.diffuse.g.ToString()); w.WriteAttributeString("B", this.diffuse.b.ToString()); w.WriteEndElement(); // End diffuse w.WriteStartElement("Specular"); w.WriteAttributeString("R", this.specular.r.ToString()); w.WriteAttributeString("G", this.specular.g.ToString()); w.WriteAttributeString("B", this.specular.b.ToString()); w.WriteEndElement(); // End Specular w.WriteEndElement(); // End GlobalAmbientLight } private void parseOrientation(XmlReader r) { for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); // set the field in this object based on the element we just read switch (r.Name) { case "Azimuth": azimuth = float.Parse(r.Value); break; case "Zenith": zenith = float.Parse(r.Value); break; } } } private void fromXml(XmlReader r) { // Parse sub-elements parseOrientation(r); while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } // look for the start of an element if (r.NodeType == XmlNodeType.Element) { // parse that element // save the name of the element string elementName = r.Name; switch (elementName) { case "Direction": this.lightDirection = XmlHelperClass.ParseVectorAttributes(r); break; case "Diffuse": diffuse = XmlHelperClass.ParseColorAttributes(r); break; case "Specular": specular = XmlHelperClass.ParseColorAttributes(r); break; } } else if (r.NodeType == XmlNodeType.EndElement) { break; } } } [BrowsableAttribute(false)] public Vector3 FocusLocation { get { return parent.FocusLocation; } } [DescriptionAttribute("The type of this object."), CategoryAttribute("Miscellaneous")] public string ObjectType { get { return "DirectionalLight"; } } [BrowsableAttribute(false)] public bool Highlight { get { return displayObject.Highlight; } set { displayObject.Highlight = value; } } [BrowsableAttribute(false)] public WorldTreeNode Node { get { return node; } set { node = value; } } #endregion #region IDisposable Members public void Dispose() { throw new Exception("The method or operation is not implemented."); } #endregion #region IWorldObject Members public void ToManifest(System.IO.StreamWriter w) { } #region IWorldDelete [BrowsableAttribute(false)] public IWorldContainer Parent { get { return parent; } } #endregion IWorldDelete #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.Security; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime { // This is a set of stub methods implementing the support for the IVector`1 interface on managed // objects that implement IList`1. Used by the interop mashaling infrastructure. // // The methods on this class must be written VERY carefully to avoid introducing security holes. // That's because they are invoked with special "this"! The "this" object // for all of these methods are not ListToVectorAdapter objects. Rather, they are of type // IList<T>. No actual ListToVectorAdapter object is ever instantiated. Thus, you will // see a lot of expressions that cast "this" to "IList<T>". internal sealed class ListToVectorAdapter { private ListToVectorAdapter() { Debug.Assert(false, "This class is never instantiated"); } // T GetAt(uint index) internal T GetAt<T>(uint index) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); EnsureIndexInt32(index, _this.Count); try { return _this[(Int32)index]; } catch (ArgumentOutOfRangeException ex) { throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange"); } } // uint Size { get } internal uint Size<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); return (uint)_this.Count; } // IVectorView<T> GetView() internal IReadOnlyList<T> GetView<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); Debug.Assert(_this != null); // Note: This list is not really read-only - you could QI for a modifiable // list. We gain some perf by doing this. We believe this is acceptable. IReadOnlyList<T> roList = _this as IReadOnlyList<T>; if (roList == null) { roList = new ReadOnlyCollection<T>(_this); } return roList; } // bool IndexOf(T value, out uint index) internal bool IndexOf<T>(T value, out uint index) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); int ind = _this.IndexOf(value); if (-1 == ind) { index = 0; return false; } index = (uint)ind; return true; } // void SetAt(uint index, T value) internal void SetAt<T>(uint index, T value) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); EnsureIndexInt32(index, _this.Count); try { _this[(int)index] = value; } catch (ArgumentOutOfRangeException ex) { throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange"); } } // void InsertAt(uint index, T value) internal void InsertAt<T>(uint index, T value) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); // Inserting at an index one past the end of the list is equivalent to appending // so we need to ensure that we're within (0, count + 1). EnsureIndexInt32(index, _this.Count + 1); try { _this.Insert((int)index, value); } catch (ArgumentOutOfRangeException ex) { // Change error code to match what WinRT expects ex.SetErrorCode(HResults.E_BOUNDS); throw; } } // void RemoveAt(uint index) internal void RemoveAt<T>(uint index) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); EnsureIndexInt32(index, _this.Count); try { _this.RemoveAt((Int32)index); } catch (ArgumentOutOfRangeException ex) { // Change error code to match what WinRT expects ex.SetErrorCode(HResults.E_BOUNDS); throw; } } // void Append(T value) internal void Append<T>(T value) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); _this.Add(value); } // void RemoveAtEnd() internal void RemoveAtEnd<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); if (_this.Count == 0) { Exception e = new InvalidOperationException(SR.InvalidOperation_CannotRemoveLastFromEmptyCollection); e.SetErrorCode(HResults.E_BOUNDS); throw e; } uint size = (uint)_this.Count; RemoveAt<T>(size - 1); } // void Clear() internal void Clear<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); _this.Clear(); } // uint GetMany(uint startIndex, T[] items) internal uint GetMany<T>(uint startIndex, T[] items) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); return GetManyHelper<T>(_this, startIndex, items); } // void ReplaceAll(T[] items) internal void ReplaceAll<T>(T[] items) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); _this.Clear(); if (items != null) { foreach (T item in items) { _this.Add(item); } } } // Helpers: private static void EnsureIndexInt32(uint index, int listCapacity) { // We use '<=' and not '<' becasue Int32.MaxValue == index would imply // that Size > Int32.MaxValue: if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity) { Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue); e.SetErrorCode(HResults.E_BOUNDS); throw e; } } private static uint GetManyHelper<T>(IList<T> sourceList, uint startIndex, T[] items) { // Calling GetMany with a start index equal to the size of the list should always // return 0 elements, regardless of the input item size if (startIndex == sourceList.Count) { return 0; } EnsureIndexInt32(startIndex, sourceList.Count); if (items == null) { return 0; } uint itemCount = Math.Min((uint)items.Length, (uint)sourceList.Count - startIndex); for (uint i = 0; i < itemCount; ++i) { items[i] = sourceList[(int)(i + startIndex)]; } if (typeof(T) == typeof(string)) { string[] stringItems = items as string[]; // Fill in rest of the array with String.Empty to avoid marshaling failure for (uint i = itemCount; i < items.Length; ++i) stringItems[i] = String.Empty; } return itemCount; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Management.RemoteApp; using Microsoft.WindowsAzure.Management.RemoteApp.Models; namespace Microsoft.WindowsAzure.Management.RemoteApp { /// <summary> /// RmoteApp management client /// </summary> public static partial class PublishingOperationsExtensions { /// <summary> /// Gets the details of a published application with given alias (short /// unique name) from the collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <param name='alias'> /// Required. Alias of published application /// </param> /// <returns> /// Definition for result of GetPublishedApplication operation. /// </returns> public static GetPublishedApplicationResult Get(this IPublishingOperations operations, string collectionName, string alias) { return Task.Factory.StartNew((object s) => { return ((IPublishingOperations)s).GetAsync(collectionName, alias); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the details of a published application with given alias (short /// unique name) from the collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <param name='alias'> /// Required. Alias of published application /// </param> /// <returns> /// Definition for result of GetPublishedApplication operation. /// </returns> public static Task<GetPublishedApplicationResult> GetAsync(this IPublishingOperations operations, string collectionName, string alias) { return operations.GetAsync(collectionName, alias, CancellationToken.None); } /// <summary> /// Gets the list of details for all published applications from the /// collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <returns> /// Definition for result of GetPublishedApplicationList operation. /// </returns> public static GetPublishedApplicationListResult List(this IPublishingOperations operations, string collectionName) { return Task.Factory.StartNew((object s) => { return ((IPublishingOperations)s).ListAsync(collectionName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of details for all published applications from the /// collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <returns> /// Definition for result of GetPublishedApplicationList operation. /// </returns> public static Task<GetPublishedApplicationListResult> ListAsync(this IPublishingOperations operations, string collectionName) { return operations.ListAsync(collectionName, CancellationToken.None); } /// <summary> /// Sets a published application matching the given alias (short unique /// name) in the collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <param name='alias'> /// Required. Alias of published application /// </param> /// <param name='applicationDetails'> /// Required. New details for the application /// </param> /// <returns> /// Definition for result of ModifyApplicaton operation. /// </returns> public static ModifyApplicationResult ModifyApplication(this IPublishingOperations operations, string collectionName, string alias, ApplicationDetailsParameter applicationDetails) { return Task.Factory.StartNew((object s) => { return ((IPublishingOperations)s).ModifyApplicationAsync(collectionName, alias, applicationDetails); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Sets a published application matching the given alias (short unique /// name) in the collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <param name='alias'> /// Required. Alias of published application /// </param> /// <param name='applicationDetails'> /// Required. New details for the application /// </param> /// <returns> /// Definition for result of ModifyApplicaton operation. /// </returns> public static Task<ModifyApplicationResult> ModifyApplicationAsync(this IPublishingOperations operations, string collectionName, string alias, ApplicationDetailsParameter applicationDetails) { return operations.ModifyApplicationAsync(collectionName, alias, applicationDetails, CancellationToken.None); } /// <summary> /// Publishes remote applications with given application details in the /// collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <param name='applicationDetailsList'> /// Required. List of publishing details /// </param> /// <returns> /// Definition for result of PublishApplications operation. /// </returns> public static PublishApplicationsResult PublishApplications(this IPublishingOperations operations, string collectionName, ApplicationDetailsListParameter applicationDetailsList) { return Task.Factory.StartNew((object s) => { return ((IPublishingOperations)s).PublishApplicationsAsync(collectionName, applicationDetailsList); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Publishes remote applications with given application details in the /// collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <param name='applicationDetailsList'> /// Required. List of publishing details /// </param> /// <returns> /// Definition for result of PublishApplications operation. /// </returns> public static Task<PublishApplicationsResult> PublishApplicationsAsync(this IPublishingOperations operations, string collectionName, ApplicationDetailsListParameter applicationDetailsList) { return operations.PublishApplicationsAsync(collectionName, applicationDetailsList, CancellationToken.None); } /// <summary> /// Gets a start menu application details for the given id from the /// collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <param name='applicationId'> /// Required. Start menu application Id /// </param> /// <returns> /// Definition for result of GetStartMenuApplication operation. /// </returns> public static GetStartMenuApplicationResult StartMenuApplication(this IPublishingOperations operations, string collectionName, string applicationId) { return Task.Factory.StartNew((object s) => { return ((IPublishingOperations)s).StartMenuApplicationAsync(collectionName, applicationId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a start menu application details for the given id from the /// collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <param name='applicationId'> /// Required. Start menu application Id /// </param> /// <returns> /// Definition for result of GetStartMenuApplication operation. /// </returns> public static Task<GetStartMenuApplicationResult> StartMenuApplicationAsync(this IPublishingOperations operations, string collectionName, string applicationId) { return operations.StartMenuApplicationAsync(collectionName, applicationId, CancellationToken.None); } /// <summary> /// Gets the list of all start menu applications from the collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <returns> /// Definition for result of GetStartMenuApplicationList operation. /// </returns> public static GetStartMenuApplicationListResult StartMenuApplicationList(this IPublishingOperations operations, string collectionName) { return Task.Factory.StartNew((object s) => { return ((IPublishingOperations)s).StartMenuApplicationListAsync(collectionName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of all start menu applications from the collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <returns> /// Definition for result of GetStartMenuApplicationList operation. /// </returns> public static Task<GetStartMenuApplicationListResult> StartMenuApplicationListAsync(this IPublishingOperations operations, string collectionName) { return operations.StartMenuApplicationListAsync(collectionName, CancellationToken.None); } /// <summary> /// Unpublishes published applications matching the given list of /// application aliases (short unique names) from the collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <param name='aliasesList'> /// Required. List of application aliases to be unpublished /// </param> /// <returns> /// Definition for result of UnpublishApplications operation. /// </returns> public static UnpublishApplicationsResult Unpublish(this IPublishingOperations operations, string collectionName, AliasesListParameter aliasesList) { return Task.Factory.StartNew((object s) => { return ((IPublishingOperations)s).UnpublishAsync(collectionName, aliasesList); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unpublishes published applications matching the given list of /// application aliases (short unique names) from the collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <param name='aliasesList'> /// Required. List of application aliases to be unpublished /// </param> /// <returns> /// Definition for result of UnpublishApplications operation. /// </returns> public static Task<UnpublishApplicationsResult> UnpublishAsync(this IPublishingOperations operations, string collectionName, AliasesListParameter aliasesList) { return operations.UnpublishAsync(collectionName, aliasesList, CancellationToken.None); } /// <summary> /// Unpublishes all published applications from the collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <returns> /// Definition for result of UnpublishApplications operation. /// </returns> public static UnpublishApplicationsResult UnpublishAll(this IPublishingOperations operations, string collectionName) { return Task.Factory.StartNew((object s) => { return ((IPublishingOperations)s).UnpublishAllAsync(collectionName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unpublishes all published applications from the collection. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.RemoteApp.IPublishingOperations. /// </param> /// <param name='collectionName'> /// Required. Collection Name /// </param> /// <returns> /// Definition for result of UnpublishApplications operation. /// </returns> public static Task<UnpublishApplicationsResult> UnpublishAllAsync(this IPublishingOperations operations, string collectionName) { return operations.UnpublishAllAsync(collectionName, CancellationToken.None); } } }
#region File Description //----------------------------------------------------------------------------- // Animation.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region File Information //----------------------------------------------------------------------------- // Animation.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace HoneycombRush { /// <summary> /// Supports animation playback. /// </summary> public class Animation { #region Fields Texture2D animatedCharacter; Point sheetSize; public Point currentFrame; public Point frameSize; private TimeSpan lastestChangeTime; private TimeSpan timeInterval = TimeSpan.Zero; private int startFrame; private int endFrame; private int lastSubFrame = -1; bool drawWasAlreadyCalledOnce = false; public int FrameCount { get { return sheetSize.X * sheetSize.Y; } } public Vector2 Offset { get; set; } public int FrameIndex { get { return sheetSize.X * currentFrame.Y + currentFrame.X; } set { if (value >= sheetSize.X * sheetSize.Y + 1) { throw new InvalidOperationException("Specified frame index exceeds available frames"); } currentFrame.Y = value / sheetSize.X; currentFrame.X = value % sheetSize.X; } } public bool IsActive { get; private set; } #endregion #region Initialization /// <summary> /// Creates a new instance of the animation class /// </summary> /// <param name="frameSheet">Texture which is a sheet containing /// the animation frames.</param> /// <param name="size">The size of a single frame.</param> /// <param name="frameSheetSize">The size of the entire animation sheet.</param> public Animation(Texture2D frameSheet, Point size, Point frameSheetSize) { animatedCharacter = frameSheet; frameSize = size; sheetSize = frameSheetSize; Offset = Vector2.Zero; } #endregion #region Update and Render /// <summary> /// Updates the animation's progress. /// </summary> /// <param name="gameTime">Game time information.</param> /// <param name="isInMotion">Whether or not the animation element itself is /// currently in motion.</param> public void Update(GameTime gameTime, bool isInMotion) { Update(gameTime, isInMotion, false); } /// <summary> /// Updates the animation's progress. /// </summary> /// <param name="gameTime">Game time information.</param> /// <param name="isInMotion">Whether or not the animation element itself is /// currently in motion.</param> /// <param name="runSubAnimation"></param> public void Update(GameTime gameTime, bool isInMotion, bool runSubAnimation) { if (IsActive && gameTime.TotalGameTime != lastestChangeTime) { // See if a time interval between frames is defined if (timeInterval != TimeSpan.Zero) { // Do nothing until an interval passes if (lastestChangeTime + timeInterval > gameTime.TotalGameTime) { return; } } lastestChangeTime = gameTime.TotalGameTime; if (FrameIndex >= FrameCount) { FrameIndex = 0; // Reset the animation } else { // Only advance the animation if the animation element is moving if (isInMotion) { if (runSubAnimation) { // Initialize the animation if (lastSubFrame == -1) { lastSubFrame = startFrame; } // Calculate the currentFrame, which depends on the current // frame in the parent animation currentFrame.Y = lastSubFrame / sheetSize.X; currentFrame.X = lastSubFrame % sheetSize.X; // Move to the next Frame lastSubFrame += 1; // Loop the animation if (lastSubFrame > endFrame) { lastSubFrame = startFrame; } } else { // Do not advance frames before the first draw operation if (drawWasAlreadyCalledOnce) { currentFrame.X++; if (currentFrame.X >= sheetSize.X) { currentFrame.X = 0; currentFrame.Y++; } if (currentFrame.Y >= sheetSize.Y) currentFrame.Y = 0; if (lastSubFrame != -1) { lastSubFrame = -1; } } } } } } } /// <summary> /// Render the animation. /// </summary> /// <param name="spriteBatch">SpriteBatch with which the current /// frame will be rendered.</param> /// <param name="position">The position to draw the current frame.</param> /// <param name="spriteEffect">SpriteEffect to apply to the /// current frame.</param> public void Draw(SpriteBatch spriteBatch, Vector2 position, SpriteEffects spriteEffect) { Draw(spriteBatch, position, 1.0f, spriteEffect); } /// <summary> /// Render the animation. /// </summary> /// <param name="spriteBatch">SpriteBatch with which the current frame /// will be rendered.</param> /// <param name="position">The position to draw the current frame.</param> /// <param name="scale">Scale factor to apply to the current frame.</param> /// <param name="spriteEffect">SpriteEffect to apply to the /// current frame.</param> public void Draw(SpriteBatch spriteBatch, Vector2 position, float scale, SpriteEffects spriteEffect) { drawWasAlreadyCalledOnce = true; spriteBatch.Draw(animatedCharacter, position + Offset, new Rectangle(frameSize.X * currentFrame.X, frameSize.Y * currentFrame.Y, frameSize.X, frameSize.Y), Color.White, 0f, Vector2.Zero, scale, spriteEffect, 0); } /// <summary> /// Causes the animation to start playing from a specified frame index. /// </summary> /// <param name="frameIndex">Frame index to play the animation from.</param> public void PlayFromFrameIndex(int frameIndex) { FrameIndex = frameIndex; IsActive = true; drawWasAlreadyCalledOnce = false; } /// <summary> /// Sets the range of frames which serves as the sub animation. /// </summary> /// <param name="startFrame">Start frame for the sub-animation.</param> /// <param name="endFrame">End frame for the sub-animation.</param> public void SetSubAnimation(int startFrame, int endFrame) { this.startFrame = startFrame; this.endFrame = endFrame; } /// <summary> /// Used to set the interval between frames. /// </summary> /// <param name="interval">The interval between frames.</param> public void SetFrameInvterval(TimeSpan interval) { timeInterval = interval; } #endregion } }
using MVC.Data; using MVC.Models; using MVC.Models.AdminViewModels; using MVC.Models.SettingsModels; using MVC.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Routing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace MVC.Controllers { [Authorize(Roles = "AdminRole, LogViewRole, ManagerRole")] public class AdminController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly RoleManager<ApplicationRole> _roleManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly IUtilityService _utilityService; private readonly Settings _settings; private readonly LogDbContext _logcontext; public AdminController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, RoleManager<ApplicationRole> roleManager, IEmailSender emailSender, ISmsSender smsSender, IUtilityService utilityService, IOptionsSnapshot<Settings> settings, LogDbContext logcontext) { _userManager = userManager; _signInManager = signInManager; _roleManager = roleManager; _emailSender = emailSender; _smsSender = smsSender; _utilityService = utilityService; _settings = settings.Value; _logcontext = logcontext; } // // GET: /Admin/Index [HttpGet] [Authorize(Roles = "AdminRole, ManagerRole")] public async Task<IActionResult> Index() { _utilityService.SetViewCookie(HttpContext, "Admin Index View", "AdminIndexView", LogType.Information); // for testing //await _smsSender.SendSmsAsync("+19876543210", "Test of Asp.Net Core Twilio."); //await _emailSender.SendEmailAsync("You@YourDomain.Com", "Test Email.", "Test of Asp.Net Core Email."); var user = await GetCurrentUserAsync(); if (user == null) { ModelState.AddModelError("", "The current user was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin Error", "Admin Index current user was not found.", LogType.Error, true); return View(); } try { var hostName = Dns.GetHostName(); var hostIPs = await Dns.GetHostAddressesAsync(hostName); var sb = new StringBuilder("Server: HostName = " + hostName + ", DNS Host IPs = "); foreach (var ip in hostIPs) { sb.Append(ip + ", "); } ViewBag.ServerHost = sb.ToString(); } catch (Exception ex) { ViewBag.ServerHost = "DNS exception = " + ex.Message; } ViewBag.RemoteIP = "RemoteIP = " + HttpContext.Request.HttpContext.Connection.RemoteIpAddress.ToString(); ViewBag.Version = $"Version {Assembly.GetEntryAssembly().GetName().Version.ToString()}"; ViewBag.Description = "Admin - Index description."; var users = _userManager.Users; var ul = new List<UserViewModel>(); foreach (ApplicationUser u in users) { var uroles = await _userManager.GetRolesAsync(u); var list = uroles.OrderBy(q => q).ToList(); var userModel = new UserViewModel(u, list); ul.Add(userModel); } return View(ul); } // // GET: /Admin/LogEntries [HttpGet] [Authorize(Roles = "AdminRole, LogViewRole")] public async Task<ActionResult> LogEntries(int? Page, string Start = "", string End = "", LogType Type = LogType.All, string Country = "Recent Countries") { _utilityService.SetViewCookie(HttpContext, "Log Entries View", "LogEntriesView", LogType.Information); var tzoffset = 0; if (Request.Cookies != null && Request.Cookies.Count > 0) { if (Request.Cookies["tzoffset"] != null) { tzoffset = Int32.Parse(Request.Cookies["tzoffset"]); } } DateTime startdate; DateTime enddate; if (Start.Length == 0 || !IsDatePicker(Start)) { startdate = DateTime.UtcNow; var smin = startdate.Minute % 15; smin *= -1; startdate = startdate.AddDays(-7).AddMinutes(smin); Start = startdate.ToUniversalTime().ToString("yyyy-MM-dd HH:mm zzz"); } else { startdate = DateTime.ParseExact(Start, "yyyy-MM-dd HH:mm zzz", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime(); } if (End.Length == 0 || !IsDatePicker(End)) { enddate = DateTime.UtcNow; var emin = 15 - enddate.Minute % 15; // + 30; enddate = enddate.AddMinutes(emin); End = enddate.ToUniversalTime().ToString("yyyy-MM-dd HH:mm zzz"); } else { enddate = DateTime.ParseExact(End, "yyyy-MM-dd HH:mm zzz", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime(); } var itemsPerPage = 10; var pageNumber = Page ?? 1; var alltypes = Enum.GetValues(typeof(LogType)).Cast<LogType>().ToArray(); var typelist = from value in alltypes select new SelectListItem() { Value = ((int)value).ToString(), Text = value.ToString() }; var selectlist = new List<SelectListItem>(typelist); var v = new LogEntriesViewModel(); try { var entries = _logcontext.LogEntries.Where(e => e.CreateDate > startdate && e.CreateDate < enddate).AsQueryable(); if (Type != LogType.All) { entries = entries.Where(e => e.LogType == Type); } entries = entries.OrderByDescending(e => e.CreateDate).Take(1000).AsQueryable(); v.TZoffset = tzoffset; v.PageIndex = pageNumber; v.RowIndex = itemsPerPage * pageNumber - itemsPerPage + 1; var count = await entries.CountAsync(); v.EntryCount = count; v.TotalPages = (int)Math.Ceiling(count / (double)itemsPerPage); v.StartDate = Start; v.EndDate = End; v.Type = Type; v.Country = Country; v.Types = selectlist; v.Entries = await entries.AsNoTracking().Skip((pageNumber - 1) * itemsPerPage).Take(itemsPerPage).ToListAsync(); } catch (Exception ex) { _utilityService.InsertLogEntry(HttpContext, "LogDbContext Error", "LogEntries threw an exception.", LogType.Critical, true, ex); throw; } return View(v); } // // AJAX GET: /Admin/LogEntry // Called by AJAX must return JSON [HttpGet] [Authorize(Roles = "AdminRole, LogViewRole")] public JsonResult LogEntry(string id = "") { if (id != string.Empty) { try { var entry = _logcontext.LogEntries.Where(e => e.ID == id).FirstOrDefault(); return Json(entry); } catch (Exception ex) { _utilityService.InsertLogEntry(HttpContext, "LogDbContext Error", "LogEntry threw an exception.", LogType.Critical, true, ex); return Json(new { error = "LogDbContext Exception." }); } } else { _utilityService.InsertLogEntry(HttpContext, "LogEntry Error", "Id is empty.", LogType.Critical, true); return Json(new { error = "Id is empty." }); } } // // GET: /Admin/UserIndex [HttpGet] [Authorize(Roles = "AdminRole, ManagerRole")] public async Task<IActionResult> UserIndex() { _utilityService.SetViewCookie(HttpContext, "User Index View", "UserIndexView", LogType.Information); var user = await GetCurrentUserAsync(); if (user == null) { ModelState.AddModelError("", "The current user was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "UserIndex current user was not found.", LogType.Error, true); return View(); } var users = _userManager.Users; var ul = new List<UserViewModel>(); foreach (ApplicationUser u in users) { var uroles = await _userManager.GetRolesAsync(u); if (!(await _userManager.IsInRoleAsync(user, "AdminRole"))) { if (uroles.Contains("AdminRole")) { continue; } } var rolelist = uroles.OrderBy(q => q).ToList(); var userLogins = await _userManager.GetLoginsAsync(u); var exlogins = ""; foreach (UserLoginInfo el in userLogins) { exlogins += el.LoginProvider[0] + ","; } var userModel = new UserViewModel(u, rolelist, exlogins); if (u.LockoutEnabled == false || user == u) { userModel.CanDelete = false; } ul.Add(userModel); } return View(ul); } // // GET: /Admin/UserRoles [HttpGet] [Authorize(Roles = "AdminRole")] public async Task<IActionResult> UserRoles(string id = "") { _utilityService.SetViewCookie(HttpContext, "User Roles View", "UserRolesView", LogType.Information); if (string.IsNullOrEmpty(id) == true) { ModelState.AddModelError("", "The id is null or empty."); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "UserRoles id is null or empty.", LogType.Error, true); return View(); } var user = await _userManager.FindByNameAsync(id); if (user == null) { ModelState.AddModelError("", "The user was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "UserRoles user was not found.", LogType.Error, true); return View(); } var uroles = await _userManager.GetRolesAsync(user); //Add all available roles to the list of EditorViewModels: var allRoles = _roleManager.Roles.OrderBy(r => r.Name); var rolesView = new List<RoleViewModel>(); foreach (ApplicationRole r in allRoles) { var rvm = new RoleViewModel(r); if (uroles.Contains(r.Name)) { rvm.Selected = true; } rolesView.Add(rvm); } ViewBag.UserName = user.UserName; return View(rolesView); } // // POST: /Admin/SetUserRole [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = "AdminRole")] public async Task<IActionResult> SetUserRole(string id, string role) { if (string.IsNullOrEmpty(id) == true) { ModelState.AddModelError("", "The id is null or empty."); _utilityService.InsertLogEntry(HttpContext, "Admin User Role Error", "SetUserRole post id is null or empty.", LogType.Error, true); return View("UserRoles"); } var user = await _userManager.FindByNameAsync(id); if (user == null) { ModelState.AddModelError("", "The user was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin User Role Error", "SetUserRole post current user was not found.", LogType.Error, true); return View("UserRoles"); } string r = HttpContext.Request.Form[role]; if (r == null) { await _userManager.RemoveFromRoleAsync(user, role); _utilityService.InsertLogEntry(HttpContext, "Remove From Role", "The user " + user + " was removed from " + role + ".", LogType.Information); } else { await _userManager.AddToRoleAsync(user, role); _utilityService.InsertLogEntry(HttpContext, "Add To Role", "The user " + user + " was added to " + role + ".", LogType.Information); } return RedirectToAction("UserRoles", "Admin", new RouteValueDictionary(new { id = id })); } // // GET: Admin/NewUser [HttpGet] [Authorize(Roles = "AdminRole, ManagerRole")] public IActionResult NewUser() { _utilityService.SetViewCookie(HttpContext, "New User View", "NewUserView", LogType.Information); return View(); } // // POST: Admin/NewUser [HttpPost] [Authorize(Roles = "AdminRole, ManagerRole")] [ValidateAntiForgeryToken] public async Task<IActionResult> NewUser([Bind("UserName,Email,EmailConfirmed,PhoneNumber,TwoFactorEnabled," + "Password,MustChangePassword,SendEmail")] CreateUserViewModel model) { if (!ModelState.IsValid) { _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "NewUser post model state is invalid.", LogType.Error, true); return View(model); } if (ModelState.IsValid) { var phoneNumberConfirmed = false; if (string.IsNullOrEmpty(model.PhoneNumber) || model.PhoneNumber.Length < 8) { model.PhoneNumber = null; } else { phoneNumberConfirmed = true; } var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, EmailConfirmed = model.EmailConfirmed, PhoneNumber = model.PhoneNumber, PhoneNumberConfirmed = phoneNumberConfirmed, MustChangePassword = model.MustChangePassword }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { if (model.SendEmail) { if (!user.EmailConfirmed) { var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); var sb = new StringBuilder("<html><body><div style='font-weight: bold; font-size: 24pt; font-family: Tahoma;'>Email" + " Verification for " + _settings.Name); sb.Append("</div><br/><div style='font-weight: normal; font-size: 14pt; font-family: Tahoma;'>"); sb.Append("Your administrator created a new user for this email address.<br/><br/>"); sb.Append("Your Login Name:&nbsp;"); sb.Append(user.UserName); sb.Append("<br/>Your Password:&nbsp;"); sb.Append(model.Password); sb.Append("<br/><br/>Please click <a href='"); sb.Append(callbackUrl); sb.Append("'>here</a> to verify your email.<br/> You must verify your email before you log in to " + _settings.Name + ".<br/><br/>If you have any problem, please let me know.<br/>"); sb.Append("Email <a href='mailto:" + _settings.SupportEmail + "?subject=Verify Email'>" + _settings.SupportEmail + "</a><br/><br/>Thank you,<br/>" + _settings.SupportName + "<br/><br/>"); sb.Append("THIS IS AN AUTOMATED MESSAGE.</div></body></html>"); //await _emailSender.SendEmailAsync(model.Email, "Email Verification for " + _settings.Name, sb.ToString()); await Task.Run(() => { Task.Delay(500); }); _utilityService.InsertLogEntry(HttpContext, "Email Confirmation Sent", user.UserName + " was sent the confirmation" + " email.", LogType.Information); } else { var callbackUrl = Url.Action("Login", "Account", null, protocol: HttpContext.Request.Scheme); var sb = new StringBuilder("<html><body><div style='font-weight: bold; font-size: 24pt; font-family: Tahoma;'>Welcome to " + _settings.Name); sb.Append("</div><br/><div style='font-weight: normal; font-size: 14pt; font-family: Tahoma;'>"); sb.Append("Your administrator created a new user for this email address.<br/><br/>"); sb.Append("Your Login Name:&nbsp;"); sb.Append(user.UserName); sb.Append("<br/>Your Password:&nbsp;"); sb.Append(model.Password); if (model.MustChangePassword) { sb.Append("<br/>You must change your password at first login."); } sb.Append("<br/><br/>Please click <a href='"); sb.Append(callbackUrl); sb.Append("'>here</a> to login.<br/><br/>If you have any problem, please let me know.<br/>"); sb.Append("Email <a href='mailto:" + _settings.SupportEmail + "?subject=Welcome Email'>" + _settings.SupportEmail + "</a><br/><br/>Thank you,<br/>" + _settings.SupportName + "<br/><br/>"); sb.Append("THIS IS AN AUTOMATED MESSAGE.</div></body></html>"); //await _emailSender.SendEmailAsync(model.Email, "Welcome to " + _settings.Name, sb.ToString()); await Task.Run(() => { Task.Delay(500); }); _utilityService.InsertLogEntry(HttpContext, "Email Welcome Sent", user.UserName + " was sent the welcome email.", LogType.Information); } } _utilityService.InsertLogEntry(HttpContext, "Admin User Added", "Admin created a new account with password.", LogType.Information); return RedirectToAction("UserIndex"); } var err = AddErrors(result); _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "NewUser post result = " + err, LogType.Error, true); } return View(); } // // GET: Admin/EditUser [HttpGet] [Authorize(Roles = "AdminRole, ManagerRole")] public async Task<IActionResult> EditUser(string id = "") { _utilityService.SetViewCookie(HttpContext, "Edit User View", "EditUserView", LogType.Information); if (string.IsNullOrEmpty(id) == true) { ModelState.AddModelError("", "The id is null or empty."); _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "EditUser id is null or empty.", LogType.Error, true); return View(); } var user = await _userManager.FindByNameAsync(id); if (user == null) { ModelState.AddModelError("", "The user was not found."); _utilityService.InsertLogEntry(HttpContext, "EditUser Error", "EditUser user was not found.", LogType.Error, true); return View(); } var roles = await _userManager.GetRolesAsync(user); roles = roles.OrderBy(q => q).ToList(); var rstring = roles.Count > 0 ? string.Join(", ", roles) : "None"; var userLogins = await _userManager.GetLoginsAsync(user); var sb = new StringBuilder(); foreach (UserLoginInfo el in userLogins) { sb.Append(el.LoginProvider[0] + ", "); } if (userLogins.Count > 0) { sb.Length = sb.Length - 2; } var usermodel = new EditUserViewModel(user, rstring, sb.ToString()); return View(usermodel); } // // POST: Admin/EditUser [HttpPost] [Authorize(Roles = "AdminRole, ManagerRole")] [ValidateAntiForgeryToken] public async Task<IActionResult> EditUser(EditUserViewModel model) { if (!ModelState.IsValid) { _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "EditUser post model state is invalid.", LogType.Error, true); return View(model); } if (ModelState.IsValid) { var phoneNumberConfirmed = false; if (string.IsNullOrEmpty(model.PhoneNumber) || model.PhoneNumber.Length < 8) { model.PhoneNumber = null; } else { phoneNumberConfirmed = true; } var user = await _userManager.FindByNameAsync(model.UserName); if (user == null) { ModelState.AddModelError("", "The user was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "EditUser post user was not found.", LogType.Error, true); return View(model); } if (model.Password != null) { var token = await _userManager.GeneratePasswordResetTokenAsync(user); var resetresult = await _userManager.ResetPasswordAsync(user, token, model.Password); if (!resetresult.Succeeded) { var err = AddErrors(resetresult); _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "EditUser post result = " + err, LogType.Error, true); return View(model); } } user.Email = model.Email; user.EmailConfirmed = model.EmailConfirmed; user.PhoneNumber = model.PhoneNumber; user.PhoneNumberConfirmed = phoneNumberConfirmed; user.TwoFactorEnabled = model.TwoFactorEnabled; user.MustChangePassword = model.MustChangePassword; var result = await _userManager.UpdateAsync(user); if (!result.Succeeded) { var err = AddErrors(result); _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "EditUser post result = " + err, LogType.Error, true); return View(model); } else { _utilityService.InsertLogEntry(HttpContext, "Admin User Updated", user.UserName + " was updated by admin.", LogType.Information); } return RedirectToAction("UserIndex"); } return View(); } // // GET: Admin/DeleteUser [HttpGet] [Authorize(Roles = "AdminRole")] public async Task<IActionResult> DeleteUser(string id = "") { _utilityService.SetViewCookie(HttpContext, "Delete User View", "DeleteUserView", LogType.Information); if (string.IsNullOrEmpty(id) == true) { ModelState.AddModelError("", "The id is null or empty."); _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "DeleteUser id is null or empty.", LogType.Error, true); return View(); } var user = await _userManager.FindByNameAsync(id); if (user == null) { ModelState.AddModelError("", "The user was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "DeleteUser user was not found.", LogType.Error, true); return View(); } var uroles = await _userManager.GetRolesAsync(user); var list = uroles.OrderBy(q => q).ToList(); var model = new UserViewModel(user, list); return View(model); } // // POST: Admin/DeleteUser [HttpPost] [Authorize(Roles = "AdminRole")] [ActionName("DeleteUser")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteUserConfirmed(string id = "") { if (string.IsNullOrEmpty(id) == true) { ModelState.AddModelError("", "The id is null or empty."); _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "DeleteUserConfirmed post id is null or empty.", LogType.Error, true); return View(); } var user = await _userManager.FindByNameAsync(id); if (user == null) { ModelState.AddModelError("", "The user was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "DeleteUserConfirmed post user was not found.", LogType.Error, true); return View(); } var result = await _userManager.DeleteAsync(user); if (!result.Succeeded) { var err = AddErrors(result); _utilityService.InsertLogEntry(HttpContext, "Admin User Error", "DeleteUserConfirmed post result = " + err, LogType.Error, true); return View(); } else { _utilityService.InsertLogEntry(HttpContext, "Admin User Deleted", user.UserName + " was deleted by admin.", LogType.Information); } return RedirectToAction("UserIndex"); } // // GET: /Admin/RoleIndex [HttpGet] [Authorize(Roles = "AdminRole")] public async Task<IActionResult> RoleIndex() { _utilityService.SetViewCookie(HttpContext, "Role Index View", "RoleIndexView", LogType.Information); var user = await GetCurrentUserAsync(); if (user == null) { ModelState.AddModelError("", "The current user was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "RoleIndex current user was not found.", LogType.Error, true); return View(); } var roles = await _userManager.GetRolesAsync(user); var list = roles.OrderBy(q => q).ToList(); var rs = string.Empty; foreach (var r in list) { rs += r + ','; } var rolesList = new List<RoleViewModel>(); var allroles = _roleManager.Roles.OrderBy(r => r.Name); foreach (ApplicationRole r in allroles) { var roleModel = new RoleViewModel(r); rolesList.Add(roleModel); } return View(rolesList); } // // GET: Admin/NewRole [HttpGet] [Authorize(Roles = "AdminRole")] public IActionResult NewRole() { _utilityService.SetViewCookie(HttpContext, "New Role View", "NewRoleView", LogType.Information); return View(); } // // POST: Admin/NewRole [HttpPost] [Authorize(Roles = "AdminRole")] [ValidateAntiForgeryToken] public async Task<IActionResult> NewRole([Bind("Name,Description")] RoleViewModel model) { if (!ModelState.IsValid) { _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "NewRole post model state is invalid.", LogType.Error, true); return View(model); } if (ModelState.IsValid) { if (await _roleManager.RoleExistsAsync(model.Name)) { ModelState.AddModelError("", "The role name " + model.Name + " has already been used."); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "NewRole post role name " + model.Name + " has already been used.", LogType.Error, true); return View(model); } else { var roleResult = await _roleManager.CreateAsync(new ApplicationRole(model.Name, model.Description)); if (!roleResult.Succeeded) { var err = AddErrors(roleResult); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "NewRole post result = " + err, LogType.Error, true); return View(model); } else { _utilityService.InsertLogEntry(HttpContext, "Admin Role Added", model.Name + " was added by admin.", LogType.Information); } return RedirectToAction("RoleIndex"); } } return View(); } // // GET: Admin/EditRole [HttpGet] [Authorize(Roles = "AdminRole")] public async Task<IActionResult> EditRole(string id = "") { _utilityService.SetViewCookie(HttpContext, "Edit Role View", "EditRoleView", LogType.Information); if (string.IsNullOrEmpty(id) == true) { ModelState.AddModelError("", "The id is null or empty."); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "EditRole id is null or empty.", LogType.Error, true); return View(); } var role = await _roleManager.FindByNameAsync(id); if (role == null) { ModelState.AddModelError("", "The role was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "EditRole role was not found.", LogType.Error, true); return View(); } var rolemodel = new RoleViewModel(role); return View(rolemodel); } // // POST: Admin/EditRole [HttpPost] [Authorize(Roles = "AdminRole")] [ValidateAntiForgeryToken] public async Task<IActionResult> EditRole(RoleViewModel model) { if (!ModelState.IsValid) { _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "EditRole post model state is invalid.", LogType.Error, true); return View(model); } if (ModelState.IsValid) { var role = await _roleManager.FindByNameAsync(model.Name); if (role == null) { ModelState.AddModelError("", "The role was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "EditRole post role was not found.", LogType.Error, true); return View(); } var roleResult = await _roleManager.UpdateAsync(role); if (!roleResult.Succeeded) { var err = AddErrors(roleResult); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "EditRole post result = " + err, LogType.Error, true); return View(model); } else { _utilityService.InsertLogEntry(HttpContext, "Admin Role Updated", model.Name + " was updated by admin.", LogType.Information); } return RedirectToAction("RoleIndex"); } return View(); } // // GET: Admin/DeleteRole [HttpGet] [Authorize(Roles = "AdminRole")] public async Task<IActionResult> DeleteRole(string id = "") { _utilityService.SetViewCookie(HttpContext, "Delete Role View", "DeleteRoleView", LogType.Information); if (string.IsNullOrEmpty(id) == true) { ModelState.AddModelError("", "The id is null or empty."); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "DeleteRole id is null or empty.", LogType.Error, true); return View(); } var role = await _roleManager.FindByNameAsync(id); if (role == null) { ModelState.AddModelError("", "The role was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "DeleteRole role was not found.", LogType.Error, true); return View(); } var model = new RoleViewModel(role); return View(model); } // // POST: Admin/DeleteRole [HttpPost] [Authorize(Roles = "AdminRole")] [ActionName("DeleteRole")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteRoleConfirmed(string id = "") { if (string.IsNullOrEmpty(id) == true) { ModelState.AddModelError("", "The id is null or empty."); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "DeleteRoleConfirmed post id is null or empty.", LogType.Error, true); return View(); } var role = await _roleManager.FindByNameAsync(id); if (role == null) { ModelState.AddModelError("", "The role was not found."); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "DeleteRoleConfirmed post role was not found.", LogType.Error, true); return View(); } var roleResult = await _roleManager.DeleteAsync(role); if (!roleResult.Succeeded) { var err = AddErrors(roleResult); _utilityService.InsertLogEntry(HttpContext, "Admin Role Error", "DeleteRoleConfirmed post result = " + err, LogType.Error, true); return View(); } else { _utilityService.InsertLogEntry(HttpContext, "Admin Role Deleted", id + " was deleted by admin.", LogType.Information); } return RedirectToAction("RoleIndex"); } #region Helpers private bool IsDatePicker(string dateString) { string utcformat = "yyyy-MM-dd HH:mm zzz"; if (DateTime.TryParseExact(dateString, utcformat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateTime)) { return true; } else { return false; } } private string AddErrors(IdentityResult result) { var sb = new StringBuilder(); foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); sb.Append(error.Description + ", "); } return sb.ToString(); } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } #endregion } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.IO; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal.Execution; namespace NUnit.Framework.Internal { [TestFixture] public class EventListenerTextWriterTests { private static readonly string STREAM_NAME = "EventListenerTextWriterTestsStream"; private static readonly string NL = Environment.NewLine; TestListenerIntercepter ListenerResult; TextWriter ListenerWriter; [SetUp] public void SetUp() { // Wrap the current listener, listening to events, and forwarding the original event ListenerResult = new TestListenerIntercepter(TestExecutionContext.CurrentContext.Listener); TestExecutionContext.CurrentContext.Listener = ListenerResult; #if NETCOREAPP1_1 ListenerWriter = new EventListenerTextWriter(STREAM_NAME, TextWriter.Null); #else ListenerWriter = TextWriter.Synchronized(new EventListenerTextWriter(STREAM_NAME, TextWriter.Null)); #endif } [TearDown] public void TearDown() { // Restore the original listener TestExecutionContext.CurrentContext.Listener = ListenerResult.DefaultListener; } [Test] public void TestWriteStringArgArray() { var format = "{0} {1} {2} {3}"; var arg = new object[] { "Hello", 4, 2, "World" }; ListenerWriter.Write(format, arg); ListenerWriter.WriteLine(format, arg); var expected = "Hello 4 2 World"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteStringArg1() { var format = "{0:dd MMM yyyy}"; var arg0 = new DateTime(2017, 4, 20); ListenerWriter.Write(format, arg0); ListenerWriter.WriteLine(format, arg0); var expected = $"{arg0:dd MMM yyyy}"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteStringArg2() { var format = "{0:00.00} {1}"; var arg0 = 5; var arg1 = "@"; ListenerWriter.Write(format, arg0, arg1); ListenerWriter.WriteLine(format, arg0, arg1); var expected = $"{5:00.00} @"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteStringArg3() { var format = "{0} {1:#.00} {2}"; var arg0 = "Quick"; var arg1 = 9.0; var arg2 = "Fox"; ListenerWriter.Write(format, arg0, arg1, arg2); ListenerWriter.WriteLine(format, arg0, arg1, arg2); var expected = $"Quick {9:#.00} Fox"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteObject() { var obj = new { Mary = "Lamb", Sheep = "White" }; ListenerWriter.Write(obj); ListenerWriter.WriteLine(obj); var expected = "{ Mary = Lamb, Sheep = White }"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteString() { var str = "Insert coin here"; ListenerWriter.Write(str); ListenerWriter.WriteLine(str); var expected = "Insert coin here"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteDecimal() { decimal value = 2.731m; ListenerWriter.Write(value); ListenerWriter.WriteLine(value); var expected = $"{2.731:0.000}"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteDouble() { double value = -1.5; ListenerWriter.Write(value); ListenerWriter.WriteLine(value); var expected = $"{-1.5:0.0}"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteULong() { ulong value = 1234567890123456; ListenerWriter.Write(value); ListenerWriter.WriteLine(value); var expected = "1234567890123456"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteLong() { long value = -987654321; ListenerWriter.Write(value); ListenerWriter.WriteLine(value); var expected = "-987654321"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteUInt() { uint value = 0xff; ListenerWriter.Write(value); ListenerWriter.WriteLine(value); var expected = "255"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteInt() { int value = 0xff; ListenerWriter.Write(value); ListenerWriter.WriteLine(value); var expected = "255"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteBool() { bool value = true; ListenerWriter.Write(value); ListenerWriter.WriteLine(value); var expected = Boolean.TrueString; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteChar() { char value = 'x'; ListenerWriter.Write(value); ListenerWriter.WriteLine(value); var expected = "x"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteCharBuffer() { char[] buffer = new char[] { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' }; ListenerWriter.Write(buffer); ListenerWriter.WriteLine(buffer); var expected = "Hello World"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteCharBufferSubstring() { char[] buffer = new char[] { 'L', 'i', 't', 't', 'l', 'e', ' ', 'M', 'i', 's', 's', ' ', 'M', 'u', 'f', 'f', 'e', 't' }; int index = 6; int count = 7; ListenerWriter.Write(buffer, index, count); ListenerWriter.WriteLine(buffer, index, count); var expected = " Miss M"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteFloat() { float value = -5.0f; ListenerWriter.Write(value); ListenerWriter.WriteLine(value); var expected = "-5"; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(2)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); Assert.That(ListenerResult.Outputs[1], Is.EqualTo(expected + NL)); } [Test] public void TestWriteLine() { ListenerWriter.WriteLine(); var expected = NL; Assert.That(ListenerResult.Outputs.Count, Is.EqualTo(1)); Assert.That(ListenerResult.Outputs[0], Is.EqualTo(expected)); } #region ITestListener implementation private class TestListenerIntercepter : ITestListener { public IList<string> Outputs { get; } public ITestListener DefaultListener { get; } public TestListenerIntercepter(ITestListener defaultListener) { DefaultListener = defaultListener; Outputs = new List<string>(); } void ITestListener.TestStarted(ITest test) { if (DefaultListener != null) DefaultListener.TestStarted(test); } void ITestListener.TestFinished(ITestResult result) { if (DefaultListener != null) DefaultListener.TestFinished(result); } void ITestListener.TestOutput(TestOutput output) { Assert.IsNotNull(output); Outputs.Add(output.Text); if (DefaultListener != null) DefaultListener.TestOutput(output); } } #endregion } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ClientApi.Admin { using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Tenants operations. /// </summary> public partial class Tenants : IServiceOperations<PubSubAdminApi>, ITenants { /// <summary> /// Initializes a new instance of the Tenants class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Tenants(PubSubAdminApi client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the PubSubAdminApi /// </summary> public PubSubAdminApi Client { get; private set; } /// <param name='tenantId'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<string>> ResetKeysWithHttpMessagesAsync(string tenantId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (tenantId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "tenantId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("tenantId", tenantId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ResetKeys", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Tenants").ToString(); List<string> _queryParameters = new List<string>(); if (tenantId != null) { _queryParameters.Add(string.Format("tenantId={0}", System.Uri.EscapeDataString(tenantId))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<string>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<string>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <param name='tenantName'> /// </param> /// <param name='appVersion'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<string>> CreateTenantWithHttpMessagesAsync(string tenantName, string appVersion, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (tenantName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "tenantName"); } if (appVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "appVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("tenantName", tenantName); tracingParameters.Add("appVersion", appVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateTenant", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Tenants").ToString(); List<string> _queryParameters = new List<string>(); if (tenantName != null) { _queryParameters.Add(string.Format("TenantName={0}", System.Uri.EscapeDataString(tenantName))); } if (appVersion != null) { _queryParameters.Add(string.Format("AppVersion={0}", System.Uri.EscapeDataString(appVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<string>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<string>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Description { using System.Collections.Generic; using System.Globalization; using System.Net; using System.Reflection; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Channels; using System.ServiceModel.Configuration; using System.ServiceModel.Dispatcher; using System.Threading; using System.Xml; using System.Xml.Schema; using WsdlNS = System.Web.Services.Description; // the description/metadata "mix-in" public class ServiceMetadataExtension : IExtension<ServiceHostBase> { const string BaseAddressPattern = "{%BaseAddress%}"; static readonly Uri EmptyUri = new Uri(String.Empty, UriKind.Relative); static readonly Type[] httpGetSupportedChannels = new Type[] { typeof(IReplyChannel), }; ServiceMetadataBehavior.MetadataExtensionInitializer initializer; MetadataSet metadata; WsdlNS.ServiceDescription singleWsdl; bool isInitialized = false; bool isSingleWsdlInitialized = false; Uri externalMetadataLocation; ServiceHostBase owner; object syncRoot = new object(); object singleWsdlSyncRoot = new object(); bool mexEnabled = false; bool httpGetEnabled = false; bool httpsGetEnabled = false; bool httpHelpPageEnabled = false; bool httpsHelpPageEnabled = false; Uri mexUrl; Uri httpGetUrl; Uri httpsGetUrl; Uri httpHelpPageUrl; Uri httpsHelpPageUrl; Binding httpHelpPageBinding; Binding httpsHelpPageBinding; Binding httpGetBinding; Binding httpsGetBinding; public ServiceMetadataExtension() : this(null) { } internal ServiceMetadataExtension(ServiceMetadataBehavior.MetadataExtensionInitializer initializer) { this.initializer = initializer; } internal ServiceMetadataBehavior.MetadataExtensionInitializer Initializer { get { return this.initializer; } set { this.initializer = value; } } public MetadataSet Metadata { get { EnsureInitialized(); return this.metadata; } } public WsdlNS.ServiceDescription SingleWsdl { get { EnsureSingleWsdlInitialized(); return this.singleWsdl; } } internal Uri ExternalMetadataLocation { get { return this.externalMetadataLocation; } set { this.externalMetadataLocation = value; } } internal bool MexEnabled { get { return this.mexEnabled; } set { this.mexEnabled = value; } } internal bool HttpGetEnabled { get { return this.httpGetEnabled; } set { this.httpGetEnabled = value; } } internal bool HttpsGetEnabled { get { return this.httpsGetEnabled; } set { this.httpsGetEnabled = value; } } internal bool HelpPageEnabled { get { return this.httpHelpPageEnabled || this.httpsHelpPageEnabled; } } internal bool MetadataEnabled { get { return this.mexEnabled || this.httpGetEnabled || this.httpsGetEnabled; } } internal bool HttpHelpPageEnabled { get { return this.httpHelpPageEnabled; } set { this.httpHelpPageEnabled = value; } } internal bool HttpsHelpPageEnabled { get { return this.httpsHelpPageEnabled; } set { this.httpsHelpPageEnabled = value; } } internal Uri MexUrl { get { return this.mexUrl; } set { this.mexUrl = value; } } internal Uri HttpGetUrl { get { return this.httpGetUrl; } set { this.httpGetUrl = value; } } internal Uri HttpsGetUrl { get { return this.httpsGetUrl; } set { this.httpsGetUrl = value; } } internal Uri HttpHelpPageUrl { get { return this.httpHelpPageUrl; } set { this.httpHelpPageUrl = value; } } internal Uri HttpsHelpPageUrl { get { return this.httpsHelpPageUrl; } set { this.httpsHelpPageUrl = value; } } internal Binding HttpHelpPageBinding { get { return this.httpHelpPageBinding; } set { this.httpHelpPageBinding = value; } } internal Binding HttpsHelpPageBinding { get { return this.httpsHelpPageBinding; } set { this.httpsHelpPageBinding = value; } } internal Binding HttpGetBinding { get { return this.httpGetBinding; } set { this.httpGetBinding = value; } } internal Binding HttpsGetBinding { get { return this.httpsGetBinding; } set { this.httpsGetBinding = value; } } internal bool UpdateAddressDynamically { get; set; } // This dictionary should not be mutated after open internal IDictionary<string, int> UpdatePortsByScheme { get; set; } internal static bool TryGetHttpHostAndPort(Uri listenUri, Message request, out string host, out int port) { host = null; port = 0; // Get the host hedaer object property; if (!request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property)) { return false; } HttpRequestMessageProperty httpRequest = property as HttpRequestMessageProperty; if (httpRequest == null) { return false; } string hostHeader = httpRequest.Headers[HttpRequestHeader.Host]; if (string.IsNullOrEmpty(hostHeader)) { return false; } // Split and validate the host and port string hostUriString = string.Concat(listenUri.Scheme, "://", hostHeader); Uri hostUri; if (!Uri.TryCreate(hostUriString, UriKind.Absolute, out hostUri)) { return false; } host = hostUri.Host; port = hostUri.Port; return true; } void EnsureInitialized() { if (!this.isInitialized) { lock (this.syncRoot) { if (!this.isInitialized) { if (this.initializer != null) { // the following call will initialize this // it will use the Metadata property to do the initialization // this will call back into this method, but exit because isInitialized is set. // if other threads try to call these methods, they will block on the lock this.metadata = this.initializer.GenerateMetadata(); } if (this.metadata == null) { this.metadata = new MetadataSet(); } Thread.MemoryBarrier(); this.isInitialized = true; this.initializer = null; } } } } void EnsureSingleWsdlInitialized() { if (!this.isSingleWsdlInitialized) { lock (this.singleWsdlSyncRoot) { if (!this.isSingleWsdlInitialized) { // Could throw NotSupportedException if multiple contract namespaces. Let the exception propagate to the dispatcher and show up on the html error page this.singleWsdl = WsdlHelper.GetSingleWsdl(this.Metadata); this.isSingleWsdlInitialized = true; } } } } void IExtension<ServiceHostBase>.Attach(ServiceHostBase owner) { if (owner == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("owner")); if (this.owner != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TheServiceMetadataExtensionInstanceCouldNot2_0))); owner.ThrowIfClosedOrOpened(); this.owner = owner; } void IExtension<ServiceHostBase>.Detach(ServiceHostBase owner) { if (owner == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("owner"); if (this.owner == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TheServiceMetadataExtensionInstanceCouldNot3_0))); if (this.owner != owner) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("owner", SR.GetString(SR.TheServiceMetadataExtensionInstanceCouldNot4_0)); this.owner.ThrowIfClosedOrOpened(); this.owner = null; } static internal ServiceMetadataExtension EnsureServiceMetadataExtension(ServiceDescription description, ServiceHostBase host) { ServiceMetadataExtension mex = host.Extensions.Find<ServiceMetadataExtension>(); if (mex == null) { mex = new ServiceMetadataExtension(); host.Extensions.Add(mex); } return mex; } internal ChannelDispatcher EnsureGetDispatcher(Uri listenUri) { ChannelDispatcher channelDispatcher = FindGetDispatcher(listenUri); if (channelDispatcher == null) { channelDispatcher = CreateGetDispatcher(listenUri); owner.ChannelDispatchers.Add(channelDispatcher); } return channelDispatcher; } internal ChannelDispatcher EnsureGetDispatcher(Uri listenUri, bool isServiceDebugBehavior) { ChannelDispatcher channelDispatcher = FindGetDispatcher(listenUri); Binding binding; if (channelDispatcher == null) { if (listenUri.Scheme == Uri.UriSchemeHttp) { if (isServiceDebugBehavior) { binding = this.httpHelpPageBinding ?? MetadataExchangeBindings.HttpGet; } else { binding = this.httpGetBinding ?? MetadataExchangeBindings.HttpGet; } } else if (listenUri.Scheme == Uri.UriSchemeHttps) { if (isServiceDebugBehavior) { binding = this.httpsHelpPageBinding ?? MetadataExchangeBindings.HttpsGet; } else { binding = this.httpsGetBinding ?? MetadataExchangeBindings.HttpsGet; } } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SFxGetChannelDispatcherDoesNotSupportScheme, typeof(ChannelDispatcher).Name, Uri.UriSchemeHttp, Uri.UriSchemeHttps))); } channelDispatcher = CreateGetDispatcher(listenUri, binding); owner.ChannelDispatchers.Add(channelDispatcher); } return channelDispatcher; } ChannelDispatcher FindGetDispatcher(Uri listenUri) { foreach (ChannelDispatcherBase channelDispatcherBase in owner.ChannelDispatchers) { ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher; if (channelDispatcher != null && channelDispatcher.Listener.Uri == listenUri) { if (channelDispatcher.Endpoints.Count == 1 && channelDispatcher.Endpoints[0].DispatchRuntime.SingletonInstanceContext != null && channelDispatcher.Endpoints[0].DispatchRuntime.SingletonInstanceContext.UserObject is HttpGetImpl) { return channelDispatcher; } } } return null; } ChannelDispatcher CreateGetDispatcher(Uri listenUri) { if (listenUri.Scheme == Uri.UriSchemeHttp) { return CreateGetDispatcher(listenUri, MetadataExchangeBindings.HttpGet); } else if (listenUri.Scheme == Uri.UriSchemeHttps) { return CreateGetDispatcher(listenUri, MetadataExchangeBindings.HttpsGet); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SFxGetChannelDispatcherDoesNotSupportScheme, typeof(ChannelDispatcher).Name, Uri.UriSchemeHttp, Uri.UriSchemeHttps))); } } ChannelDispatcher CreateGetDispatcher(Uri listenUri, Binding binding) { EndpointAddress address = new EndpointAddress(listenUri); Uri listenUriBaseAddress = listenUri; string listenUriRelativeAddress = string.Empty; //Set up binding parameter collection BindingParameterCollection parameters = owner.GetBindingParameters(); AspNetEnvironment.Current.AddMetadataBindingParameters(listenUriBaseAddress, owner.Description.Behaviors, parameters); // find listener for HTTP GET IChannelListener listener = null; if (binding.CanBuildChannelListener<IReplyChannel>(parameters)) { listener = binding.BuildChannelListener<IReplyChannel>(listenUriBaseAddress, listenUriRelativeAddress, parameters); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.SFxBindingNotSupportedForMetadataHttpGet))); } //create dispatchers ChannelDispatcher channelDispatcher = new ChannelDispatcher(listener, HttpGetImpl.MetadataHttpGetBinding, binding); channelDispatcher.MessageVersion = binding.MessageVersion; EndpointDispatcher dispatcher = new EndpointDispatcher(address, HttpGetImpl.ContractName, HttpGetImpl.ContractNamespace, true); //Add operation DispatchOperation operationDispatcher = new DispatchOperation(dispatcher.DispatchRuntime, HttpGetImpl.GetMethodName, HttpGetImpl.RequestAction, HttpGetImpl.ReplyAction); operationDispatcher.Formatter = MessageOperationFormatter.Instance; MethodInfo methodInfo = typeof(IHttpGetMetadata).GetMethod(HttpGetImpl.GetMethodName); operationDispatcher.Invoker = new SyncMethodInvoker(methodInfo); dispatcher.DispatchRuntime.Operations.Add(operationDispatcher); //wire up dispatchers HttpGetImpl impl = new HttpGetImpl(this, listener.Uri); dispatcher.DispatchRuntime.SingletonInstanceContext = new InstanceContext(owner, impl, false); dispatcher.DispatchRuntime.MessageInspectors.Add(impl); channelDispatcher.Endpoints.Add(dispatcher); dispatcher.ContractFilter = new MatchAllMessageFilter(); dispatcher.FilterPriority = 0; dispatcher.DispatchRuntime.InstanceContextProvider = InstanceContextProviderBase.GetProviderForMode(InstanceContextMode.Single, dispatcher.DispatchRuntime); channelDispatcher.ServiceThrottle = owner.ServiceThrottle; ServiceDebugBehavior sdb = owner.Description.Behaviors.Find<ServiceDebugBehavior>(); if (sdb != null) channelDispatcher.IncludeExceptionDetailInFaults |= sdb.IncludeExceptionDetailInFaults; ServiceBehaviorAttribute sba = owner.Description.Behaviors.Find<ServiceBehaviorAttribute>(); if (sba != null) channelDispatcher.IncludeExceptionDetailInFaults |= sba.IncludeExceptionDetailInFaults; return channelDispatcher; } WriteFilter GetWriteFilter(Message request, Uri listenUri, bool removeBaseAddress) { WriteFilter result = null; if (this.UpdateAddressDynamically) { // Update address dynamically based on the request URI result = GetDynamicAddressWriter(request, listenUri, removeBaseAddress); } if (result == null) { // Just use the statically known listen URI if (removeBaseAddress) { result = new LocationUpdatingWriter(BaseAddressPattern, null); } else { result = new LocationUpdatingWriter(BaseAddressPattern, listenUri.ToString()); } } return result; } DynamicAddressUpdateWriter GetDynamicAddressWriter(Message request, Uri listenUri, bool removeBaseAddress) { string requestHost; int requestPort; if (!TryGetHttpHostAndPort(listenUri, request, out requestHost, out requestPort)) { if (request.Headers.To == null) { return null; } requestHost = request.Headers.To.Host; requestPort = request.Headers.To.Port; } // Perf optimization: don't do dynamic update if it would be a no-op. // Ordinal string comparison is okay; it just means we don't get the perf optimization // if the listen host and request host are case-insensitively equal. if (requestHost == listenUri.Host && requestPort == listenUri.Port && (UpdatePortsByScheme == null || UpdatePortsByScheme.Count == 0)) { return null; } return new DynamicAddressUpdateWriter( listenUri, requestHost, requestPort, this.UpdatePortsByScheme, removeBaseAddress); } internal class MetadataBindingParameter { } internal class WSMexImpl : IMetadataExchange { internal const string MetadataMexBinding = "ServiceMetadataBehaviorMexBinding"; internal const string ContractName = MetadataStrings.WSTransfer.Name; internal const string ContractNamespace = MetadataStrings.WSTransfer.Namespace; internal const string GetMethodName = "Get"; internal const string RequestAction = MetadataStrings.WSTransfer.GetAction; internal const string ReplyAction = MetadataStrings.WSTransfer.GetResponseAction; ServiceMetadataExtension parent; MetadataSet metadataLocationSet; TypedMessageConverter converter; Uri listenUri; bool isListeningOnHttps; internal WSMexImpl(ServiceMetadataExtension parent, bool isListeningOnHttps, Uri listenUri) { this.parent = parent; this.isListeningOnHttps = isListeningOnHttps; this.listenUri = listenUri; if (this.parent.ExternalMetadataLocation != null && this.parent.ExternalMetadataLocation != EmptyUri) { this.metadataLocationSet = new MetadataSet(); string location = this.GetLocationToReturn(); MetadataSection metadataLocationSection = new MetadataSection(MetadataSection.ServiceDescriptionDialect, null, new MetadataLocation(location)); this.metadataLocationSet.MetadataSections.Add(metadataLocationSection); } } internal bool IsListeningOnHttps { get { return this.isListeningOnHttps; } set { this.isListeningOnHttps = value; } } string GetLocationToReturn() { Fx.Assert(this.parent.ExternalMetadataLocation != null, ""); Uri location = this.parent.ExternalMetadataLocation; if (!location.IsAbsoluteUri) { Uri httpAddr = parent.owner.GetVia(Uri.UriSchemeHttp, location); Uri httpsAddr = parent.owner.GetVia(Uri.UriSchemeHttps, location); if (this.IsListeningOnHttps && httpsAddr != null) { location = httpsAddr; } else if (httpAddr != null) { location = httpAddr; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("ExternalMetadataLocation", SR.GetString(SR.SFxBadMetadataLocationNoAppropriateBaseAddress, this.parent.ExternalMetadataLocation.OriginalString)); } } return location.ToString(); } MetadataSet GatherMetadata(string dialect, string identifier) { if (metadataLocationSet != null) { return metadataLocationSet; } else { MetadataSet metadataSet = new MetadataSet(); foreach (MetadataSection document in parent.Metadata.MetadataSections) { if ((dialect == null || dialect == document.Dialect) && (identifier == null || identifier == document.Identifier)) metadataSet.MetadataSections.Add(document); } return metadataSet; } } public Message Get(Message request) { GetResponse response = new GetResponse(); response.Metadata = GatherMetadata(null, null); response.Metadata.WriteFilter = parent.GetWriteFilter(request, this.listenUri, true); if (converter == null) converter = TypedMessageConverter.Create(typeof(GetResponse), ReplyAction); return converter.ToMessage(response, request.Version); } public IAsyncResult BeginGet(Message request, AsyncCallback callback, object state) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException()); } public Message EndGet(IAsyncResult result) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException()); } } //If this contract is changed, you may need to change ServiceMetadataExtension.CreateHttpGetDispatcher() [ServiceContract] internal interface IHttpGetMetadata { [OperationContract(Action = MessageHeaders.WildcardAction, ReplyAction = MessageHeaders.WildcardAction)] Message Get(Message msg); } internal class HttpGetImpl : IHttpGetMetadata, IDispatchMessageInspector { const string DiscoToken = "disco token"; const string DiscoQueryString = "disco"; const string WsdlQueryString = "wsdl"; const string XsdQueryString = "xsd"; const string SingleWsdlQueryString = "singleWsdl"; const string HtmlContentType = "text/html; charset=UTF-8"; const string XmlContentType = "text/xml; charset=UTF-8"; const int closeTimeoutInSeconds = 90; const int maxQueryStringChars = 2048; internal const string MetadataHttpGetBinding = "ServiceMetadataBehaviorHttpGetBinding"; internal const string ContractName = "IHttpGetHelpPageAndMetadataContract"; internal const string ContractNamespace = "http://schemas.microsoft.com/2006/04/http/metadata"; internal const string GetMethodName = "Get"; internal const string RequestAction = MessageHeaders.WildcardAction; internal const string ReplyAction = MessageHeaders.WildcardAction; internal const string HtmlBreak = "<BR/>"; static string[] NoQueries = new string[0]; ServiceMetadataExtension parent; object sync = new object(); InitializationData initData; Uri listenUri; bool helpPageEnabled = false; bool getWsdlEnabled = false; internal HttpGetImpl(ServiceMetadataExtension parent, Uri listenUri) { this.parent = parent; this.listenUri = listenUri; } public bool HelpPageEnabled { get { return this.helpPageEnabled; } set { this.helpPageEnabled = value; } } public bool GetWsdlEnabled { get { return this.getWsdlEnabled; } set { this.getWsdlEnabled = value; } } InitializationData GetInitData() { if (this.initData == null) { lock (this.sync) { if (this.initData == null) { this.initData = InitializationData.InitializeFrom(parent); } } } return this.initData; } string FindWsdlReference(DynamicAddressUpdateWriter addressUpdater) { if (this.parent.ExternalMetadataLocation == null || this.parent.ExternalMetadataLocation == EmptyUri) { return null; } else { Uri location = this.parent.ExternalMetadataLocation; Uri result = ServiceHost.GetUri(this.listenUri, location); if (addressUpdater != null) { addressUpdater.UpdateUri(ref result); } return result.ToString(); } } bool TryHandleDocumentationRequest(Message httpGetRequest, string[] queries, out Message replyMessage) { replyMessage = null; if (!this.HelpPageEnabled) return false; if (parent.MetadataEnabled) { string discoUrl = null; string wsdlUrl = null; string httpGetUrl = null; string singleWsdlUrl = null; bool linkMetadata = true; DynamicAddressUpdateWriter addressUpdater = null; if (parent.UpdateAddressDynamically) { addressUpdater = parent.GetDynamicAddressWriter(httpGetRequest, this.listenUri, false); } wsdlUrl = FindWsdlReference(addressUpdater); httpGetUrl = GetHttpGetUrl(addressUpdater); if (wsdlUrl == null && httpGetUrl != null) { wsdlUrl = httpGetUrl + "?" + WsdlQueryString; singleWsdlUrl = httpGetUrl + "?" + SingleWsdlQueryString; } if (httpGetUrl != null) discoUrl = httpGetUrl + "?" + DiscoQueryString; if (wsdlUrl == null) { wsdlUrl = GetMexUrl(addressUpdater); linkMetadata = false; } replyMessage = new MetadataOnHelpPageMessage(discoUrl, wsdlUrl, singleWsdlUrl, GetInitData().ServiceName, GetInitData().ClientName, linkMetadata); } else { replyMessage = new MetadataOffHelpPageMessage(GetInitData().ServiceName); } AddHttpProperty(replyMessage, HttpStatusCode.OK, HtmlContentType); return true; } string GetHttpGetUrl(DynamicAddressUpdateWriter addressUpdater) { Uri result = null; if (this.listenUri.Scheme == Uri.UriSchemeHttp) { if (parent.HttpGetEnabled) result = parent.HttpGetUrl; else if (parent.HttpsGetEnabled) result = parent.HttpsGetUrl; } else { if (parent.HttpsGetEnabled) result = parent.HttpsGetUrl; else if (parent.HttpGetEnabled) result = parent.HttpGetUrl; } if (result != null) { if (addressUpdater != null) { addressUpdater.UpdateUri(ref result, this.listenUri.Scheme != result.Scheme /*updateBaseAddressOnly*/); } return result.ToString(); } return null; } string GetMexUrl(DynamicAddressUpdateWriter addressUpdater) { if (parent.MexEnabled) { Uri result = parent.MexUrl; if (addressUpdater != null) { addressUpdater.UpdateUri(ref result); } return result.ToString(); } return null; } bool TryHandleMetadataRequest(Message httpGetRequest, string[] queries, out Message replyMessage) { replyMessage = null; if (!this.GetWsdlEnabled) return false; WriteFilter writeFilter = parent.GetWriteFilter(httpGetRequest, this.listenUri, false); string query = FindQuery(queries); if (String.IsNullOrEmpty(query)) { //if the documentation page is not available return the default wsdl if it exists if (!this.helpPageEnabled && GetInitData().DefaultWsdl != null) { // use the default WSDL using (httpGetRequest) { replyMessage = new ServiceDescriptionMessage( GetInitData().DefaultWsdl, writeFilter); AddHttpProperty(replyMessage, HttpStatusCode.OK, XmlContentType); GetInitData().FixImportAddresses(); return true; } } return false; } // try to look the document up in the query table object doc; if (GetInitData().TryQueryLookup(query, out doc)) { using (httpGetRequest) { if (doc is WsdlNS.ServiceDescription) { replyMessage = new ServiceDescriptionMessage( (WsdlNS.ServiceDescription)doc, writeFilter); } else if (doc is XmlSchema) { replyMessage = new XmlSchemaMessage( ((XmlSchema)doc), writeFilter); } else if (doc is string) { if (((string)doc) == DiscoToken) { replyMessage = CreateDiscoMessage(writeFilter as DynamicAddressUpdateWriter); } else { Fx.Assert("Bad object in HttpGetImpl docFromQuery table"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Bad object in HttpGetImpl docFromQuery table"))); } } else { Fx.Assert("Bad object in HttpGetImpl docFromQuery table"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Bad object in HttpGetImpl docFromQuery table"))); } AddHttpProperty(replyMessage, HttpStatusCode.OK, XmlContentType); GetInitData().FixImportAddresses(); return true; } } // otherwise see if they just wanted ?WSDL if (String.Compare(query, WsdlQueryString, StringComparison.OrdinalIgnoreCase) == 0) { if (GetInitData().DefaultWsdl != null) { // use the default WSDL using (httpGetRequest) { replyMessage = new ServiceDescriptionMessage( GetInitData().DefaultWsdl, writeFilter); AddHttpProperty(replyMessage, HttpStatusCode.OK, XmlContentType); GetInitData().FixImportAddresses(); return true; } } // or redirect to an external WSDL string wsdlReference = FindWsdlReference(writeFilter as DynamicAddressUpdateWriter); if (wsdlReference != null) { replyMessage = CreateRedirectMessage(wsdlReference); return true; } } // ?singleWSDL if (String.Compare(query, SingleWsdlQueryString, StringComparison.OrdinalIgnoreCase) == 0) { WsdlNS.ServiceDescription singleWSDL = parent.SingleWsdl; if (singleWSDL != null) { using (httpGetRequest) { replyMessage = new ServiceDescriptionMessage( singleWSDL, writeFilter); AddHttpProperty(replyMessage, HttpStatusCode.OK, XmlContentType); return true; } } } // we weren't able to handle the request -- return the documentation page if available return false; } Message CreateDiscoMessage(DynamicAddressUpdateWriter addressUpdater) { Uri wsdlUrlBase = this.listenUri; if (addressUpdater != null) { addressUpdater.UpdateUri(ref wsdlUrlBase); } string wsdlUrl = wsdlUrlBase.ToString() + "?" + WsdlQueryString; Uri docUrl = null; if (this.listenUri.Scheme == Uri.UriSchemeHttp) { if (parent.HttpHelpPageEnabled) docUrl = parent.HttpHelpPageUrl; else if (parent.HttpsHelpPageEnabled) docUrl = parent.HttpsGetUrl; } else { if (parent.HttpsHelpPageEnabled) docUrl = parent.HttpsHelpPageUrl; else if (parent.HttpHelpPageEnabled) docUrl = parent.HttpGetUrl; } if (addressUpdater != null) { addressUpdater.UpdateUri(ref docUrl); } return new DiscoMessage(wsdlUrl, docUrl.ToString()); } string FindQuery(string[] queries) { string query = null; foreach (string q in queries) { int start = (q.Length > 0 && q[0] == '?') ? 1 : 0; if (String.Compare(q, start, WsdlQueryString, 0, WsdlQueryString.Length, StringComparison.OrdinalIgnoreCase) == 0) query = q; else if (String.Compare(q, start, XsdQueryString, 0, XsdQueryString.Length, StringComparison.OrdinalIgnoreCase) == 0) query = q; else if (String.Compare(q, start, SingleWsdlQueryString, 0, SingleWsdlQueryString.Length, StringComparison.OrdinalIgnoreCase) == 0) query = q; else if (parent.HelpPageEnabled && (String.Compare(q, start, DiscoQueryString, 0, DiscoQueryString.Length, StringComparison.OrdinalIgnoreCase) == 0)) query = q; } return query; } Message ProcessHttpRequest(Message httpGetRequest) { string queryString = httpGetRequest.Properties.Via.Query; if (queryString.Length > maxQueryStringChars) return CreateHttpResponseMessage(HttpStatusCode.RequestUriTooLong); if (queryString.StartsWith("?", StringComparison.OrdinalIgnoreCase)) queryString = queryString.Substring(1); string[] queries = queryString.Length > 0 ? queryString.Split('&') : NoQueries; Message replyMessage = null; if (TryHandleMetadataRequest(httpGetRequest, queries, out replyMessage)) return replyMessage; if (TryHandleDocumentationRequest(httpGetRequest, queries, out replyMessage)) return replyMessage; return CreateHttpResponseMessage(HttpStatusCode.MethodNotAllowed); } public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { return request.Version; } public void BeforeSendReply(ref Message reply, object correlationState) { if ((reply != null) && reply.IsFault) { string error = SR.GetString(SR.SFxInternalServerError); ExceptionDetail exceptionDetail = null; MessageFault fault = MessageFault.CreateFault(reply, /* maxBufferSize */ 64 * 1024); if (fault.HasDetail) { exceptionDetail = fault.GetDetail<ExceptionDetail>(); if (exceptionDetail != null) { error = SR.GetString(SR.SFxDocExt_Error); } } reply = new MetadataOnHelpPageMessage(error, exceptionDetail); AddHttpProperty(reply, HttpStatusCode.InternalServerError, HtmlContentType); } } public Message Get(Message message) { return ProcessHttpRequest(message); } class InitializationData { readonly Dictionary<string, object> docFromQuery; readonly Dictionary<object, string> queryFromDoc; WsdlNS.ServiceDescriptionCollection wsdls; XmlSchemaSet xsds; public string ServiceName; public string ClientName; public WsdlNS.ServiceDescription DefaultWsdl; InitializationData( Dictionary<string, object> docFromQuery, Dictionary<object, string> queryFromDoc, WsdlNS.ServiceDescriptionCollection wsdls, XmlSchemaSet xsds) { this.docFromQuery = docFromQuery; this.queryFromDoc = queryFromDoc; this.wsdls = wsdls; this.xsds = xsds; } public bool TryQueryLookup(string query, out object doc) { return docFromQuery.TryGetValue(query, out doc); } public static InitializationData InitializeFrom(ServiceMetadataExtension extension) { Dictionary<string, object> docFromQueryInit = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); Dictionary<object, string> queryFromDocInit = new Dictionary<object, string>(); // this collection type provides useful lookup features WsdlNS.ServiceDescriptionCollection wsdls = CollectWsdls(extension.Metadata); XmlSchemaSet xsds = CollectXsds(extension.Metadata); WsdlNS.ServiceDescription defaultWsdl = null; WsdlNS.Service someService = GetAnyService(wsdls); if (someService != null) defaultWsdl = someService.ServiceDescription; // WSDLs { int i = 0; foreach (WsdlNS.ServiceDescription wsdlDoc in wsdls) { string query = WsdlQueryString; if (wsdlDoc != defaultWsdl) // don't count the WSDL at ?WSDL query += "=wsdl" + (i++).ToString(System.Globalization.CultureInfo.InvariantCulture); docFromQueryInit.Add(query, wsdlDoc); queryFromDocInit.Add(wsdlDoc, query); } } // XSDs { int i = 0; foreach (XmlSchema xsdDoc in xsds.Schemas()) { string query = XsdQueryString + "=xsd" + (i++).ToString(System.Globalization.CultureInfo.InvariantCulture); docFromQueryInit.Add(query, xsdDoc); queryFromDocInit.Add(xsdDoc, query); } } // Disco if (extension.HelpPageEnabled) { string query = DiscoQueryString; docFromQueryInit.Add(query, DiscoToken); queryFromDocInit.Add(DiscoToken, query); } InitializationData data = new InitializationData(docFromQueryInit, queryFromDocInit, wsdls, xsds); data.DefaultWsdl = defaultWsdl; data.ServiceName = GetAnyWsdlName(wsdls); data.ClientName = ClientClassGenerator.GetClientClassName(GetAnyContractName(wsdls) ?? "IHello"); return data; } static WsdlNS.ServiceDescriptionCollection CollectWsdls(MetadataSet metadata) { WsdlNS.ServiceDescriptionCollection wsdls = new WsdlNS.ServiceDescriptionCollection(); foreach (MetadataSection section in metadata.MetadataSections) { if (section.Metadata is WsdlNS.ServiceDescription) { wsdls.Add((WsdlNS.ServiceDescription)section.Metadata); } } return wsdls; } static XmlSchemaSet CollectXsds(MetadataSet metadata) { XmlSchemaSet xsds = new XmlSchemaSet(); xsds.XmlResolver = null; foreach (MetadataSection section in metadata.MetadataSections) { if (section.Metadata is XmlSchema) { xsds.Add((XmlSchema)section.Metadata); } } return xsds; } internal void FixImportAddresses() { // fixup imports and includes with addresses // WSDLs foreach (WsdlNS.ServiceDescription wsdlDoc in this.wsdls) { FixImportAddresses(wsdlDoc); } // XSDs foreach (XmlSchema xsdDoc in this.xsds.Schemas()) { FixImportAddresses(xsdDoc); } } void FixImportAddresses(WsdlNS.ServiceDescription wsdlDoc) { foreach (WsdlNS.Import import in wsdlDoc.Imports) { if (!String.IsNullOrEmpty(import.Location)) continue; WsdlNS.ServiceDescription targetDoc = this.wsdls[import.Namespace ?? String.Empty]; if (targetDoc != null) { string query = queryFromDoc[targetDoc]; import.Location = BaseAddressPattern + "?" + query; } } if (wsdlDoc.Types != null) { foreach (XmlSchema xsdDoc in wsdlDoc.Types.Schemas) { FixImportAddresses(xsdDoc); } } } void FixImportAddresses(XmlSchema xsdDoc) { foreach (XmlSchemaObject o in xsdDoc.Includes) { XmlSchemaExternal external = o as XmlSchemaExternal; if (external == null || !String.IsNullOrEmpty(external.SchemaLocation)) continue; string targetNs = external is XmlSchemaImport ? ((XmlSchemaImport)external).Namespace : xsdDoc.TargetNamespace; foreach (XmlSchema targetXsd in this.xsds.Schemas(targetNs ?? String.Empty)) { if (targetXsd != xsdDoc) { string query = this.queryFromDoc[targetXsd]; external.SchemaLocation = BaseAddressPattern + "?" + query; break; } } } } static string GetAnyContractName(WsdlNS.ServiceDescriptionCollection wsdls) { // try to track down a WSDL portType name using a wsdl:service as a starting point foreach (WsdlNS.ServiceDescription wsdl in wsdls) { foreach (WsdlNS.Service service in wsdl.Services) { foreach (WsdlNS.Port port in service.Ports) { if (!port.Binding.IsEmpty) { WsdlNS.Binding binding = wsdls.GetBinding(port.Binding); if (!binding.Type.IsEmpty) { return binding.Type.Name; } } } } } return null; } static WsdlNS.Service GetAnyService(WsdlNS.ServiceDescriptionCollection wsdls) { // try to track down a WSDL service foreach (WsdlNS.ServiceDescription wsdl in wsdls) { if (wsdl.Services.Count > 0) { return wsdl.Services[0]; } } return null; } static string GetAnyWsdlName(WsdlNS.ServiceDescriptionCollection wsdls) { // try to track down a WSDL name foreach (WsdlNS.ServiceDescription wsdl in wsdls) { if (!String.IsNullOrEmpty(wsdl.Name)) { return wsdl.Name; } } return null; } } #region static helpers static void AddHttpProperty(Message message, HttpStatusCode status, string contentType) { HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty(); responseProperty.StatusCode = status; responseProperty.Headers.Add(HttpResponseHeader.ContentType, contentType); message.Properties.Add(HttpResponseMessageProperty.Name, responseProperty); } static Message CreateRedirectMessage(string redirectedDestination) { Message redirectMessage = CreateHttpResponseMessage(HttpStatusCode.RedirectKeepVerb); HttpResponseMessageProperty httpResponseProperty = (HttpResponseMessageProperty)redirectMessage.Properties[HttpResponseMessageProperty.Name]; httpResponseProperty.Headers["Location"] = redirectedDestination; return redirectMessage; } static Message CreateHttpResponseMessage(HttpStatusCode code) { Message message = new NullMessage(); HttpResponseMessageProperty httpResponseProperty = new HttpResponseMessageProperty(); httpResponseProperty.StatusCode = code; message.Properties.Add(HttpResponseMessageProperty.Name, httpResponseProperty); return message; } #endregion static helpers #region Helper Message implementations class DiscoMessage : ContentOnlyMessage { string wsdlAddress; string docAddress; public DiscoMessage(string wsdlAddress, string docAddress) : base() { this.wsdlAddress = wsdlAddress; this.docAddress = docAddress; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteStartDocument(); writer.WriteStartElement("discovery", "http://schemas.xmlsoap.org/disco/"); writer.WriteStartElement("contractRef", "http://schemas.xmlsoap.org/disco/scl/"); writer.WriteAttributeString("ref", wsdlAddress); writer.WriteAttributeString("docRef", docAddress); writer.WriteEndElement(); // </contractRef> writer.WriteEndElement(); // </discovery> writer.WriteEndDocument(); } } class MetadataOnHelpPageMessage : ContentOnlyMessage { string discoUrl; string metadataUrl; string singleWsdlUrl; string serviceName; string clientName; bool linkMetadata; string errorMessage; ExceptionDetail exceptionDetail; public MetadataOnHelpPageMessage(string discoUrl, string metadataUrl, string singleWsdlUrl, string serviceName, string clientName, bool linkMetadata) : base() { this.discoUrl = discoUrl; this.metadataUrl = metadataUrl; this.singleWsdlUrl = singleWsdlUrl; this.serviceName = serviceName; this.clientName = clientName; this.linkMetadata = linkMetadata; } public MetadataOnHelpPageMessage(string errorMessage, ExceptionDetail exceptionDetail) : base() { this.errorMessage = errorMessage; this.exceptionDetail = exceptionDetail; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { HelpPageWriter page = new HelpPageWriter(writer); writer.WriteStartElement("HTML"); writer.WriteStartElement("HEAD"); if (!String.IsNullOrEmpty(this.discoUrl)) { page.WriteDiscoLink(this.discoUrl); } page.WriteStyleSheet(); page.WriteTitle(!String.IsNullOrEmpty(this.serviceName) ? SR.GetString(SR.SFxDocExt_MainPageTitle, this.serviceName) : SR.GetString(SR.SFxDocExt_MainPageTitleNoServiceName)); if (!String.IsNullOrEmpty(this.errorMessage)) { page.WriteError(this.errorMessage); if (this.exceptionDetail != null) { page.WriteExceptionDetail(this.exceptionDetail); } } else { page.WriteToolUsage(this.metadataUrl, this.singleWsdlUrl, this.linkMetadata); page.WriteSampleCode(this.clientName); } writer.WriteEndElement(); // BODY writer.WriteEndElement(); // HTML } struct HelpPageWriter { XmlWriter writer; public HelpPageWriter(XmlWriter writer) { this.writer = writer; } internal void WriteClass(string className) { writer.WriteStartElement("font"); writer.WriteAttributeString("color", "teal"); writer.WriteString(className); writer.WriteEndElement(); // font } internal void WriteComment(string comment) { writer.WriteStartElement("font"); writer.WriteAttributeString("color", "green"); writer.WriteString(comment); writer.WriteEndElement(); // font } internal void WriteDiscoLink(string discoUrl) { writer.WriteStartElement("link"); writer.WriteAttributeString("rel", "alternate"); writer.WriteAttributeString("type", "text/xml"); writer.WriteAttributeString("href", discoUrl); writer.WriteEndElement(); // link } internal void WriteError(string message) { writer.WriteStartElement("P"); writer.WriteAttributeString("class", "intro"); writer.WriteString(message); writer.WriteEndElement(); // P } internal void WriteKeyword(string keyword) { writer.WriteStartElement("font"); writer.WriteAttributeString("color", "blue"); writer.WriteString(keyword); writer.WriteEndElement(); // font } internal void WriteSampleCode(string clientName) { writer.WriteStartElement("P"); writer.WriteAttributeString("class", "intro"); writer.WriteEndElement(); // P writer.WriteRaw(SR.GetString(SR.SFxDocExt_MainPageIntro2)); // C# writer.WriteRaw(SR.GetString(SR.SFxDocExt_CS)); writer.WriteStartElement("PRE"); WriteKeyword("class "); WriteClass("Test\n"); writer.WriteString("{\n"); WriteKeyword(" static void "); writer.WriteString("Main()\n"); writer.WriteString(" {\n"); writer.WriteString(" "); WriteClass(clientName); writer.WriteString(" client = "); WriteKeyword("new "); WriteClass(clientName); writer.WriteString("();\n\n"); WriteComment(" // " + SR.GetString(SR.SFxDocExt_MainPageComment) + "\n\n"); WriteComment(" // " + SR.GetString(SR.SFxDocExt_MainPageComment2) + "\n"); writer.WriteString(" client.Close();\n"); writer.WriteString(" }\n"); writer.WriteString("}\n"); writer.WriteEndElement(); // PRE writer.WriteRaw(HttpGetImpl.HtmlBreak); // VB writer.WriteRaw(SR.GetString(SR.SFxDocExt_VB)); writer.WriteStartElement("PRE"); WriteKeyword("Class "); WriteClass("Test\n"); WriteKeyword(" Shared Sub "); writer.WriteString("Main()\n"); WriteKeyword(" Dim "); writer.WriteString("client As "); WriteClass(clientName); writer.WriteString(" = "); WriteKeyword("New "); WriteClass(clientName); writer.WriteString("()\n"); WriteComment(" ' " + SR.GetString(SR.SFxDocExt_MainPageComment) + "\n\n"); WriteComment(" ' " + SR.GetString(SR.SFxDocExt_MainPageComment2) + "\n"); writer.WriteString(" client.Close()\n"); WriteKeyword(" End Sub\n"); WriteKeyword("End Class"); writer.WriteEndElement(); // PRE } internal void WriteExceptionDetail(ExceptionDetail exceptionDetail) { writer.WriteStartElement("PRE"); writer.WriteString(exceptionDetail.ToString().Replace("\r", "")); writer.WriteEndElement(); // PRE } internal void WriteStyleSheet() { writer.WriteStartElement("STYLE"); writer.WriteAttributeString("type", "text/css"); writer.WriteString("#content{ FONT-SIZE: 0.7em; PADDING-BOTTOM: 2em; MARGIN-LEFT: 30px}"); writer.WriteString("BODY{MARGIN-TOP: 0px; MARGIN-LEFT: 0px; COLOR: #000000; FONT-FAMILY: Verdana; BACKGROUND-COLOR: white}"); writer.WriteString("P{MARGIN-TOP: 0px; MARGIN-BOTTOM: 12px; COLOR: #000000; FONT-FAMILY: Verdana}"); writer.WriteString("PRE{BORDER-RIGHT: #f0f0e0 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #f0f0e0 1px solid; MARGIN-TOP: -5px; PADDING-LEFT: 5px; FONT-SIZE: 1.2em; PADDING-BOTTOM: 5px; BORDER-LEFT: #f0f0e0 1px solid; PADDING-TOP: 5px; BORDER-BOTTOM: #f0f0e0 1px solid; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e5e5cc}"); writer.WriteString(".heading1{MARGIN-TOP: 0px; PADDING-LEFT: 15px; FONT-WEIGHT: normal; FONT-SIZE: 26px; MARGIN-BOTTOM: 0px; PADDING-BOTTOM: 3px; MARGIN-LEFT: -30px; WIDTH: 100%; COLOR: #ffffff; PADDING-TOP: 10px; FONT-FAMILY: Tahoma; BACKGROUND-COLOR: #003366}"); writer.WriteString(".intro{MARGIN-LEFT: -15px}"); writer.WriteEndElement(); // STYLE } internal void WriteTitle(string title) { writer.WriteElementString("TITLE", title); writer.WriteEndElement(); // HEAD writer.WriteStartElement("BODY"); writer.WriteStartElement("DIV"); writer.WriteAttributeString("id", "content"); writer.WriteStartElement("P"); writer.WriteAttributeString("class", "heading1"); writer.WriteString(title); writer.WriteEndElement(); // P writer.WriteRaw(HttpGetImpl.HtmlBreak); } internal void WriteToolUsage(string wsdlUrl, string singleWsdlUrl, bool linkMetadata) { writer.WriteStartElement("P"); writer.WriteAttributeString("class", "intro"); if (wsdlUrl != null) { WriteMetadataAddress(SR.SFxDocExt_MainPageIntro1a, "svcutil.exe ", wsdlUrl, linkMetadata); if (singleWsdlUrl != null) { // ?singleWsdl message writer.WriteStartElement("P"); WriteMetadataAddress(SR.SFxDocExt_MainPageIntroSingleWsdl, null, singleWsdlUrl, linkMetadata); writer.WriteEndElement(); } } else { // no metadata message writer.WriteRaw(SR.GetString(SR.SFxDocExt_MainPageIntro1b)); } writer.WriteEndElement(); // P } void WriteMetadataAddress(string introductionText, string clientToolName, string wsdlUrl, bool linkMetadata) { writer.WriteRaw(SR.GetString(introductionText)); writer.WriteRaw(HttpGetImpl.HtmlBreak); writer.WriteStartElement("PRE"); if (!string.IsNullOrEmpty(clientToolName)) { writer.WriteString(clientToolName); } if (linkMetadata) { writer.WriteStartElement("A"); writer.WriteAttributeString("HREF", wsdlUrl); } writer.WriteString(wsdlUrl); if (linkMetadata) { writer.WriteEndElement(); // A } writer.WriteEndElement(); // PRE } } } class MetadataOffHelpPageMessage : ContentOnlyMessage { public MetadataOffHelpPageMessage(string serviceName) { } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteStartElement("HTML"); writer.WriteStartElement("HEAD"); writer.WriteRaw(String.Format(CultureInfo.InvariantCulture, @"<STYLE type=""text/css"">#content{{ FONT-SIZE: 0.7em; PADDING-BOTTOM: 2em; MARGIN-LEFT: 30px}}BODY{{MARGIN-TOP: 0px; MARGIN-LEFT: 0px; COLOR: #000000; FONT-FAMILY: Verdana; BACKGROUND-COLOR: white}}P{{MARGIN-TOP: 0px; MARGIN-BOTTOM: 12px; COLOR: #000000; FONT-FAMILY: Verdana}}PRE{{BORDER-RIGHT: #f0f0e0 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #f0f0e0 1px solid; MARGIN-TOP: -5px; PADDING-LEFT: 5px; FONT-SIZE: 1.2em; PADDING-BOTTOM: 5px; BORDER-LEFT: #f0f0e0 1px solid; PADDING-TOP: 5px; BORDER-BOTTOM: #f0f0e0 1px solid; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e5e5cc}}.heading1{{MARGIN-TOP: 0px; PADDING-LEFT: 15px; FONT-WEIGHT: normal; FONT-SIZE: 26px; MARGIN-BOTTOM: 0px; PADDING-BOTTOM: 3px; MARGIN-LEFT: -30px; WIDTH: 100%; COLOR: #ffffff; PADDING-TOP: 10px; FONT-FAMILY: Tahoma; BACKGROUND-COLOR: #003366}}.intro{{MARGIN-LEFT: -15px}}</STYLE> <TITLE>Service</TITLE>")); writer.WriteEndElement(); //HEAD writer.WriteRaw(String.Format(CultureInfo.InvariantCulture, @"<BODY> <DIV id=""content""> <P class=""heading1"">Service</P> <BR/> <P class=""intro"">{0}</P> <PRE> <font color=""blue"">&lt;<font color=""darkred"">" + ConfigurationStrings.BehaviorsSectionName + @"</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">" + ConfigurationStrings.ServiceBehaviors + @"</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">" + ConfigurationStrings.Behavior + @" </font><font color=""red"">" + ConfigurationStrings.Name + @"</font>=<font color=""black"">""</font>MyServiceTypeBehaviors<font color=""black"">"" </font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">" + ConfigurationStrings.ServiceMetadataPublishingSectionName + @" </font><font color=""red"">" + ConfigurationStrings.HttpGetEnabled + @"</font>=<font color=""black"">""</font>true<font color=""black"">"" </font>/&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">/" + ConfigurationStrings.Behavior + @"</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">/" + ConfigurationStrings.ServiceBehaviors + @"</font>&gt;</font> <font color=""blue"">&lt;<font color=""darkred"">/" + ConfigurationStrings.BehaviorsSectionName + @"</font>&gt;</font> </PRE> <P class=""intro"">{1}</P> <PRE> <font color=""blue"">&lt;<font color=""darkred"">" + ConfigurationStrings.Service + @" </font><font color=""red"">" + ConfigurationStrings.Name + @"</font>=<font color=""black"">""</font><i>MyNamespace.MyServiceType</i><font color=""black"">"" </font><font color=""red"">" + ConfigurationStrings.BehaviorConfiguration + @"</font>=<font color=""black"">""</font><i>MyServiceTypeBehaviors</i><font color=""black"">"" </font>&gt;</font> </PRE> <P class=""intro"">{2}</P> <PRE> <font color=""blue"">&lt;<font color=""darkred"">" + ConfigurationStrings.Endpoint + @" </font><font color=""red"">" + ConfigurationStrings.Contract + @"</font>=<font color=""black"">""</font>" + ServiceMetadataBehavior.MexContractName + @"<font color=""black"">"" </font><font color=""red"">" + ConfigurationStrings.Binding + @"</font>=<font color=""black"">""</font>mexHttpBinding<font color=""black"">"" </font><font color=""red"">" + ConfigurationStrings.Address + @"</font>=<font color=""black"">""</font>mex<font color=""black"">"" </font>/&gt;</font> </PRE> <P class=""intro"">{3}</P> <PRE> <font color=""blue"">&lt;<font color=""darkred"">configuration</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">" + ConfigurationStrings.SectionGroupName + @"</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">" + ConfigurationStrings.ServicesSectionName + @"</font>&gt;</font> <font color=""blue""> &lt;!-- <font color=""green"">{4}</font> --&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">" + ConfigurationStrings.Service + @" </font><font color=""red"">" + ConfigurationStrings.Name + @"</font>=<font color=""black"">""</font><i>MyNamespace.MyServiceType</i><font color=""black"">"" </font><font color=""red"">" + ConfigurationStrings.BehaviorConfiguration + @"</font>=<font color=""black"">""</font><i>MyServiceTypeBehaviors</i><font color=""black"">"" </font>&gt;</font> <font color=""blue""> &lt;!-- <font color=""green"">{5}</font> --&gt;</font> <font color=""blue""> &lt;!-- <font color=""green"">{6}</font> --&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">" + ConfigurationStrings.Endpoint + @" </font><font color=""red"">" + ConfigurationStrings.Contract + @"</font>=<font color=""black"">""</font>" + ServiceMetadataBehavior.MexContractName + @"<font color=""black"">"" </font><font color=""red"">" + ConfigurationStrings.Binding + @"</font>=<font color=""black"">""</font>mexHttpBinding<font color=""black"">"" </font><font color=""red"">" + ConfigurationStrings.Address + @"</font>=<font color=""black"">""</font>mex<font color=""black"">"" </font>/&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">/" + ConfigurationStrings.Service + @"</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">/" + ConfigurationStrings.ServicesSectionName + @"</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">" + ConfigurationStrings.BehaviorsSectionName + @"</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">" + ConfigurationStrings.ServiceBehaviors + @"</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">" + ConfigurationStrings.Behavior + @" </font><font color=""red"">name</font>=<font color=""black"">""</font><i>MyServiceTypeBehaviors</i><font color=""black"">"" </font>&gt;</font> <font color=""blue""> &lt;!-- <font color=""green"">{7}</font> --&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">" + ConfigurationStrings.ServiceMetadataPublishingSectionName + @" </font><font color=""red"">" + ConfigurationStrings.HttpGetEnabled + @"</font>=<font color=""black"">""</font>true<font color=""black"">"" </font>/&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">/" + ConfigurationStrings.Behavior + @"</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">/" + ConfigurationStrings.ServiceBehaviors + @"</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">/" + ConfigurationStrings.BehaviorsSectionName + @"</font>&gt;</font> <font color=""blue""> &lt;<font color=""darkred"">/" + ConfigurationStrings.SectionGroupName + @"</font>&gt;</font> <font color=""blue"">&lt;<font color=""darkred"">/configuration</font>&gt;</font> </PRE> <P class=""intro"">{8}</P> </DIV> </BODY>", SR.GetString(SR.SFxDocExt_NoMetadataSection1), SR.GetString(SR.SFxDocExt_NoMetadataSection2), SR.GetString(SR.SFxDocExt_NoMetadataSection3), SR.GetString(SR.SFxDocExt_NoMetadataSection4), SR.GetString(SR.SFxDocExt_NoMetadataConfigComment1), SR.GetString(SR.SFxDocExt_NoMetadataConfigComment2), SR.GetString(SR.SFxDocExt_NoMetadataConfigComment3), SR.GetString(SR.SFxDocExt_NoMetadataConfigComment4), SR.GetString(SR.SFxDocExt_NoMetadataSection5) )); writer.WriteEndElement(); //HTML } } class ServiceDescriptionMessage : ContentOnlyMessage { WsdlNS.ServiceDescription description; WriteFilter responseWriter; public ServiceDescriptionMessage(WsdlNS.ServiceDescription description, WriteFilter responseWriter) : base() { this.description = description; this.responseWriter = responseWriter; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { this.responseWriter.Writer = writer; description.Write(this.responseWriter); } } class XmlSchemaMessage : ContentOnlyMessage { XmlSchema schema; WriteFilter responseWriter; public XmlSchemaMessage(XmlSchema schema, WriteFilter responseWriter) : base() { this.schema = schema; this.responseWriter = responseWriter; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { this.responseWriter.Writer = writer; schema.Write(responseWriter); } } #endregion //Helper Message implementations } internal abstract class WriteFilter : XmlDictionaryWriter { internal XmlWriter Writer; public abstract WriteFilter CloneWriteFilter(); public override void Close() { this.Writer.Close(); } public override void Flush() { this.Writer.Flush(); } public override string LookupPrefix(string ns) { return this.Writer.LookupPrefix(ns); } public override void WriteBase64(byte[] buffer, int index, int count) { this.Writer.WriteBase64(buffer, index, count); } public override void WriteCData(string text) { this.Writer.WriteCData(text); } public override void WriteCharEntity(char ch) { this.Writer.WriteCharEntity(ch); } public override void WriteChars(char[] buffer, int index, int count) { this.Writer.WriteChars(buffer, index, count); } public override void WriteComment(string text) { this.Writer.WriteComment(text); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { this.Writer.WriteDocType(name, pubid, sysid, subset); } public override void WriteEndAttribute() { this.Writer.WriteEndAttribute(); } public override void WriteEndDocument() { this.Writer.WriteEndDocument(); } public override void WriteEndElement() { this.Writer.WriteEndElement(); } public override void WriteEntityRef(string name) { this.Writer.WriteEntityRef(name); } public override void WriteFullEndElement() { this.Writer.WriteFullEndElement(); } public override void WriteProcessingInstruction(string name, string text) { this.Writer.WriteProcessingInstruction(name, text); } public override void WriteRaw(string data) { this.Writer.WriteRaw(data); } public override void WriteRaw(char[] buffer, int index, int count) { this.Writer.WriteRaw(buffer, index, count); } public override void WriteStartAttribute(string prefix, string localName, string ns) { this.Writer.WriteStartAttribute(prefix, localName, ns); } public override void WriteStartDocument(bool standalone) { this.Writer.WriteStartDocument(standalone); } public override void WriteStartDocument() { this.Writer.WriteStartDocument(); } public override void WriteStartElement(string prefix, string localName, string ns) { this.Writer.WriteStartElement(prefix, localName, ns); } public override WriteState WriteState { get { return this.Writer.WriteState; } } public override void WriteString(string text) { this.Writer.WriteString(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { this.Writer.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteWhitespace(string ws) { this.Writer.WriteWhitespace(ws); } } class LocationUpdatingWriter : WriteFilter { readonly string oldValue; readonly string newValue; // passing null for newValue filters any string with oldValue as a prefix rather than replacing internal LocationUpdatingWriter(string oldValue, string newValue) { this.oldValue = oldValue; this.newValue = newValue; } public override WriteFilter CloneWriteFilter() { return new LocationUpdatingWriter(oldValue, newValue); } public override void WriteString(string text) { if (this.newValue != null) text = text.Replace(this.oldValue, this.newValue); else if (text.StartsWith(this.oldValue, StringComparison.Ordinal)) text = String.Empty; base.WriteString(text); } } class DynamicAddressUpdateWriter : WriteFilter { readonly string oldHostName; readonly string newHostName; readonly string newBaseAddress; readonly bool removeBaseAddress; readonly string requestScheme; readonly int requestPort; readonly IDictionary<string, int> updatePortsByScheme; internal DynamicAddressUpdateWriter(Uri listenUri, string requestHost, int requestPort, IDictionary<string, int> updatePortsByScheme, bool removeBaseAddress) : this(listenUri.Host, requestHost, removeBaseAddress, listenUri.Scheme, requestPort, updatePortsByScheme) { this.newBaseAddress = UpdateUri(listenUri).ToString(); } DynamicAddressUpdateWriter(string oldHostName, string newHostName, string newBaseAddress, bool removeBaseAddress, string requestScheme, int requestPort, IDictionary<string, int> updatePortsByScheme) : this(oldHostName, newHostName, removeBaseAddress, requestScheme, requestPort, updatePortsByScheme) { this.newBaseAddress = newBaseAddress; } DynamicAddressUpdateWriter(string oldHostName, string newHostName, bool removeBaseAddress, string requestScheme, int requestPort, IDictionary<string, int> updatePortsByScheme) { this.oldHostName = oldHostName; this.newHostName = newHostName; this.removeBaseAddress = removeBaseAddress; this.requestScheme = requestScheme; this.requestPort = requestPort; this.updatePortsByScheme = updatePortsByScheme; } public override WriteFilter CloneWriteFilter() { return new DynamicAddressUpdateWriter(this.oldHostName, this.newHostName, this.newBaseAddress, this.removeBaseAddress, this.requestScheme, this.requestPort, this.updatePortsByScheme); } public override void WriteString(string text) { Uri uri; if (this.removeBaseAddress && text.StartsWith(ServiceMetadataExtension.BaseAddressPattern, StringComparison.Ordinal)) { text = string.Empty; } else if (!this.removeBaseAddress && text.Contains(ServiceMetadataExtension.BaseAddressPattern)) { text = text.Replace(ServiceMetadataExtension.BaseAddressPattern, this.newBaseAddress); } else if (Uri.TryCreate(text, UriKind.Absolute, out uri)) { Uri newUri = UpdateUri(uri); if (newUri != null) { text = newUri.ToString(); } } base.WriteString(text); } public void UpdateUri(ref Uri uri, bool updateBaseAddressOnly = false) { Uri newUri = UpdateUri(uri, updateBaseAddressOnly); if (newUri != null) { uri = newUri; } } Uri UpdateUri(Uri uri, bool updateBaseAddressOnly = false) { // Ordinal comparison okay: we're filtering for auto-generated URIs which will // always be based off the listenURI, so always match in case if (uri.Host != oldHostName) { return null; } UriBuilder result = new UriBuilder(uri); result.Host = this.newHostName; if (!updateBaseAddressOnly) { int port; if (uri.Scheme == this.requestScheme) { port = requestPort; } else if (!this.updatePortsByScheme.TryGetValue(uri.Scheme, out port)) { return null; } result.Port = port; } return result.Uri; } } } }
using Newtonsoft.Json; using TypedRest.Endpoints.Rpc; namespace TypedRest.Endpoints; [Collection("Endpoint")] public class CustomEndpointTest : EndpointTestBase { private readonly CustomEndpoint _endpoint; public CustomEndpointTest() { _endpoint = new(EntryEndpoint, "endpoint"); } [Fact] public async Task TestAcceptHeader() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .WithHeaders("Accept", JsonMime) .Respond(_ => new StringContent("{}")); await _endpoint.GetAsync(); } [Fact] public async Task TestAllowHeader() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new StringContent("") {Headers = {Allow = {HttpMethod.Put.Method, HttpMethod.Post.Method}}}); await _endpoint.GetAsync(); _endpoint.IsMethodAllowed(HttpMethod.Put).Should().BeTrue(); _endpoint.IsMethodAllowed(HttpMethod.Post).Should().BeTrue(); _endpoint.IsMethodAllowed(HttpMethod.Delete).Should().BeFalse(); } [Fact] public async Task TestLink() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.NoContent) { Headers = { {"Link", "<a>; rel=target1, <b>; rel=target2"} } }); await _endpoint.GetAsync(); _endpoint.Link("target1").Should().Be(new Uri("http://localhost/a")); _endpoint.Link("target2").Should().Be(new Uri("http://localhost/b")); } [Fact] public void TestLinkLazy() { Mock.Expect(HttpMethod.Head, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.NoContent) { Headers = { {"Link", "<a>; rel=target1, <b>; rel=target2"} } }); _endpoint.Link("target1").Should().Be(new Uri("http://localhost/a")); _endpoint.Link("target2").Should().Be(new Uri("http://localhost/b")); } [Fact] public async Task TestLinkAbsolute() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.NoContent) { Headers = { {"Link", "<http://localhost/b>; rel=target1"} } }); await _endpoint.GetAsync(); _endpoint.Link("target1").Should().Be(new Uri("http://localhost/b")); } [Fact] public void TestLinkException() { Mock.Expect(HttpMethod.Head, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.NoContent) { Headers = {{"Link", "<a>; rel=target1"}} }); Assert.Throws<KeyNotFoundException>(() => _endpoint.Link("target2")); } [Fact] public async Task TestGetLinks() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.NoContent) { Headers = { {"Link", "<target1>; rel=child; title=Title"}, {"Link", "<target2>; rel=child"} } }); await _endpoint.GetAsync(); _endpoint.GetLinks("child").Should().BeEquivalentTo(new[] { (new Uri("http://localhost/target1"), "Title"), (new Uri("http://localhost/target2"), (string?)null) }); } [Fact] public async Task TestGetLinksEscaping() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.NoContent) { Headers = { {"Link", "<target1>; rel=child; title=\"Title,= 1\", <target2>; rel=child"} } }); await _endpoint.GetAsync(); _endpoint.GetLinks("child").Should().BeEquivalentTo(new[] { (new Uri("http://localhost/target1"), "Title,= 1"), (new Uri("http://localhost/target2"), (string?)null) }); } [Fact] public void TestSetDefaultLink() { _endpoint.SetDefaultLink(rel: "child", "target"); _endpoint.Link("child").Should().Be(new Uri("http://localhost/target")); } [Fact] public async Task TestLinkTemplate() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.NoContent) { Headers = { {"Link", "<a{?x}>; rel=child; templated=true"} } }); await _endpoint.GetAsync(); _endpoint.GetLinkTemplate("child").ToString().Should().Be("a{?x}"); } [Fact] public async Task TestLinkTemplateResolve() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.NoContent) { Headers = { {"Link", "<a{?x}>; rel=child; templated=true"} } }); await _endpoint.GetAsync(); _endpoint.LinkTemplate("child", new {x = "1"}).Should().Be(new Uri("http://localhost/a?x=1")); } [Fact] public async Task TestLinkTemplateResolveAbsolute() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.NoContent) { Headers = { {"Link", "<http://localhost/b{?x}>; rel=child; templated=true"} } }); await _endpoint.GetAsync(); _endpoint.LinkTemplate("child", new {x = "1"}).Should().Be(new Uri("http://localhost/b?x=1")); } [Fact] public async Task TestLinkTemplateResolveQuery() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.NoContent) { Headers = { {"Link", "<http://localhost/b{?x,y}>; rel=search; templated=true"} } }); await _endpoint.GetAsync(); _endpoint.LinkTemplate("search", new {x = "1", y = "2"}).Should().Be(new Uri("http://localhost/b?x=1&y=2")); } [Fact] public void TestLinkTemplateException() { Mock.Expect(HttpMethod.Head, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.NoContent) { Headers = { {"Link", "<a>; rel=child; templated=true"} } }); Assert.Throws<KeyNotFoundException>(() => _endpoint.GetLinkTemplate("child2")); } [Fact] public async Task TestLinkHal() { string body = JsonConvert.SerializeObject(new { _links = new { single = new {href = "a"}, collection = new object[] {new {href = "b", title = "Title 1"}, new {href = "c"}}, template = new {href = "{id}", templated = true} } }); Mock.Expect(HttpMethod.Get, "http://localhost/endpoint").Respond("application/hal+json", body); await _endpoint.GetAsync(); _endpoint.Link("single").Should().Be(new Uri("http://localhost/a")); _endpoint.GetLinks("collection").Should().BeEquivalentTo(new[] { (new Uri("http://localhost/b"), "Title 1"), (new Uri("http://localhost/c"), (string?)null) }); _endpoint.GetLinkTemplate("template").ToString().Should().Be("{id}"); } [Fact] public void TestSetDefaultLinkTemplate() { _endpoint.SetDefaultLinkTemplate(rel: "child", href: "a"); _endpoint.GetLinkTemplate("child").ToString().Should().Be("a"); } [Fact] public void TestEnsureTrailingSlashOnReferrerUri() { new ActionEndpoint(_endpoint, "subresource").Uri.Should().Be(new Uri("http://localhost/subresource")); new ActionEndpoint(_endpoint, "./subresource").Uri.Should().Be(new Uri("http://localhost/endpoint/subresource")); } private class CustomEndpoint : EndpointBase { public CustomEndpoint(IEndpoint referrer, string relativeUri) : base(referrer, relativeUri) {} public Task GetAsync() => FinalizeAsync(() => HttpClient.GetAsync(Uri)); public new bool? IsMethodAllowed(HttpMethod method) => base.IsMethodAllowed(method); } [Fact] public async Task TestErrorHandlingWithNoContent() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.Conflict)); await _endpoint.Awaiting(x => x.GetAsync()) .Should().ThrowAsync<InvalidOperationException>() .WithMessage("http://localhost/endpoint responded with 409 Conflict"); } [Fact] public async Task TestErrorHandlingWithMessage() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.Conflict) { Content = new StringContent("{\"message\":\"my message\"}") { Headers = {ContentType = MediaTypeHeaderValue.Parse(JsonMime)} } }); await _endpoint.Awaiting(x => x.GetAsync()) .Should().ThrowAsync<InvalidOperationException>() .WithMessage("my message"); } [Fact] public async Task TestErrorHandlingWithArray() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.Conflict) { Content = new StringContent("[{\"message\":\"my message\"}]") { Headers = {ContentType = MediaTypeHeaderValue.Parse(JsonMime)} } }); await _endpoint.Awaiting(x => x.GetAsync()) .Should().ThrowAsync<InvalidOperationException>() .WithMessage("http://localhost/endpoint responded with 409 Conflict"); } [Fact] public void TestErrorHandlingWithUnknownContentType() { Mock.Expect(HttpMethod.Get, "http://localhost/endpoint") .Respond(_ => new(HttpStatusCode.Conflict) {Content = new ByteArrayContent(new byte[0])}); _endpoint.Awaiting(x => x.GetAsync()) .Should().ThrowAsync<InvalidOperationException>() .WithMessage("http://localhost/endpoint responded with 409 Conflict"); } }
// 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.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public abstract partial class ImmutableDictionaryBuilderTestBase : ImmutablesTestBase { [Fact] public void Add() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); builder.Add(new KeyValuePair<string, int>("six", 6)); Assert.Equal(5, builder["five"]); Assert.Equal(6, builder["six"]); Assert.False(builder.ContainsKey("four")); } /// <summary> /// Verifies that "adding" an entry to the dictionary that already exists /// with exactly the same key and value will *not* throw an exception. /// </summary> /// <remarks> /// The BCL Dictionary type would throw in this circumstance. /// But in an immutable world, not only do we not care so much since the result is the same. /// </remarks> [Fact] public void AddExactDuplicate() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); builder.Add("five", 5); Assert.Equal(1, builder.Count); } [Fact] public void AddExistingKeyWithDifferentValue() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); AssertExtensions.Throws<ArgumentException>(null, () => builder.Add("five", 6)); } [Fact] public void Indexer() { var builder = this.GetBuilder<string, int>(); // Set and set again. builder["five"] = 5; Assert.Equal(5, builder["five"]); builder["five"] = 5; Assert.Equal(5, builder["five"]); // Set to a new value. builder["five"] = 50; Assert.Equal(50, builder["five"]); // Retrieve an invalid value. Assert.Throws<KeyNotFoundException>(() => builder["foo"]); } [Fact] public void ContainsPair() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5); var builder = this.GetBuilder(map); Assert.True(builder.Contains(new KeyValuePair<string, int>("five", 5))); } [Fact] public void RemovePair() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); Assert.True(builder.Remove(new KeyValuePair<string, int>("five", 5))); Assert.False(builder.Remove(new KeyValuePair<string, int>("foo", 1))); Assert.Equal(1, builder.Count); Assert.Equal(6, builder["six"]); } [Fact] public void RemoveKey() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); builder.Remove("five"); Assert.Equal(1, builder.Count); Assert.Equal(6, builder["six"]); } [Fact] public void CopyTo() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5); var builder = this.GetBuilder(map); var array = new KeyValuePair<string, int>[2]; // intentionally larger than source. builder.CopyTo(array, 1); Assert.Equal(new KeyValuePair<string, int>(), array[0]); Assert.Equal(new KeyValuePair<string, int>("five", 5), array[1]); AssertExtensions.Throws<ArgumentNullException>("array", () => builder.CopyTo(null, 0)); } [Fact] public void IsReadOnly() { var builder = this.GetBuilder<string, int>(); Assert.False(builder.IsReadOnly); } [Fact] public void Keys() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); CollectionAssertAreEquivalent(new[] { "five", "six" }, builder.Keys); CollectionAssertAreEquivalent(new[] { "five", "six" }, ((IReadOnlyDictionary<string, int>)builder).Keys.ToArray()); } [Fact] public void Values() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); CollectionAssertAreEquivalent(new[] { 5, 6 }, builder.Values); CollectionAssertAreEquivalent(new[] { 5, 6 }, ((IReadOnlyDictionary<string, int>)builder).Values.ToArray()); } [Fact] public void TryGetValue() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); int value; Assert.True(builder.TryGetValue("five", out value) && value == 5); Assert.True(builder.TryGetValue("six", out value) && value == 6); Assert.False(builder.TryGetValue("four", out value)); Assert.Equal(0, value); } [Fact] public void EnumerateTest() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); using (var enumerator = builder.GetEnumerator()) { Assert.True(enumerator.MoveNext()); Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); } var manualEnum = builder.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); while (manualEnum.MoveNext()) { } Assert.False(manualEnum.MoveNext()); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); } [Fact] public void IDictionaryMembers() { var builder = this.GetBuilder<string, int>(); var dictionary = (IDictionary)builder; dictionary.Add("a", 1); Assert.True(dictionary.Contains("a")); Assert.Equal(1, dictionary["a"]); Assert.Equal(new[] { "a" }, dictionary.Keys.Cast<string>().ToArray()); Assert.Equal(new[] { 1 }, dictionary.Values.Cast<int>().ToArray()); dictionary["a"] = 2; Assert.Equal(2, dictionary["a"]); dictionary.Remove("a"); Assert.False(dictionary.Contains("a")); Assert.False(dictionary.IsFixedSize); Assert.False(dictionary.IsReadOnly); } [Fact] public void IDictionaryEnumerator() { var builder = this.GetBuilder<string, int>(); var dictionary = (IDictionary)builder; dictionary.Add("a", 1); var enumerator = dictionary.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Entry, enumerator.Current); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.False(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key); Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.False(enumerator.MoveNext()); } [Fact] public void ICollectionMembers() { var builder = this.GetBuilder<string, int>(); var collection = (ICollection)builder; collection.CopyTo(new object[0], 0); builder.Add("b", 2); Assert.True(builder.ContainsKey("b")); var array = new object[builder.Count + 1]; collection.CopyTo(array, 1); Assert.Null(array[0]); Assert.Equal(new object[] { null, new DictionaryEntry("b", 2), }, array); Assert.False(collection.IsSynchronized); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } protected abstract bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey); /// <summary> /// Gets the Builder for a given dictionary instance. /// </summary> /// <typeparam name="TKey">The type of key.</typeparam> /// <typeparam name="TValue">The type of value.</typeparam> /// <returns>The builder.</returns> protected abstract IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue> basis = null); /// <summary> /// Gets an empty immutable dictionary. /// </summary> /// <typeparam name="TKey">The type of key.</typeparam> /// <typeparam name="TValue">The type of value.</typeparam> /// <returns>The immutable dictionary.</returns> protected abstract IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>(); protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Tests { public static class ValueTypeTests { [Fact] public static void ToStringTest() { object obj = new S(); Assert.Equal(obj.ToString(), obj.GetType().ToString()); Assert.Equal("System.Tests.ValueTypeTests+S", obj.ToString()); } [Fact] public static void StructWithDoubleFieldNotTightlyPackedZeroCompareTest() { StructWithDoubleFieldNotTightlyPacked obj1 = new StructWithDoubleFieldNotTightlyPacked(); obj1.value1 = 1; obj1.value2 = 0.0; StructWithDoubleFieldNotTightlyPacked obj2 = new StructWithDoubleFieldNotTightlyPacked(); obj2.value1 = 1; obj2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithDoubleFieldTightlyPackedZeroCompareTest() { StructWithDoubleFieldTightlyPacked obj1 = new StructWithDoubleFieldTightlyPacked(); obj1.value1 = 1; obj1.value2 = 0.0; StructWithDoubleFieldTightlyPacked obj2 = new StructWithDoubleFieldTightlyPacked(); obj2.value1 = 1; obj2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithDoubleFieldNotTightlyPackedNaNCompareTest() { StructWithDoubleFieldNotTightlyPacked obj1 = new StructWithDoubleFieldNotTightlyPacked(); obj1.value1 = 1; obj1.value2 = double.NaN; StructWithDoubleFieldNotTightlyPacked obj2 = new StructWithDoubleFieldNotTightlyPacked(); obj2.value1 = 1; obj2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithDoubleFieldTightlyPackedNaNCompareTest() { StructWithDoubleFieldTightlyPacked obj1 = new StructWithDoubleFieldTightlyPacked(); obj1.value1 = 1; obj1.value2 = double.NaN; StructWithDoubleFieldTightlyPacked obj2 = new StructWithDoubleFieldTightlyPacked(); obj2.value1 = 1; obj2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldNotTightlyPackedZeroCompareTest() { StructWithDoubleFieldNestedNotTightlyPacked obj1 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = 0.0; StructWithDoubleFieldNestedNotTightlyPacked obj2 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldTightlyPackedZeroCompareTest() { StructWithDoubleFieldNestedTightlyPacked obj1 = new StructWithDoubleFieldNestedTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = 0.0; StructWithDoubleFieldNestedTightlyPacked obj2 = new StructWithDoubleFieldNestedTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldNotTightlyPackedNaNCompareTest() { StructWithDoubleFieldNestedNotTightlyPacked obj1 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = double.NaN; StructWithDoubleFieldNestedNotTightlyPacked obj2 = new StructWithDoubleFieldNestedNotTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedDoubleFieldTightlyPackedNaNCompareTest() { StructWithDoubleFieldNestedTightlyPacked obj1 = new StructWithDoubleFieldNestedTightlyPacked(); obj1.value1.value1 = 1; obj1.value2.value2 = double.NaN; StructWithDoubleFieldNestedTightlyPacked obj2 = new StructWithDoubleFieldNestedTightlyPacked(); obj2.value1.value1 = 1; obj2.value2.value2 = -double.NaN; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldNotTightlyPackedZeroCompareTest() { StructWithFloatFieldNotTightlyPacked obj1 = new StructWithFloatFieldNotTightlyPacked(); obj1.value1 = 0.0f; obj1.value2 = 1; StructWithFloatFieldNotTightlyPacked obj2 = new StructWithFloatFieldNotTightlyPacked(); obj2.value1 = -0.0f; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldTightlyPackedZeroCompareTest() { StructWithFloatFieldTightlyPacked obj1 = new StructWithFloatFieldTightlyPacked(); obj1.value1 = 0.0f; obj1.value2 = 1; StructWithFloatFieldTightlyPacked obj2 = new StructWithFloatFieldTightlyPacked(); obj2.value1 = -0.0f; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldNotTightlyPackedNaNCompareTest() { StructWithFloatFieldNotTightlyPacked obj1 = new StructWithFloatFieldNotTightlyPacked(); obj1.value1 = float.NaN; obj1.value2 = 1; StructWithFloatFieldNotTightlyPacked obj2 = new StructWithFloatFieldNotTightlyPacked(); obj2.value1 = -float.NaN; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithFloatFieldTightlyPackedNaNCompareTest() { StructWithFloatFieldTightlyPacked obj1 = new StructWithFloatFieldTightlyPacked(); obj1.value1 = float.NaN; obj1.value2 = 1; StructWithFloatFieldTightlyPacked obj2 = new StructWithFloatFieldTightlyPacked(); obj2.value1 = -float.NaN; obj2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldNotTightlyPackedZeroCompareTest() { StructWithFloatFieldNestedNotTightlyPacked obj1 = new StructWithFloatFieldNestedNotTightlyPacked(); obj1.value1.value1 = 0.0f; obj1.value2.value2 = 1; StructWithFloatFieldNestedNotTightlyPacked obj2 = new StructWithFloatFieldNestedNotTightlyPacked(); obj2.value1.value1 = -0.0f; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldTightlyPackedZeroCompareTest() { StructWithFloatFieldNestedTightlyPacked obj1 = new StructWithFloatFieldNestedTightlyPacked(); obj1.value1.value1 = 0.0f; obj1.value2.value2 = 1; StructWithFloatFieldNestedTightlyPacked obj2 = new StructWithFloatFieldNestedTightlyPacked(); obj2.value1.value1 = -0.0f; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldNotTightlyPackedNaNCompareTest() { StructWithFloatFieldNestedNotTightlyPacked obj1 = new StructWithFloatFieldNestedNotTightlyPacked(); obj1.value1.value1 = float.NaN; obj1.value2.value2 = 1; StructWithFloatFieldNestedNotTightlyPacked obj2 = new StructWithFloatFieldNestedNotTightlyPacked(); obj2.value1.value1 = -float.NaN; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedFloatFieldTightlyPackedNaNCompareTest() { StructWithFloatFieldNestedTightlyPacked obj1 = new StructWithFloatFieldNestedTightlyPacked(); obj1.value1.value1 = float.NaN; obj1.value2.value2 = 1; StructWithFloatFieldNestedTightlyPacked obj2 = new StructWithFloatFieldNestedTightlyPacked(); obj2.value1.value1 = -float.NaN; obj2.value2.value2 = 1; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithoutNestedOverriddenEqualsCompareTest() { StructWithoutNestedOverriddenEqualsAndGetHashCode obj1 = new StructWithoutNestedOverriddenEqualsAndGetHashCode(); obj1.value1.value = 1; obj1.value2.value = 2; StructWithoutNestedOverriddenEqualsAndGetHashCode obj2 = new StructWithoutNestedOverriddenEqualsAndGetHashCode(); obj2.value1.value = 1; obj2.value2.value = 2; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructWithNestedOverriddenEqualsCompareTest() { StructWithNestedOverriddenEqualsAndGetHashCode obj1 = new StructWithNestedOverriddenEqualsAndGetHashCode(); obj1.value1.value = 1; obj1.value2.value = 2; StructWithNestedOverriddenEqualsAndGetHashCode obj2 = new StructWithNestedOverriddenEqualsAndGetHashCode(); obj2.value1.value = 1; obj2.value2.value = 2; Assert.False(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } [Fact] public static void StructContainsPointerCompareTest() { StructContainsPointer obj1 = new StructContainsPointer(); obj1.value1 = 1; obj1.value2 = 0.0; StructContainsPointer obj2 = new StructContainsPointer(); obj2.value1 = 1; obj2.value2 = -0.0; Assert.True(obj1.Equals(obj2)); Assert.Equal(obj1.GetHashCode(), obj2.GetHashCode()); } public struct S { public int x; public int y; } public struct StructWithDoubleFieldNotTightlyPacked { public int value1; public double value2; } public struct StructWithDoubleFieldTightlyPacked { public double value1; public double value2; } public struct StructWithDoubleFieldNestedNotTightlyPacked { public StructWithDoubleFieldNotTightlyPacked value1; public StructWithDoubleFieldNotTightlyPacked value2; } public struct StructWithDoubleFieldNestedTightlyPacked { public StructWithDoubleFieldTightlyPacked value1; public StructWithDoubleFieldTightlyPacked value2; } public struct StructWithFloatFieldNotTightlyPacked { public float value1; public long value2; } public struct StructWithFloatFieldTightlyPacked { public float value1; public float value2; } public struct StructWithFloatFieldNestedNotTightlyPacked { public StructWithFloatFieldNotTightlyPacked value1; public StructWithFloatFieldNotTightlyPacked value2; } public struct StructWithFloatFieldNestedTightlyPacked { public StructWithFloatFieldTightlyPacked value1; public StructWithFloatFieldTightlyPacked value2; } public struct StructNonOverriddenEqualsOrGetHasCode { public byte value; } public struct StructNeverEquals { public byte value; public override bool Equals(object obj) { return false; } public override int GetHashCode() { return 0; } } public struct StructWithoutNestedOverriddenEqualsAndGetHashCode { public StructNonOverriddenEqualsOrGetHasCode value1; public StructNonOverriddenEqualsOrGetHasCode value2; } public struct StructWithNestedOverriddenEqualsAndGetHashCode { public StructNeverEquals value1; public StructNeverEquals value2; } public struct StructContainsPointer { public string s; public double value1; public double value2; } } }
using System; using System.Collections.Concurrent; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Invio.Extensions.Reflection { /// <summary> /// A collections of extension methods on <see cref="ConstructorInfo" /> /// that allows the caller to cache the reflection-based objects into /// a delegate. This speeds up the instantiation of objects normally /// created from the extended <see cref="ConstructorInfo" />. /// </summary> public static class CachedDelegatesConstructorInfoExtensions { private static ConcurrentDictionary<ConstructorInfo, Func<object[], object>> untypedArrays { get; } private static ConcurrentDictionary<Tuple<Type, ConstructorInfo>, object> typedArrays { get; } private static ConcurrentDictionary<ConstructorInfo, object> untypedFuncs { get; } private static ConcurrentDictionary<Tuple<Type, ConstructorInfo>, object> typedFuncs { get; } static CachedDelegatesConstructorInfoExtensions() { untypedArrays = new ConcurrentDictionary<ConstructorInfo, Func<object[], object>>(); typedArrays = new ConcurrentDictionary<Tuple<Type, ConstructorInfo>, object>(); untypedFuncs = new ConcurrentDictionary<ConstructorInfo, object>(); typedFuncs = new ConcurrentDictionary<Tuple<Type, ConstructorInfo>, object>(); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via the <see cref="MemberInfo.DeclaringType" /> property on /// <see cref="ConstructorInfo" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object[], object> CreateArrayFunc(this ConstructorInfo constructor) { if (constructor == null) { throw new ArgumentNullException(nameof(constructor)); } return untypedArrays.GetOrAdd(constructor, CreateArrayFuncImpl<object>); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via type parameter <typeparamref name="T" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <typeparam name="T"> /// The type of object that will be provided when the delegate that is returned /// from this method is invoked. /// </typeparam> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> references a different type /// in its <see cref="MemberInfo.DeclaringType" /> property than what /// was provided via the type parameter <typeparamref name="T" />. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object[], T> CreateArrayFunc<T>(this ConstructorInfo constructor) { CheckType<T>(constructor); return (Func<object[], T>)typedArrays.GetOrAdd( Tuple.Create(typeof(T), constructor), tuple => CreateArrayFuncImpl<T>(tuple.Item2) ); } private static Func<object[], T> CreateArrayFuncImpl<T>(ConstructorInfo constructor) { var array = Expression.Parameter(typeof(object[]), "array"); Func<ParameterInfo, int, Expression> toExpression = (ParameterInfo parameter, int index) => { return Expression.Convert( Expression.ArrayAccess(array, Expression.Constant(index)), parameter.ParameterType ); }; var parameters = constructor .GetParameters() .Select(toExpression) .ToArray(); var body = Expression.Block( Expression.IfThen( Expression.Equal(array, Expression.Constant(null, array.Type)), Expression.Throw( Expression.Constant( new ArgumentNullException(array.Name) ) ) ), Expression.IfThen( Expression.NotEqual( Expression.Property(array, typeof(object[]).GetProperty("Length")), Expression.Constant(parameters.Length) ), Expression.Throw( Expression.Constant( new ArgumentException( $"The '{array.Name}' argument must " + $"have {parameters.Length:N0} objects.", array.Name ) ) ) ), Expression.Convert( Expression.New(constructor, parameters), typeof(T) ) ); return Expression.Lambda<Func<object[], T>>(body, array).Compile(); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via the <see cref="MemberInfo.DeclaringType" /> property on /// <see cref="ConstructorInfo" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> isn't parameterless. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object> CreateFunc0(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 0); return CreateUntypedFunc<Func<object>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via type parameter <typeparamref name="T" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <typeparam name="T"> /// The type of object that will be provided when the delegate that is returned /// from this method is invoked. /// </typeparam> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> isn't parameterless. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> references a different type /// in its <see cref="MemberInfo.DeclaringType" /> property than what /// was provided via the type parameter <typeparamref name="T" />. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<T> CreateFunc0<T>(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 0); return CreateTypedFunc<T, Func<T>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via the <see cref="MemberInfo.DeclaringType" /> property on /// <see cref="ConstructorInfo" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 1 parameter. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object> CreateFunc1(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 1); return CreateUntypedFunc<Func<object, object>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via type parameter <typeparamref name="T" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <typeparam name="T"> /// The type of object that will be provided when the delegate that is returned /// from this method is invoked. /// </typeparam> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 1 parameter. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> references a different type /// in its <see cref="MemberInfo.DeclaringType" /> property than what /// was provided via the type parameter <typeparamref name="T" />. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, T> CreateFunc1<T>(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 1); return CreateTypedFunc<T, Func<object, T>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via the <see cref="MemberInfo.DeclaringType" /> property on /// <see cref="ConstructorInfo" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 2 parameters. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object> CreateFunc2(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 2); return CreateUntypedFunc<Func<object, object, object>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via type parameter <typeparamref name="T" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <typeparam name="T"> /// The type of object that will be provided when the delegate that is returned /// from this method is invoked. /// </typeparam> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 2 parameters. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> references a different type /// in its <see cref="MemberInfo.DeclaringType" /> property than what /// was provided via the type parameter <typeparamref name="T" />. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, T> CreateFunc2<T>(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 2); return CreateTypedFunc<T, Func<object, object, T>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via the <see cref="MemberInfo.DeclaringType" /> property on /// <see cref="ConstructorInfo" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 3 parameters. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object> CreateFunc3(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 3); return CreateUntypedFunc<Func<object, object, object, object>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via type parameter <typeparamref name="T" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <typeparam name="T"> /// The type of object that will be provided when the delegate that is returned /// from this method is invoked. /// </typeparam> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 3 parameters. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> references a different type /// in its <see cref="MemberInfo.DeclaringType" /> property than what /// was provided via the type parameter <typeparamref name="T" />. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, T> CreateFunc3<T>(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 3); return CreateTypedFunc<T, Func<object, object, object, T>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via the <see cref="MemberInfo.DeclaringType" /> property on /// <see cref="ConstructorInfo" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 4 parameters. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, object> CreateFunc4(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 4); return CreateUntypedFunc<Func<object, object, object, object, object>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via type parameter <typeparamref name="T" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <typeparam name="T"> /// The type of object that will be provided when the delegate that is returned /// from this method is invoked. /// </typeparam> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 4 parameters. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> references a different type /// in its <see cref="MemberInfo.DeclaringType" /> property than what /// was provided via the type parameter <typeparamref name="T" />. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, T> CreateFunc4<T>(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 4); return CreateTypedFunc<T, Func<object, object, object, object, T>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via the <see cref="MemberInfo.DeclaringType" /> property on /// <see cref="ConstructorInfo" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 5 parameters. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, object, object> CreateFunc5(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 5); return CreateUntypedFunc<Func<object, object, object, object, object, object>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via type parameter <typeparamref name="T" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <typeparam name="T"> /// The type of object that will be provided when the delegate that is returned /// from this method is invoked. /// </typeparam> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 5 parameters. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> references a different type /// in its <see cref="MemberInfo.DeclaringType" /> property than what /// was provided via the type parameter <typeparamref name="T" />. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, object, T> CreateFunc5<T>(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 5); return CreateTypedFunc<T, Func<object, object, object, object, object, T>>(constructor); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via the <see cref="MemberInfo.DeclaringType" /> property on /// <see cref="ConstructorInfo" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 6 parameters. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, object, object, object> CreateFunc6(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 6); return CreateUntypedFunc<Func<object, object, object, object, object, object, object>>( constructor ); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via type parameter <typeparamref name="T" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <typeparam name="T"> /// The type of object that will be provided when the delegate that is returned /// from this method is invoked. /// </typeparam> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 6 parameters. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> references a different type /// in its <see cref="MemberInfo.DeclaringType" /> property than what /// was provided via the type parameter <typeparamref name="T" />. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, object, object, T> CreateFunc6<T>(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 6); return CreateTypedFunc<T, Func<object, object, object, object, object, object, T>>( constructor ); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via the <see cref="MemberInfo.DeclaringType" /> property on /// <see cref="ConstructorInfo" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 7 parameters. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, object, object, object, object> CreateFunc7(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 7); return CreateUntypedFunc<Func<object, object, object, object, object, object, object, object>>( constructor ); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via type parameter <typeparamref name="T" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <typeparam name="T"> /// The type of object that will be provided when the delegate that is returned /// from this method is invoked. /// </typeparam> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 7 parameters. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> references a different type /// in its <see cref="MemberInfo.DeclaringType" /> property than what /// was provided via the type parameter <typeparamref name="T" />. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, object, object, object, T> CreateFunc7<T>(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 7); return CreateTypedFunc<T, Func<object, object, object, object, object, object, object, T>>( constructor ); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via the <see cref="MemberInfo.DeclaringType" /> property on /// <see cref="ConstructorInfo" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 8 parameters. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, object, object, object, object, object> CreateFunc8(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 8); return CreateUntypedFunc<Func<object, object, object, object, object, object, object, object, object>>( constructor ); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via type parameter <typeparamref name="T" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <typeparam name="T"> /// The type of object that will be provided when the delegate that is returned /// from this method is invoked. /// </typeparam> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 8 parameters. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> references a different type /// in its <see cref="MemberInfo.DeclaringType" /> property than what /// was provided via the type parameter <typeparamref name="T" />. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, object, object, object, object, T> CreateFunc8<T>(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 8); return CreateTypedFunc<T, Func<object, object, object, object, object, object, object, object, T>>( constructor ); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via the <see cref="MemberInfo.DeclaringType" /> property on /// <see cref="ConstructorInfo" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 9 parameters. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, object, object, object, object, object, object> CreateFunc9(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 9); return CreateUntypedFunc<Func<object, object, object, object, object, object, object, object, object, object>>( constructor ); } /// <summary> /// Return an efficient functor for the specified constructor which, when called, /// creates a new instance of the class that the <paramref name="constructor" /> /// references via type parameter <typeparamref name="T" />. /// </summary> /// <param name="constructor"> /// The <see cref="ConstructorInfo" /> instance the caller wants to turn into /// a compiled delegate that can be recalled efficiently. /// </param> /// <typeparam name="T"> /// The type of object that will be provided when the delegate that is returned /// from this method is invoked. /// </typeparam> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="constructor" /> is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> does not have 9 parameters. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="constructor" /> references a different type /// in its <see cref="MemberInfo.DeclaringType" /> property than what /// was provided via the type parameter <typeparamref name="T" />. /// </exception> /// <returns> /// A delegate that can called to efficiently create instances normally created /// by invoking the <paramref name="constructor" /> directly. /// </returns> public static Func<object, object, object, object, object, object, object, object, object, T> CreateFunc9<T>(this ConstructorInfo constructor) { CheckParameters(constructor, expected: 9); return CreateTypedFunc<T, Func<object, object, object, object, object, object, object, object, object, T>>( constructor ); } private static void CheckParameters(ConstructorInfo constructor, int expected) { if (constructor == null) { throw new ArgumentNullException(nameof(constructor)); } var parameters = constructor.GetParameters(); if (parameters.Length != expected) { throw new ArgumentException( $"The '{nameof(constructor)}' argument must reference a " + $"{typeof(ConstructorInfo).Name} with {expected:N0} parameters.", nameof(constructor) ); } } private static void CheckType<T>(ConstructorInfo constructor) { if (constructor == null) { throw new ArgumentNullException(nameof(constructor)); } if (!typeof(T).IsAssignableFrom(constructor.DeclaringType)) { throw new ArgumentException( $"Type parameter '{typeof(T).Name}' does not match the " + $"'{nameof(MemberInfo.DeclaringType)}' of the provided " + $"'{typeof(ConstructorInfo).Name}' object.", nameof(constructor) ); } } private static TFunc CreateTypedFunc<T, TFunc>(ConstructorInfo constructor) { CheckType<T>(constructor); return (TFunc)typedFuncs.GetOrAdd( Tuple.Create(typeof(T), constructor), tuple => CreateFuncImpl<T, TFunc>(tuple.Item2) ); } private static TFunc CreateUntypedFunc<TFunc>(ConstructorInfo constructor) { return (TFunc)untypedFuncs.GetOrAdd(constructor, CreateFuncImpl<object, TFunc>); } private static object CreateFuncImpl<T, TFunc>(ConstructorInfo constructor) { var parameters = constructor.GetParameters(); Func<ParameterInfo, int, ParameterExpression> toArgument = (info, index) => Expression.Parameter(typeof(object), $"argument{index}"); var arguments = parameters.Select(toArgument).ToArray(); Func<ParameterInfo, ParameterExpression, Expression> convert = (info, expression) => Expression.Convert(expression, info.ParameterType); var body = Expression.Convert( Expression.New( constructor, parameters .Zip(arguments, convert) .ToArray() ), typeof(T) ); return Expression.Lambda<TFunc>(body, arguments).Compile(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** ** Purpose: Generic hash table implementation ** ** #DictionaryVersusHashtableThreadSafety ** Hashtable has multiple reader/single writer (MR/SW) thread safety built into ** certain methods and properties, whereas Dictionary doesn't. If you're ** converting framework code that formerly used Hashtable to Dictionary, it's ** important to consider whether callers may have taken a dependence on MR/SW ** thread safety. If a reader writer lock is available, then that may be used ** with a Dictionary to get the same thread safety guarantee. ** ** Reader writer locks don't exist in silverlight, so we do the following as a ** result of removing non-generic collections from silverlight: ** 1. If the Hashtable was fully synchronized, then we replace it with a ** Dictionary with full locks around reads/writes (same thread safety ** guarantee). ** 2. Otherwise, the Hashtable has the default MR/SW thread safety behavior, ** so we do one of the following on a case-by-case basis: ** a. If the race condition can be addressed by rearranging the code and using a temp ** variable (for example, it's only populated immediately after created) ** then we address the race condition this way and use Dictionary. ** b. If there's concern about degrading performance with the increased ** locking, we ifdef with FEATURE_NONGENERIC_COLLECTIONS so we can at ** least use Hashtable in the desktop build, but Dictionary with full ** locks in silverlight builds. Note that this is heavier locking than ** MR/SW, but this is the only option without rewriting (or adding back) ** the reader writer lock. ** c. If there's no performance concern (e.g. debug-only code) we ** consistently replace Hashtable with Dictionary plus full locks to ** reduce complexity. ** d. Most of serialization is dead code in silverlight. Instead of updating ** those Hashtable occurences in serialization, we carved out references ** to serialization such that this code doesn't need to build in ** silverlight. ===========================================================*/ namespace System.Collections.Generic { using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Security.Permissions; [DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.InteropServices.ComVisible(false)] 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 version; private int freeList; private int freeCount; private IEqualityComparer<TKey> comparer; private KeyCollection keys; private ValueCollection values; private Object _syncRoot; // constants for serialization private const String VersionName = "Version"; private const String HashSizeName = "HashSize"; // Must save buckets.Length private const String KeyValuePairsName = "KeyValuePairs"; private const String ComparerName = "Comparer"; 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); this.comparer = comparer ?? EqualityComparer<TKey>.Default; #if FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR if (HashHelpers.s_UseRandomizedStringHashing && comparer == EqualityComparer<string>.Default) { this.comparer = (IEqualityComparer<TKey>) NonRandomizedStringEqualityComparer.Default; } #endif // FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR } 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); } } 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 { Contract.Ensures(Contract.Result<KeyCollection>() != null); 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 { Contract.Ensures(Contract.Result<ValueCollection>() != null); 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(); return default(TValue); } set { Insert(key, value, false); } } public void Add(TKey key, TValue value) { Insert(key, value, true); } 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() { if (count > 0) { for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; Array.Clear(entries, 0, count); freeList = -1; count = 0; freeCount = 0; version++; } } 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.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = this.count; Entry[] entries = this.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); } [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } info.AddValue(VersionName, version); #if FEATURE_RANDOMIZED_STRING_HASHING info.AddValue(ComparerName, HashHelpers.GetEqualityComparerForSerialization(comparer), typeof(IEqualityComparer<TKey>)); #else info.AddValue(ComparerName, comparer, typeof(IEqualityComparer<TKey>)); #endif info.AddValue(HashSizeName, buckets == null ? 0 : buckets.Length); //This is the length of the bucket array. if( buckets != null) { KeyValuePair<TKey, TValue>[] 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 void Initialize(int capacity) { int size = HashHelpers.GetPrime(capacity); buckets = new int[size]; for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; entries = new Entry[size]; freeList = -1; } private void Insert(TKey key, TValue value, bool add) { if( key == null ) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets == null) Initialize(0); int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int targetBucket = hashCode % buckets.Length; #if FEATURE_RANDOMIZED_STRING_HASHING int collisionCount = 0; #endif for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) { if (add) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); } entries[i].value = value; version++; return; } #if FEATURE_RANDOMIZED_STRING_HASHING collisionCount++; #endif } 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 FEATURE_RANDOMIZED_STRING_HASHING #if FEATURE_CORECLR // In case we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing // in this case will be EqualityComparer<string>.Default. // Note, randomized string hashing is turned on by default on coreclr so EqualityComparer<string>.Default will // be using randomized string hashing if (collisionCount > HashHelpers.HashCollisionThreshold && comparer == NonRandomizedStringEqualityComparer.Default) { comparer = (IEqualityComparer<TKey>) EqualityComparer<string>.Default; Resize(entries.Length, true); } #else if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer)) { comparer = (IEqualityComparer<TKey>) HashHelpers.GetRandomizedEqualityComparer(comparer); Resize(entries.Length, true); } #endif // FEATURE_CORECLR #endif } public virtual void OnDeserialization(Object sender) { SerializationInfo siInfo; HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo); if (siInfo==null) { // It might be necessary to call OnDeserialization from a container if the container object also implements // OnDeserialization. However, remoting will call OnDeserialization again. // We can return immediately if this function is called twice. // Note we set 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) { buckets = new int[hashsize]; for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; entries = new Entry[hashsize]; freeList = -1; 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); } Insert(array[i].Key, array[i].Value, true); } } else { buckets = null; } version = realVersion; HashHelpers.SerializationInfoTable.Remove(this); } private void Resize() { Resize(HashHelpers.ExpandPrime(count), false); } private void Resize(int newSize, bool forceNewHashCodes) { Contract.Assert(newSize >= entries.Length); int[] newBuckets = new int[newSize]; for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1; Entry[] newEntries = new Entry[newSize]; Array.Copy(entries, 0, newEntries, 0, count); if(forceNewHashCodes) { for (int i = 0; i < count; i++) { if(newEntries[i].hashCode != -1) { newEntries[i].hashCode = (comparer.GetHashCode(newEntries[i].key) & 0x7FFFFFFF); } } } for (int i = 0; i < count; i++) { if (newEntries[i].hashCode >= 0) { int bucket = newEntries[i].hashCode % newSize; newEntries[i].next = newBuckets[bucket]; newBuckets[bucket] = i; } } buckets = newBuckets; entries = newEntries; } 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; for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) { if (last < 0) { buckets[bucket] = entries[i].next; } else { entries[last].next = entries[i].next; } entries[i].hashCode = -1; entries[i].next = freeList; entries[i].key = default(TKey); entries[i].value = default(TValue); freeList = i; freeCount++; version++; return true; } } } 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; } // This is a convenience method for the internal callers that were converted from using Hashtable. // Many were combining key doesn't exist and key exists but null value (for non-value types) checks. // This allows them to continue getting that behavior with minimal code delta. This is basically // TryGetValue without the out param internal TValue GetValueOrDefault(TKey key) { int i = FindEntry(key); if (i >= 0) { return entries[i].value; } return default(TValue); } 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.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } 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 = this.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(ExceptionResource.Argument_InvalidArrayType); } try { int count = this.count; Entry[] entries = this.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(ExceptionResource.Argument_InvalidArrayType); } } } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } 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); } } [Serializable] 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) { this.dictionary = dictionary; version = dictionary.version; index = 0; this.getEnumeratorRetType = getEnumeratorRetType; current = new KeyValuePair<TKey, TValue>(); } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.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) { if (dictionary.entries[index].hashCode >= 0) { current = new KeyValuePair<TKey, TValue>(dictionary.entries[index].key, dictionary.entries[index].value); index++; return true; } index++; } 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(ExceptionResource.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(ExceptionResource.InvalidOperation_EnumFailedVersion); } index = 0; current = new KeyValuePair<TKey, TValue>(); } DictionaryEntry IDictionaryEnumerator.Entry { get { if( index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(current.Key, current.Value); } } object IDictionaryEnumerator.Key { get { if( index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return current.Key; } } object IDictionaryEnumerator.Value { get { if( index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return current.Value; } } } [DebuggerTypeProxy(typeof(Mscorlib_DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] 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); } this.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.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } 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.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } 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(ExceptionResource.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(ExceptionResource.Argument_InvalidArrayType); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } [Serializable] 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) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentKey = default(TKey); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { currentKey = dictionary.entries[index].key; index++; return true; } index++; } 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(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return currentKey; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } index = 0; currentKey = default(TKey); } } } [DebuggerTypeProxy(typeof(Mscorlib_DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] 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); } this.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.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } 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.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } 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(ExceptionResource.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(ExceptionResource.Argument_InvalidArrayType); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } [Serializable] 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) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentValue = default(TValue); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { currentValue = dictionary.entries[index].value; index++; return true; } index++; } 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(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return currentValue; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } index = 0; currentValue = default(TValue); } } } } }
using System; using System.Net; using System.Text; using System.Reflection; using NServiceKit.Common.Web; using NServiceKit.ServiceHost; using NServiceKit.ServiceInterface.ServiceModel; using NServiceKit.Text; using NServiceKit.Logging; #if !NETFX_CORE using System.Security.Cryptography; #endif #if NETFX_CORE using System.Net.Http.Headers; using Windows.Security.Cryptography; using Windows.Security.Cryptography.Core; using Windows.Storage.Streams; #endif namespace NServiceKit.ServiceClient.Web { /// <summary>Exception for signalling authentication errors.</summary> public class AuthenticationException : Exception { /// <summary>Initializes a new instance of the NServiceKit.ServiceClient.Web.AuthenticationException class.</summary> public AuthenticationException() { } /// <summary>Initializes a new instance of the NServiceKit.ServiceClient.Web.AuthenticationException class.</summary> /// /// <param name="message">The message.</param> public AuthenticationException(string message) : base(message) { } /// <summary>Initializes a new instance of the NServiceKit.ServiceClient.Web.AuthenticationException class.</summary> /// /// <param name="message"> The message.</param> /// <param name="innerException">The inner exception.</param> public AuthenticationException(string message, Exception innerException) : base(message, innerException) { } } /// <summary>by adamfowleruk.</summary> public class AuthenticationInfo { private static readonly ILog Log = LogManager.GetLogger(typeof(AuthenticationInfo)); /// <summary>Gets or sets the method.</summary> /// /// <value>The method.</value> public string method {get;set;} /// <summary>Gets or sets the realm.</summary> /// /// <value>The realm.</value> public string realm {get;set;} /// <summary>Gets or sets the qop.</summary> /// /// <value>The qop.</value> public string qop {get;set;} /// <summary>Gets or sets the nonce.</summary> /// /// <value>The nonce.</value> public string nonce { get; set; } /// <summary>Gets or sets the opaque.</summary> /// /// <value>The opaque.</value> public string opaque { get; set; } /// <summary>Gets or sets the cnonce.</summary> /// /// <value>The cnonce.</value> public string cnonce { get; set; } /// <summary>Gets or sets the non-client.</summary> /// /// <value>The non-client.</value> public int nc { get; set; } /// <summary>Initializes a new instance of the NServiceKit.ServiceClient.Web.AuthenticationInfo class.</summary> /// /// <exception cref="AuthenticationException">Thrown when an Authentication error condition occurs.</exception> /// /// <param name="authHeader">The authentication header.</param> public AuthenticationInfo(String authHeader) { cnonce = "0a4f113b"; nc = 1; // Example Digest header: WWW-Authenticate: Digest realm="testrealm@host.com", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41" // get method from first word int pos = authHeader.IndexOf (" "); if (pos < 0) { throw new AuthenticationException(string.Format("Authentication header not supported, {0}", authHeader)); } method = authHeader.Substring (0, pos).ToLower (); string remainder = authHeader.Substring (pos + 1); // split the rest by comma, then = string[] pars = remainder.Split (','); string[] newpars = new string[pars.Length]; int maxnewpars = 0; // test possibility that a comma is mid value for a split (as in above example) for (int i = 0; i < pars.Length; i++) { if (pars[i].EndsWith("\"")) { newpars[maxnewpars] = pars[i]; maxnewpars++; } else { // merge with next one newpars[maxnewpars] = pars[i] + "," + pars[i+1]; maxnewpars++; i++; // skips next value } } // now go through each part, splitting on first = character, and removing leading and trailing spaces and " quotes for (int i = 0;i < maxnewpars;i++) { int pos2 = newpars[i].IndexOf("="); string name = newpars[i].Substring(0,pos2).Trim(); string value = newpars[i].Substring(pos2 + 1).Trim (); if (value.StartsWith("\"")) { value = value.Substring(1); } if (value.EndsWith("\"")) { value = value.Substring(0,value.Length - 1); } if ("qop".Equals (name)) { qop = value; } else if ("realm".Equals (name)) { realm = value; } else if ("nonce".Equals (name)) { nonce = value; } else if ("opaque".Equals (name)) { opaque = value; } } } /// <summary>Returns a string that represents the current object.</summary> /// /// <returns>A string that represents the current object.</returns> public override string ToString () { return string.Format ("[AuthenticationInfo: method={0}, realm={1}, qop={2}, nonce={3}, opaque={4}, cnonce={5}, nc={6}]", method, realm, qop, nonce, opaque, cnonce, nc); } } /// <summary>A web request utilities.</summary> public static class WebRequestUtils { private static readonly ILog Log = LogManager.GetLogger(typeof(WebRequestUtils)); internal static AuthenticationException CreateCustomException(string uri, AuthenticationException ex) { if (uri.StartsWith("https")) { return new AuthenticationException( String.Format("Invalid remote SSL certificate, overide with: \nServicePointManager.ServerCertificateValidationCallback += ((sender, certificate, chain, sslPolicyErrors) => isValidPolicy);"), ex); } return null; } internal static bool ShouldAuthenticate(Exception ex, string userName, string password) { var webEx = ex as WebException; return (webEx != null && webEx.Response != null && ((HttpWebResponse) webEx.Response).StatusCode == HttpStatusCode.Unauthorized && !String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password)); } internal static void AddBasicAuth(this WebRequest client, string userName, string password) { client.Headers[NServiceKit.Common.Web.HttpHeaders.Authorization] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + password)); } #if NETFX_CORE internal static string CalculateMD5Hash(string input) { var alg = HashAlgorithmProvider.OpenAlgorithm("MD5"); IBuffer buff = CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8); var hashed = alg.HashData(buff); var res = CryptographicBuffer.EncodeToHexString(hashed); return res.ToLower(); } #endif #if !NETFX_CORE && !SILVERLIGHT internal static string CalculateMD5Hash(string input) { // copied/pasted by adamfowleruk // step 1, calculate MD5 hash from input MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } return sb.ToString().ToLower(); // The RFC requires the hex values are lowercase } #endif internal static string padNC(int num) { // by adamfowleruk var pad = ""; for (var i = 0;i < (8 - ("" + num).Length);i++) { pad += "0"; } var ret = pad + num; return ret; } #if !SILVERLIGHT internal static void AddAuthInfo(this WebRequest client,string userName,string password,AuthenticationInfo authInfo) { if ("basic".Equals (authInfo.method)) { client.AddBasicAuth (userName, password); // FIXME AddBasicAuth ignores the server provided Realm property. Potential Bug. } else if ("digest".Equals (authInfo.method)) { // do digest auth header using auth info // auth info saved in ServiceClientBase for subsequent requests client.AddDigestAuth (userName, password, authInfo); } } internal static void AddDigestAuth(this WebRequest client,string userName,string password,AuthenticationInfo authInfo) { // by adamfowleruk // See Client Request at http://en.wikipedia.org/wiki/Digest_access_authentication string ncUse = padNC(authInfo.nc); authInfo.nc++; // incrememnt for subsequent requests string ha1raw = userName + ":" + authInfo.realm + ":" + password; string ha1 = CalculateMD5Hash(ha1raw); string ha2raw = client.Method + ":" + client.RequestUri.PathAndQuery; string ha2 = CalculateMD5Hash(ha2raw); string md5rraw = ha1 + ":" + authInfo.nonce + ":" + ncUse + ":" + authInfo.cnonce + ":" + authInfo.qop + ":" + ha2; string response = CalculateMD5Hash(md5rraw); string header = "Digest username=\"" + userName + "\", realm=\"" + authInfo.realm + "\", nonce=\"" + authInfo.nonce + "\", uri=\"" + client.RequestUri.PathAndQuery + "\", cnonce=\"" + authInfo.cnonce + "\", nc=" + ncUse + ", qop=\"" + authInfo.qop + "\", response=\"" + response + "\", opaque=\"" + authInfo.opaque + "\""; client.Headers [NServiceKit.Common.Web.HttpHeaders.Authorization] = header; } #endif /// <summary> /// Naming convention for the request's Response DTO /// </summary> public const string ResponseDtoSuffix = "Response"; /// <summary>Gets response dto name.</summary> /// /// <param name="request">The request.</param> /// /// <returns>The response dto name.</returns> public static string GetResponseDtoName(object request) { var requestType = request.GetType(); return requestType != typeof(object) ? requestType.FullName + ResponseDtoSuffix : request.GetType().FullName + ResponseDtoSuffix; } /// <summary>Gets error response dto type.</summary> /// /// <param name="request">The request.</param> /// /// <returns>The error response dto type.</returns> public static Type GetErrorResponseDtoType(object request) { if (request == null) return typeof(ErrorResponse); //If a conventionally-named Response type exists use that regardless if it has ResponseStatus or not var responseDtoType = AssemblyUtils.FindType(GetResponseDtoName(request)); if (responseDtoType == null) { var genericDef = request.GetType().GetTypeWithGenericTypeDefinitionOf(typeof(IReturn<>)); if (genericDef != null) { var returnDtoType = genericDef.GenericTypeArguments()[0]; var hasResponseStatus = returnDtoType is IHasResponseStatus || returnDtoType.GetPropertyInfo("ResponseStatus") != null; //Only use the specified Return type if it has a ResponseStatus property if (hasResponseStatus) { responseDtoType = returnDtoType; } } } return responseDtoType ?? typeof(ErrorResponse); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class CompilationContext { private static readonly SymbolDisplayFormat s_fullNameFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); internal readonly CSharpCompilation Compilation; internal readonly Binder NamespaceBinder; // Internal for test purposes. private readonly MetadataDecoder _metadataDecoder; private readonly MethodSymbol _currentFrame; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; private readonly ImmutableHashSet<string> _hoistedParameterNames; private readonly ImmutableArray<LocalSymbol> _localsForBinding; private readonly CSharpSyntaxNode _syntax; private readonly bool _methodNotType; /// <summary> /// Create a context to compile expressions within a method scope. /// </summary> internal CompilationContext( CSharpCompilation compilation, MetadataDecoder metadataDecoder, MethodSymbol currentFrame, ImmutableArray<LocalSymbol> locals, InScopeHoistedLocals inScopeHoistedLocals, MethodDebugInfo methodDebugInfo, CSharpSyntaxNode syntax) { Debug.Assert(string.IsNullOrEmpty(methodDebugInfo.DefaultNamespaceName)); Debug.Assert((syntax == null) || (syntax is ExpressionSyntax) || (syntax is LocalDeclarationStatementSyntax)); // TODO: syntax.SyntaxTree should probably be added to the compilation, // but it isn't rooted by a CompilationUnitSyntax so it doesn't work (yet). _currentFrame = currentFrame; _syntax = syntax; _methodNotType = !locals.IsDefault; // NOTE: Since this is done within CompilationContext, it will not be cached. // CONSIDER: The values should be the same everywhere in the module, so they // could be cached. // (Catch: what happens in a type context without a method def?) this.Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords); _metadataDecoder = metadataDecoder; // Each expression compile should use a unique compilation // to ensure expression-specific synthesized members can be // added (anonymous types, for instance). Debug.Assert(this.Compilation != compilation); this.NamespaceBinder = CreateBinderChain( this.Compilation, (PEModuleSymbol)currentFrame.ContainingModule, currentFrame.ContainingNamespace, methodDebugInfo.ImportRecordGroups, _metadataDecoder); if (_methodNotType) { _locals = locals; ImmutableArray<string> displayClassVariableNamesInOrder; GetDisplayClassVariables( currentFrame, _locals, inScopeHoistedLocals, out displayClassVariableNamesInOrder, out _displayClassVariables, out _hoistedParameterNames); Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count); _localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables); } else { _locals = ImmutableArray<LocalSymbol>.Empty; _displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; _localsForBinding = ImmutableArray<LocalSymbol>.Empty; } // Assert that the cheap check for "this" is equivalent to the expensive check for "this". Debug.Assert( _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()) == _displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This)); } internal CommonPEModuleBuilder CompileExpression( string typeName, string methodName, ImmutableArray<Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var properties = default(ResultProperties); var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( this.Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, methodName, this, (method, diags) => { var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()); var binder = ExtendBinderChain( _syntax, aliases, method, this.NamespaceBinder, hasDisplayClassThis, _methodNotType); var statementSyntax = _syntax as StatementSyntax; return (statementSyntax == null) ? BindExpression(binder, (ExpressionSyntax)_syntax, diags, out properties) : BindStatement(binder, statementSyntax, diags, out properties); }); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), synthesizedType: synthesizedType, testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, win32Resources: null, xmlDocStream: null, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } // Should be no name mangling since the caller provided explicit names. Debug.Assert(synthesizedType.MetadataName == typeName); Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName); resultProperties = properties; return module; } internal CommonPEModuleBuilder CompileAssignment( string typeName, string methodName, ImmutableArray<Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, methodName, this, (method, diags) => { var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()); var binder = ExtendBinderChain( _syntax, aliases, method, this.NamespaceBinder, hasDisplayClassThis, methodNotType: true); return BindAssignment(binder, (ExpressionSyntax)_syntax, diags); }); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), synthesizedType: synthesizedType, testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, win32Resources: null, xmlDocStream: null, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } // Should be no name mangling since the caller provided explicit names. Debug.Assert(synthesizedType.MetadataName == typeName); Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName); resultProperties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect); return module; } private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder) { return string.Format("<>m{0}", builder.Count); } /// <summary> /// Generate a class containing methods that represent /// the set of arguments and locals at the current scope. /// </summary> internal CommonPEModuleBuilder CompileGetLocals( string typeName, ArrayBuilder<LocalAndMethod> localBuilder, bool argumentsOnly, ImmutableArray<Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics) { var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var allTypeParameters = _currentFrame.GetAllTypeParameters(); var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance(); EENamedTypeSymbol typeVariablesType = null; if (!argumentsOnly && (allTypeParameters.Length > 0)) { // Generate a generic type with matching type parameters. // A null instance of the type will be used to represent the // "Type variables" local. typeVariablesType = new EENamedTypeSymbol( this.Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, ExpressionCompilerConstants.TypeVariablesClassName, (m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)), allTypeParameters, (t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2)); additionalTypes.Add(typeVariablesType); } var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, (m, container) => { var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); if (!argumentsOnly) { // Pseudo-variables: $exception, $ReturnValue, etc. if (aliases.Length > 0) { var sourceAssembly = Compilation.SourceAssembly; var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule); foreach (var alias in aliases) { var local = PlaceholderLocalSymbol.Create( typeNameDecoder, _currentFrame, sourceAssembly, alias); var methodName = GetNextMethodName(methodBuilder); var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); var aliasMethod = this.CreateMethod(container, methodName, syntax, (method, diags) => { var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type); return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; }); var flags = local.IsWritable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult; localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags)); methodBuilder.Add(aliasMethod); } } // "this" for non-static methods that are not display class methods or // display class methods where the display class contains "<>4__this". if (!m.IsStatic && (!IsDisplayClassType(m.ContainingType) || _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()))) { var methodName = GetNextMethodName(methodBuilder); var method = this.GetThisMethod(container, methodName); localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11. methodBuilder.Add(method); } } // Hoisted method parameters (represented as locals in the EE). if (!_hoistedParameterNames.IsEmpty) { int localIndex = 0; foreach (var local in _localsForBinding) { // Since we are showing hoisted method parameters first, the parameters may appear out of order // in the Locals window if only some of the parameters are hoisted. This is consistent with the // behavior of the old EE. if (_hoistedParameterNames.Contains(local.Name)) { AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local)); } localIndex++; } } // Method parameters (except those that have been hoisted). int parameterIndex = m.IsStatic ? 0 : 1; foreach (var parameter in m.Parameters) { var parameterName = parameter.Name; if (!_hoistedParameterNames.Contains(parameterName) && GeneratedNames.GetKind(parameterName) == GeneratedNameKind.None) { AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex); } parameterIndex++; } if (!argumentsOnly) { // Locals. int localIndex = 0; foreach (var local in _localsForBinding) { if (!_hoistedParameterNames.Contains(local.Name)) { AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local)); } localIndex++; } // "Type variables". if ((object)typeVariablesType != null) { var methodName = GetNextMethodName(methodBuilder); var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); var method = this.GetTypeVariablesMethod(container, methodName, returnType); localBuilder.Add(new CSharpLocalAndMethod( ExpressionCompilerConstants.TypeVariablesLocalName, ExpressionCompilerConstants.TypeVariablesLocalName, method, DkmClrCompilationResultFlags.ReadOnlyResult)); methodBuilder.Add(method); } } return methodBuilder.ToImmutableAndFree(); }); additionalTypes.Add(synthesizedType); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: additionalTypes.ToImmutableAndFree(), synthesizedType: synthesizedType, testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, win32Resources: null, xmlDocStream: null, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); return diagnostics.HasAnyErrors() ? null : module; } private void AppendLocalAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, LocalSymbol local, EENamedTypeSymbol container, int localIndex, DkmClrCompilationResultFlags resultFlags) { var methodName = GetNextMethodName(methodBuilder); var method = this.GetLocalMethod(container, methodName, local.Name, localIndex); localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags)); methodBuilder.Add(method); } private void AppendParameterAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, ParameterSymbol parameter, EENamedTypeSymbol container, int parameterIndex) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name); var methodName = GetNextMethodName(methodBuilder); var method = this.GetParameterMethod(container, methodName, name, parameterIndex); localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None)); methodBuilder.Add(method); } private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name); var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName; return new CSharpLocalAndMethod(escapedName, displayName, method, flags); } private static EEAssemblyBuilder CreateModuleBuilder( CSharpCompilation compilation, ImmutableArray<MethodSymbol> methods, ImmutableArray<NamedTypeSymbol> additionalTypes, EENamedTypeSymbol synthesizedType, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics) { // Each assembly must have a unique name. var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName()); var dynamicOperationContextType = GetNonDisplayClassContainer(synthesizedType.SubstitutedSourceType); string runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics); var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion); return new EEAssemblyBuilder(compilation.SourceAssembly, emitOptions, methods, serializationProperties, additionalTypes, dynamicOperationContextType, testData); } internal EEMethodSymbol CreateMethod( EENamedTypeSymbol container, string methodName, CSharpSyntaxNode syntax, GenerateMethodBody generateMethodBody) { return new EEMethodSymbol( container, methodName, syntax.Location, _currentFrame, _locals, _localsForBinding, _displayClassVariables, generateMethodBody); } private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex) { var syntax = SyntaxFactory.IdentifierName(localName); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var local = method.LocalsForBinding[localIndex]; var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, diagnostics), type: local.Type); return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex) { var syntax = SyntaxFactory.IdentifierName(parameterName); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var parameter = method.Parameters[parameterIndex]; var expression = new BoundParameter(syntax, parameter); return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName) { var syntax = SyntaxFactory.ThisExpression(); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType)); return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType) { var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var type = method.TypeMap.SubstituteNamedType(typeVariablesType); var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]); var statement = new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; return statement; }); } private static BoundStatement BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var flags = DkmClrCompilationResultFlags.None; // In addition to C# expressions, the native EE also supports // type names which are bound to a representation of the type // (but not System.Type) that the user can expand to see the // base type. Instead, we only allow valid C# expressions. var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } try { if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression)) { flags |= DkmClrCompilationResultFlags.PotentialSideEffect; } } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); resultProperties = default(ResultProperties); return null; } var expressionType = expression.Type; if ((object)expressionType == null) { expression = binder.CreateReturnConversion( syntax, diagnostics, expression, binder.Compilation.GetSpecialType(SpecialType.System_Object)); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } } else if (expressionType.SpecialType == SpecialType.System_Void) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; Debug.Assert(expression.ConstantValue == null); resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false); return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else if (expressionType.SpecialType == SpecialType.System_Boolean) { flags |= DkmClrCompilationResultFlags.BoolResult; } if (!IsAssignableExpression(binder, expression)) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; } resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null); return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true }; } private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties) { properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); return binder.BindStatement(syntax, diagnostics); } private static bool IsAssignableExpression(Binder binder, BoundExpression expression) { // NOTE: Surprisingly, binder.CheckValueKind will return true (!) for readonly fields // in contexts where they cannot be assigned - it simply reports a diagnostic. // Presumably, this is done to avoid producing a confusing error message about the // field not being an lvalue. var diagnostics = DiagnosticBag.GetInstance(); var result = binder.CheckValueKind(expression, Binder.BindValueKind.Assignment, diagnostics) && !diagnostics.HasAnyErrors(); diagnostics.Free(); return result; } private static BoundStatement BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics) { var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { return null; } return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true }; } private static Binder CreateBinderChain( CSharpCompilation compilation, PEModuleSymbol module, NamespaceSymbol @namespace, ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups, MetadataDecoder metadataDecoder) { var stack = ArrayBuilder<string>.GetInstance(); while ((object)@namespace != null) { stack.Push(@namespace.Name); @namespace = @namespace.ContainingNamespace; } var binder = (new BuckStopsHereBinder(compilation)).WithAdditionalFlags( BinderFlags.SuppressObsoleteChecks | BinderFlags.IgnoreAccessibility | BinderFlags.UnsafeRegion | BinderFlags.UncheckedRegion | BinderFlags.AllowManagedAddressOf | BinderFlags.AllowAwaitInUnsafeContext | BinderFlags.IgnoreCorLibraryDuplicatedTypes); var hasImports = !importRecordGroups.IsDefaultOrEmpty; var numImportStringGroups = hasImports ? importRecordGroups.Length : 0; var currentStringGroup = numImportStringGroups - 1; // PERF: We used to call compilation.GetCompilationNamespace on every iteration, // but that involved walking up to the global namespace, which we have to do // anyway. Instead, we'll inline the functionality into our own walk of the // namespace chain. @namespace = compilation.GlobalNamespace; while (stack.Count > 0) { var namespaceName = stack.Pop(); if (namespaceName.Length > 0) { // We're re-getting the namespace, rather than using the one containing // the current frame method, because we want the merged namespace. @namespace = @namespace.GetNestedNamespace(namespaceName); Debug.Assert((object)@namespace != null, $"We worked backwards from symbols to names, but no symbol exists for name '{namespaceName}'"); } else { Debug.Assert((object)@namespace == (object)compilation.GlobalNamespace); } Imports imports = null; if (hasImports) { if (currentStringGroup < 0) { Debug.WriteLine($"No import string group for namespace '{@namespace}'"); break; } var importsBinder = new InContainerBinder(@namespace, binder); imports = BuildImports(compilation, module, importRecordGroups[currentStringGroup], importsBinder, metadataDecoder); currentStringGroup--; } binder = new InContainerBinder(@namespace, binder, imports); } stack.Free(); if (currentStringGroup >= 0) { // CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since // the usings are already for the wrong method. Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces"); } return binder; } private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords) { if (externAliasRecords.IsDefaultOrEmpty) { return compilation.Clone(); } var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance(); var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance(); foreach (var reference in compilation.References) { updatedReferences.Add(reference); assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference)); } Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count); var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree(); foreach (var externAliasRecord in externAliasRecords) { int index = externAliasRecord.GetIndexOfTargetAssembly(assembliesAndModules, compilation.Options.AssemblyIdentityComparer); if (index < 0) { Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'"); continue; } var externAlias = externAliasRecord.Alias; var assemblyReference = updatedReferences[index]; var oldAliases = assemblyReference.Properties.Aliases; var newAliases = oldAliases.IsEmpty ? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias) : oldAliases.Concat(ImmutableArray.Create(externAlias)); // NOTE: Dev12 didn't emit custom debug info about "global", so we don't have // a good way to distinguish between a module aliased with both (e.g.) "X" and // "global" and a module aliased with only "X". As in Dev12, we assume that // "global" is a valid alias to remain at least as permissive as source. // NOTE: In the event that this introduces ambiguities between two assemblies // (e.g. because one was "global" in source and the other was "X"), it should be // possible to disambiguate as long as each assembly has a distinct extern alias, // not necessarily used in source. Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias)); // Replace the value in the map with the updated reference. updatedReferences[index] = assemblyReference.WithAliases(newAliases); } compilation = compilation.WithReferences(updatedReferences); updatedReferences.Free(); return compilation; } private static Binder ExtendBinderChain( CSharpSyntaxNode syntax, ImmutableArray<Alias> aliases, EEMethodSymbol method, Binder binder, bool hasDisplayClassThis, bool methodNotType) { var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis); var substitutedSourceType = substitutedSourceMethod.ContainingType; var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance(); for (var type = substitutedSourceType; (object)type != null; type = type.ContainingType) { stack.Add(type); } while (stack.Count > 0) { substitutedSourceType = stack.Pop(); binder = new InContainerBinder(substitutedSourceType, binder); if (substitutedSourceType.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArguments, binder); } } stack.Free(); if (substitutedSourceMethod.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArguments, binder); } if (methodNotType) { // Method locals and parameters shadow pseudo-variables. var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule); binder = new PlaceholderLocalBinder( syntax, aliases, method, typeNameDecoder, binder); } binder = new EEMethodBinder(method, substitutedSourceMethod, binder); if (methodNotType) { binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder); } return binder; } private static Imports BuildImports(CSharpCompilation compilation, PEModuleSymbol module, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder, MetadataDecoder metadataDecoder) { // We make a first pass to extract all of the extern aliases because other imports may depend on them. var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance(); foreach (var importRecord in importRecords) { if (importRecord.TargetKind != ImportTargetKind.Assembly) { continue; } var alias = importRecord.Alias; IdentifierNameSyntax aliasNameSyntax; if (!TryParseIdentifierNameSyntax(alias, out aliasNameSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'"); continue; } var externAliasSyntax = SyntaxFactory.ExternAliasDirective(aliasNameSyntax.Identifier); var aliasSymbol = new AliasSymbol(binder, externAliasSyntax); // Binder is only used to access compilation. externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null)); // We have one, but we pass null for consistency. } var externs = externsBuilder.ToImmutableAndFree(); if (externs.Any()) { // NB: This binder (and corresponding Imports) is only used to bind the other imports. // We'll merge the externs into a final Imports object and return that to be used in // the actual binder chain. binder = new InContainerBinder( binder.Container, binder, Imports.FromCustomDebugInfo(binder.Compilation, ImmutableDictionary<string, AliasAndUsingDirective>.Empty, ImmutableArray<NamespaceOrTypeAndUsingDirective>.Empty, externs)); } var usingAliases = ImmutableDictionary.CreateBuilder<string, AliasAndUsingDirective>(); var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance(); foreach (var importRecord in importRecords) { switch (importRecord.TargetKind) { case ImportTargetKind.Type: { var portableImportRecord = importRecord as PortableImportRecord; TypeSymbol typeSymbol = portableImportRecord != null ? portableImportRecord.GetTargetType(metadataDecoder) : metadataDecoder.GetTypeSymbolForSerializedType(importRecord.TargetString); Debug.Assert((object)typeSymbol != null); if (typeSymbol.IsErrorType()) { // Type is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } else if (importRecord.Alias == null && !typeSymbol.IsStatic) { // Only static types can be directly imported. continue; } if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Namespace: { var namespaceName = importRecord.TargetString; NameSyntax targetSyntax; if (!SyntaxHelpers.TryParseDottedName(namespaceName, out targetSyntax)) { // DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}". // Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}" // (which will rarely work and never be correct). Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'"); continue; } NamespaceSymbol namespaceSymbol; var portableImportRecord = importRecord as PortableImportRecord; if (portableImportRecord != null) { var targetAssembly = portableImportRecord.GetTargetAssembly<ModuleSymbol, AssemblySymbol>(module, module.Module); if ((object)targetAssembly == null) { namespaceSymbol = BindNamespace(namespaceName, compilation.GlobalNamespace); } else if (targetAssembly.IsMissing) { Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'"); continue; } else { namespaceSymbol = BindNamespace(namespaceName, targetAssembly.GlobalNamespace); } } else { var globalNamespace = compilation.GlobalNamespace; var externAlias = ((NativeImportRecord)importRecord).ExternAlias; if (externAlias != null) { IdentifierNameSyntax externAliasSyntax = null; if (!TryParseIdentifierNameSyntax(externAlias, out externAliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{externAlias}'"); continue; } var unusedDiagnostics = DiagnosticBag.GetInstance(); var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, unusedDiagnostics); unusedDiagnostics.Free(); if ((object)aliasSymbol == null) { Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{externAlias}'"); continue; } globalNamespace = (NamespaceSymbol)aliasSymbol.Target; } namespaceSymbol = BindNamespace(namespaceName, globalNamespace); } if ((object)namespaceSymbol == null) { // Namespace is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Assembly: { // Handled in first pass (above). break; } default: { throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind); } } } return Imports.FromCustomDebugInfo(binder.Compilation, usingAliases.ToImmutableDictionary(), usingsBuilder.ToImmutableAndFree(), externs); } private static NamespaceSymbol BindNamespace(string namespaceName, NamespaceSymbol globalNamespace) { var namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = members.Length == 1 ? members[0] as NamespaceSymbol : null; if ((object)namespaceSymbol == null) { break; } } return namespaceSymbol; } private static bool TryAddImport( string alias, NamespaceOrTypeSymbol targetSymbol, ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder, ImmutableDictionary<string, AliasAndUsingDirective>.Builder usingAliases, InContainerBinder binder, ImportRecord importRecord) { if (alias == null) { usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null)); } else { IdentifierNameSyntax aliasSyntax; if (!TryParseIdentifierNameSyntax(alias, out aliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'"); return false; } var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder); usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null)); } return true; } private static bool TryParseIdentifierNameSyntax(string name, out IdentifierNameSyntax syntax) { Debug.Assert(name != null); if (name == MetadataReferenceProperties.GlobalAlias) { syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); return true; } NameSyntax nameSyntax; if (!SyntaxHelpers.TryParseDottedName(name, out nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName) { syntax = null; return false; } syntax = (IdentifierNameSyntax)nameSyntax; return true; } internal CommonMessageProvider MessageProvider { get { return this.Compilation.MessageProvider; } } private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local) { // CONSIDER: We might want to prevent the user from modifying pinned locals - // that's pretty dangerous. return local.IsConst ? DkmClrCompilationResultFlags.ReadOnlyResult : DkmClrCompilationResultFlags.None; } /// <summary> /// Generate the set of locals to use for binding. /// </summary> private static ImmutableArray<LocalSymbol> GetLocalsForBinding( ImmutableArray<LocalSymbol> locals, ImmutableArray<string> displayClassVariableNamesInOrder, ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in locals) { var name = local.Name; if (name == null) { continue; } if (GeneratedNames.GetKind(name) != GeneratedNameKind.None) { continue; } // Although Roslyn doesn't name synthesized locals unless they are well-known to EE, // Dev12 did so we need to skip them here. if (GeneratedNames.IsSynthesizedLocalName(name)) { continue; } builder.Add(local); } foreach (var variableName in displayClassVariableNamesInOrder) { var variable = displayClassVariables[variableName]; switch (variable.Kind) { case DisplayClassVariableKind.Local: case DisplayClassVariableKind.Parameter: builder.Add(new EEDisplayClassFieldLocalSymbol(variable)); break; } } return builder.ToImmutableAndFree(); } /// <summary> /// Return a mapping of captured variables (parameters, locals, and /// "this") to locals. The mapping is needed to expose the original /// local identifiers (those from source) in the binder. /// </summary> private static void GetDisplayClassVariables( MethodSymbol method, ImmutableArray<LocalSymbol> locals, InScopeHoistedLocals inScopeHoistedLocals, out ImmutableArray<string> displayClassVariableNamesInOrder, out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables, out ImmutableHashSet<string> hoistedParameterNames) { // Calculated the shortest paths from locals to instances of display // classes. There should not be two instances of the same display // class immediately within any particular method. var displayClassTypes = PooledHashSet<NamedTypeSymbol>.GetInstance(); var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); // Add any display class instances from locals (these will contain any hoisted locals). foreach (var local in locals) { var name = local.Name; if ((name != null) && (GeneratedNames.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField)) { var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local); displayClassTypes.Add(instance.Type); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } foreach (var parameter in method.Parameters) { if (GeneratedNames.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier) { var instance = new DisplayClassInstanceFromParameter(parameter); displayClassTypes.Add(instance.Type); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } var containingType = method.ContainingType; bool isIteratorOrAsyncMethod = false; if (IsDisplayClassType(containingType)) { if (!method.IsStatic) { // Add "this" display class instance. var instance = new DisplayClassInstanceFromParameter(method.ThisParameter); displayClassTypes.Add(instance.Type); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } isIteratorOrAsyncMethod = GeneratedNames.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType; } if (displayClassInstances.Any()) { // Find any additional display class instances breadth first. for (int depth = 0; GetDisplayClassInstances(displayClassTypes, displayClassInstances, depth) > 0; depth++) { } // The locals are the set of all fields from the display classes. var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance(); var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance(); var parameterNames = PooledHashSet<string>.GetInstance(); if (isIteratorOrAsyncMethod) { Debug.Assert(IsDisplayClassType(containingType)); foreach (var field in containingType.GetMembers().OfType<FieldSymbol>()) { // All iterator and async state machine fields (including hoisted locals) have mangled names, except // for hoisted parameters (whose field names are always the same as the original source parameters). var fieldName = field.Name; if (GeneratedNames.GetKind(fieldName) == GeneratedNameKind.None) { parameterNames.Add(fieldName); } } } else { foreach (var p in method.Parameters) { parameterNames.Add(p.Name); } } var pooledHoistedParameterNames = PooledHashSet<string>.GetInstance(); foreach (var instance in displayClassInstances) { GetDisplayClassVariables( displayClassVariableNamesInOrderBuilder, displayClassVariablesBuilder, parameterNames, inScopeHoistedLocals, instance, pooledHoistedParameterNames); } hoistedParameterNames = pooledHoistedParameterNames.ToImmutableHashSet<string>(); pooledHoistedParameterNames.Free(); parameterNames.Free(); displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree(); displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary(); displayClassVariablesBuilder.Free(); } else { hoistedParameterNames = ImmutableHashSet<string>.Empty; displayClassVariableNamesInOrder = ImmutableArray<string>.Empty; displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; } displayClassTypes.Free(); displayClassInstances.Free(); } /// <summary> /// Return the set of display class instances that can be reached /// from the given local. A particular display class may be reachable /// from multiple locals. In those cases, the instance from the /// shortest path (fewest intermediate fields) is returned. /// </summary> private static int GetDisplayClassInstances( HashSet<NamedTypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, int depth) { Debug.Assert(displayClassInstances.All(p => p.Depth <= depth)); var atDepth = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); atDepth.AddRange(displayClassInstances.Where(p => p.Depth == depth)); Debug.Assert(atDepth.Count > 0); int n = 0; foreach (var instance in atDepth) { n += GetDisplayClassInstances(displayClassTypes, displayClassInstances, instance); } atDepth.Free(); return n; } private static int GetDisplayClassInstances( HashSet<NamedTypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. int n = 0; foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldType = field.Type; var fieldKind = GeneratedNames.GetKind(field.Name); if (fieldKind == GeneratedNameKind.DisplayClassLocalOrField || fieldKind == GeneratedNameKind.TransparentIdentifier || IsTransparentIdentifierFieldInAnonymousType(field) || (fieldKind == GeneratedNameKind.ThisProxyField && GeneratedNames.GetKind(fieldType.Name) == GeneratedNameKind.LambdaDisplayClass)) // Async lambda case. { Debug.Assert(!field.IsStatic); // A local that is itself a display class instance. if (displayClassTypes.Add((NamedTypeSymbol)fieldType)) { var other = instance.FromField(field); displayClassInstances.Add(other); n++; } } } return n; } private static bool IsTransparentIdentifierFieldInAnonymousType(FieldSymbol field) { string fieldName = field.Name; if (GeneratedNames.GetKind(fieldName) != GeneratedNameKind.AnonymousTypeField) { return false; } GeneratedNameKind kind; int openBracketOffset; int closeBracketOffset; if (!GeneratedNames.TryParseGeneratedName(fieldName, out kind, out openBracketOffset, out closeBracketOffset)) { return false; } fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); return GeneratedNames.GetKind(fieldName) == GeneratedNameKind.TransparentIdentifier; } private static void GetDisplayClassVariables( ArrayBuilder<string> displayClassVariableNamesInOrderBuilder, Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder, HashSet<string> parameterNames, InScopeHoistedLocals inScopeHoistedLocals, DisplayClassInstanceAndFields instance, HashSet<string> hoistedParameterNames) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; REPARSE: DisplayClassVariableKind variableKind; string variableName; GeneratedNameKind fieldKind; int openBracketOffset; int closeBracketOffset; GeneratedNames.TryParseGeneratedName(fieldName, out fieldKind, out openBracketOffset, out closeBracketOffset); switch (fieldKind) { case GeneratedNameKind.AnonymousTypeField: Debug.Assert(fieldName == field.Name); // This only happens once. fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); goto REPARSE; case GeneratedNameKind.TransparentIdentifier: // A transparent identifier (field) in an anonymous type synthesized for a transparent identifier. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.DisplayClassLocalOrField: // A local that is itself a display class instance. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.HoistedLocalField: // Filter out hoisted locals that are known to be out-of-scope at the current IL offset. // Hoisted locals with invalid indices will be included since more information is better // than less in error scenarios. if (!inScopeHoistedLocals.IsInScope(fieldName)) { continue; } variableName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); variableKind = DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.ThisProxyField: // A reference to "this". variableName = fieldName; variableKind = DisplayClassVariableKind.This; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.None: // A reference to a parameter or local. variableName = fieldName; if (parameterNames.Contains(variableName)) { variableKind = DisplayClassVariableKind.Parameter; hoistedParameterNames.Add(variableName); } else { variableKind = DisplayClassVariableKind.Local; } Debug.Assert(!field.IsStatic); break; default: continue; } if (displayClassVariablesBuilder.ContainsKey(variableName)) { // Only expecting duplicates for async state machine // fields (that should be at the top-level). Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1); Debug.Assert(instance.Fields.Count() >= 1); // greater depth Debug.Assert((variableKind == DisplayClassVariableKind.Parameter) || (variableKind == DisplayClassVariableKind.This)); } else if (variableKind != DisplayClassVariableKind.This || GeneratedNames.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass) { // In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one. // In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one). displayClassVariableNamesInOrderBuilder.Add(variableName); displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field)); } } } private static bool IsDisplayClassType(NamedTypeSymbol type) { switch (GeneratedNames.GetKind(type.Name)) { case GeneratedNameKind.LambdaDisplayClass: case GeneratedNameKind.StateMachineType: return true; default: return false; } } private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type) { // 1) Display class and state machine types are always nested within the types // that use them (so that they can access private members of those types). // 2) The native compiler used to produce nested display classes for nested lambdas, // so we may have to walk out more than one level. while (IsDisplayClassType(type)) { type = type.ContainingType; } Debug.Assert((object)type != null); return type; } /// <summary> /// Identifies the method in which binding should occur. /// </summary> /// <param name="candidateSubstitutedSourceMethod"> /// The symbol of the method that is currently on top of the callstack, with /// EE type parameters substituted in place of the original type parameters. /// </param> /// <param name="sourceMethodMustBeInstance"> /// True if "this" is available via a display class in the current context. /// </param> /// <returns> /// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated, /// then we will attempt to determine which user-defined method caused it to be /// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/> /// is a state machine MoveNext method, then we will try to find the iterator or /// async method for which it was generated. If we are able to find the original /// method, then we will substitute in the EE type parameters. Otherwise, we will /// return <paramref name="candidateSubstitutedSourceMethod"/>. /// </returns> /// <remarks> /// In the event that the original method is overloaded, we may not be able to determine /// which overload actually corresponds to the state machine. In particular, we do not /// have information about the signature of the original method (i.e. number of parameters, /// parameter types and ref-kinds, return type). However, we conjecture that this /// level of uncertainty is acceptable, since parameters are managed by a separate binder /// in the synthesized binder chain and we have enough information to check the other method /// properties that are used during binding (e.g. static-ness, generic arity, type parameter /// constraints). /// </remarks> internal static MethodSymbol GetSubstitutedSourceMethod( MethodSymbol candidateSubstitutedSourceMethod, bool sourceMethodMustBeInstance) { var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType; string desiredMethodName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) || GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName)) { // We could be in the MoveNext method of an async lambda. string tempMethodName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName)) { desiredMethodName = tempMethodName; var containing = candidateSubstitutedSourceType.ContainingType; Debug.Assert((object)containing != null); if (GeneratedNames.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass) { candidateSubstitutedSourceType = containing; sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNames.GetKind).Contains(GeneratedNameKind.ThisProxyField); } } var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters; // Type containing the original iterator, async, or lambda-containing method. var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType); foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>()) { if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance)) { return desiredTypeParameters.Length == 0 ? candidateMethod : candidateMethod.Construct(candidateSubstitutedSourceType.TypeArguments); } } Debug.Assert(false, "Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?"); } return candidateSubstitutedSourceMethod; } private static bool IsViableSourceMethod( MethodSymbol candidateMethod, string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, bool desiredMethodMustBeInstance) { return !candidateMethod.IsAbstract && (!(desiredMethodMustBeInstance && candidateMethod.IsStatic)) && candidateMethod.Name == desiredMethodName && HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters); } private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters) { int arity = candidateTypeParameters.Length; if (arity != desiredTypeParameters.Length) { return false; } else if (arity == 0) { return true; } var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true); var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true); return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap); } private struct DisplayClassInstanceAndFields { internal readonly DisplayClassInstance Instance; internal readonly ConsList<FieldSymbol> Fields; internal DisplayClassInstanceAndFields(DisplayClassInstance instance) : this(instance, ConsList<FieldSymbol>.Empty) { Debug.Assert(IsDisplayClassType(instance.Type) || GeneratedNames.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType); } private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields) { this.Instance = instance; this.Fields = fields; } internal NamedTypeSymbol Type { get { return this.Fields.Any() ? (NamedTypeSymbol)this.Fields.Head.Type : this.Instance.Type; } } internal int Depth { get { return this.Fields.Count(); } } internal DisplayClassInstanceAndFields FromField(FieldSymbol field) { Debug.Assert(IsDisplayClassType((NamedTypeSymbol)field.Type) || GeneratedNames.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType); return new DisplayClassInstanceAndFields(this.Instance, this.Fields.Prepend(field)); } internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field) { return new DisplayClassVariable(name, kind, this.Instance, this.Fields.Prepend(field)); } } } }
//----------------------------------------------------------------------- // <copyright file="DetectedPlaneVisualizer.cs" company="Google"> // // Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore.Examples.Common { using System.Collections.Generic; using GoogleARCore; using UnityEngine; /// <summary> /// Visualizes a single DetectedPlane in the Unity scene. /// </summary> public class DetectedPlaneVisualizer : MonoBehaviour { private static int s_PlaneCount = 0; private readonly Color[] k_PlaneColors = new Color[] { new Color(1.0f, 1.0f, 1.0f), new Color(0.956f, 0.262f, 0.211f), new Color(0.913f, 0.117f, 0.388f), new Color(0.611f, 0.152f, 0.654f), new Color(0.403f, 0.227f, 0.717f), new Color(0.247f, 0.317f, 0.709f), new Color(0.129f, 0.588f, 0.952f), new Color(0.011f, 0.662f, 0.956f), new Color(0f, 0.737f, 0.831f), new Color(0f, 0.588f, 0.533f), new Color(0.298f, 0.686f, 0.313f), new Color(0.545f, 0.764f, 0.290f), new Color(0.803f, 0.862f, 0.223f), new Color(1.0f, 0.921f, 0.231f), new Color(1.0f, 0.756f, 0.027f) }; private DetectedPlane m_DetectedPlane; // Keep previous frame's mesh polygon to avoid mesh update every frame. private List<Vector3> m_PreviousFrameMeshVertices = new List<Vector3>(); private List<Vector3> m_MeshVertices = new List<Vector3>(); private Vector3 m_PlaneCenter = new Vector3(); private List<Color> m_MeshColors = new List<Color>(); private List<int> m_MeshIndices = new List<int>(); private Mesh m_Mesh; private MeshRenderer m_MeshRenderer; /// <summary> /// The Unity Awake() method. /// </summary> public void Awake() { m_Mesh = GetComponent<MeshFilter>().mesh; m_MeshRenderer = GetComponent<UnityEngine.MeshRenderer>(); } /// <summary> /// The Unity Update() method. /// </summary> public void Update() { if (m_DetectedPlane == null) { return; } else if (m_DetectedPlane.SubsumedBy != null) { Destroy(gameObject); return; } else if (m_DetectedPlane.TrackingState != TrackingState.Tracking) { m_MeshRenderer.enabled = false; return; } m_MeshRenderer.enabled = true; _UpdateMeshIfNeeded(); } /// <summary> /// Initializes the DetectedPlaneVisualizer with a DetectedPlane. /// </summary> /// <param name="plane">The plane to vizualize.</param> public void Initialize(DetectedPlane plane) { m_DetectedPlane = plane; m_MeshRenderer.material.SetColor("_GridColor", k_PlaneColors[s_PlaneCount++ % k_PlaneColors.Length]); m_MeshRenderer.material.SetFloat("_UvRotation", Random.Range(0.0f, 360.0f)); Update(); } /// <summary> /// Update mesh with a list of Vector3 and plane's center position. /// </summary> private void _UpdateMeshIfNeeded() { m_DetectedPlane.GetBoundaryPolygon(m_MeshVertices); if (_AreVerticesListsEqual(m_PreviousFrameMeshVertices, m_MeshVertices)) { return; } m_PreviousFrameMeshVertices.Clear(); m_PreviousFrameMeshVertices.AddRange(m_MeshVertices); m_PlaneCenter = m_DetectedPlane.CenterPose.position; Vector3 planeNormal = m_DetectedPlane.CenterPose.rotation * Vector3.up; m_MeshRenderer.material.SetVector("_PlaneNormal", planeNormal); int planePolygonCount = m_MeshVertices.Count; // The following code converts a polygon to a mesh with two polygons, inner // polygon renders with 100% opacity and fade out to outter polygon with opacity 0%, as shown below. // The indices shown in the diagram are used in comments below. // _______________ 0_______________1 // | | |4___________5| // | | | | | | // | | => | | | | // | | | | | | // | | |7-----------6| // --------------- 3---------------2 m_MeshColors.Clear(); // Fill transparent color to vertices 0 to 3. for (int i = 0; i < planePolygonCount; ++i) { m_MeshColors.Add(Color.clear); } // Feather distance 0.2 meters. const float featherLength = 0.2f; // Feather scale over the distance between plane center and vertices. const float featherScale = 0.2f; // Add vertex 4 to 7. for (int i = 0; i < planePolygonCount; ++i) { Vector3 v = m_MeshVertices[i]; // Vector from plane center to current point Vector3 d = v - m_PlaneCenter; float scale = 1.0f - Mathf.Min(featherLength / d.magnitude, featherScale); m_MeshVertices.Add((scale * d) + m_PlaneCenter); m_MeshColors.Add(Color.white); } m_MeshIndices.Clear(); int firstOuterVertex = 0; int firstInnerVertex = planePolygonCount; // Generate triangle (4, 5, 6) and (4, 6, 7). for (int i = 0; i < planePolygonCount - 2; ++i) { m_MeshIndices.Add(firstInnerVertex); m_MeshIndices.Add(firstInnerVertex + i + 1); m_MeshIndices.Add(firstInnerVertex + i + 2); } // Generate triangle (0, 1, 4), (4, 1, 5), (5, 1, 2), (5, 2, 6), (6, 2, 3), (6, 3, 7) // (7, 3, 0), (7, 0, 4) for (int i = 0; i < planePolygonCount; ++i) { int outerVertex1 = firstOuterVertex + i; int outerVertex2 = firstOuterVertex + ((i + 1) % planePolygonCount); int innerVertex1 = firstInnerVertex + i; int innerVertex2 = firstInnerVertex + ((i + 1) % planePolygonCount); m_MeshIndices.Add(outerVertex1); m_MeshIndices.Add(outerVertex2); m_MeshIndices.Add(innerVertex1); m_MeshIndices.Add(innerVertex1); m_MeshIndices.Add(outerVertex2); m_MeshIndices.Add(innerVertex2); } m_Mesh.Clear(); m_Mesh.SetVertices(m_MeshVertices); m_Mesh.SetTriangles(m_MeshIndices, 0); m_Mesh.SetColors(m_MeshColors); } private bool _AreVerticesListsEqual(List<Vector3> firstList, List<Vector3> secondList) { if (firstList.Count != secondList.Count) { return false; } for (int i = 0; i < firstList.Count; i++) { if (firstList[i] != secondList[i]) { return false; } } return true; } } }
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // 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 SafetySharp.Runtime.Serialization { using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; using ISSE.SafetyChecking.Utilities; using Utilities; /// <summary> /// Dynamically generates state serialization and deserialization methods. /// </summary> public sealed class SerializationGenerator { /// <summary> /// The reflection information of the <see cref="ObjectTable.GetObjectIdentifier" /> method. /// </summary> private readonly MethodInfo _getObjectIdentifierMethod = typeof(ObjectTable).GetMethod(nameof(ObjectTable.GetObjectIdentifier)); /// <summary> /// The reflection information of the <see cref="ObjectTable.GetObject" /> method. /// </summary> private readonly MethodInfo _getObjectMethod = typeof(ObjectTable).GetMethod(nameof(ObjectTable.GetObject)); /// <summary> /// The IL generator of the serialization method. /// </summary> private readonly ILGenerator _il; /// <summary> /// The method that is being generated. /// </summary> private readonly DynamicMethod _method; /// <summary> /// The index used to read or write a bit. /// </summary> private int _bitIndex; /// <summary> /// Indicates whether individual elements of the state vector are addressed by bit instead of by byte. /// </summary> private bool _bitLevelAddressing; /// <summary> /// The object that is currently stored in the local variable. /// </summary> private int _loadedObject; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="methodName">The name of the generated method.</param> internal SerializationGenerator(string methodName) { Requires.NotNullOrWhitespace(methodName, nameof(methodName)); _method = new DynamicMethod( name: methodName, returnType: typeof(void), parameterTypes: new[] { typeof(ObjectTable), typeof(byte*) }, m: typeof(object).Assembly.ManifestModule, skipVisibility: true); _il = _method.GetILGenerator(); // Store the state vector in a local variable _il.DeclareLocal(typeof(byte*)); _il.DeclareLocal(typeof(object)); _il.Emit(OpCodes.Ldarg_1); _il.Emit(OpCodes.Stloc_0); } /// <summary> /// Compiles the dynamic method, returning a delegate that can be used to invoke it. /// </summary> /// <param name="objects">The known objects that can be serialized and deserialized.</param> internal T Compile<T>(ObjectTable objects = null) { _il.Emit(OpCodes.Ret); return (T)(object)_method.CreateDelegate(typeof(T), objects); } /// <summary> /// Generates the code for the serialization method. /// </summary> /// <param name="stateGroups">The state groups the code should be generated for.</param> internal void GenerateSerializationCode(CompactedStateGroup[] stateGroups) { Requires.NotNull(stateGroups, nameof(stateGroups)); foreach (var group in stateGroups) { _bitLevelAddressing = group.ElementSizeInBits == 1; _bitIndex = 0; foreach (var slot in group.Slots) { if (slot.Field != null) { SerializeField(slot); Advance(slot.ElementSizeInBits / 8); } else SerializeArray(slot); } if (_bitLevelAddressing) { _bitLevelAddressing = false; if (_bitIndex != 0) Advance(1); } Advance(group.PaddingBytes); } } /// <summary> /// Generates the code for the deserialization method. /// </summary> /// <param name="stateGroups">The state groups the code should be generated for.</param> internal void GenerateDeserializationCode(CompactedStateGroup[] stateGroups) { Requires.NotNull(stateGroups, nameof(stateGroups)); foreach (var group in stateGroups) { _bitLevelAddressing = group.ElementSizeInBits == 1; _bitIndex = 0; foreach (var slot in group.Slots) { if (slot.Field != null) { DeserializeField(slot); Advance(slot.ElementSizeInBits / 8); } else DeserializeArray(slot); } if (_bitLevelAddressing) { _bitLevelAddressing = false; if (_bitIndex != 0) Advance(1); } Advance(group.PaddingBytes); } } /// <summary> /// Generates the code to deserialize the state slot described by the <paramref name="metadata" />. /// </summary> /// <param name="metadata">The metadata of the state slot the code should be generated for.</param> private void DeserializeField(StateSlotMetadata metadata) { LoadObject(metadata.ObjectIdentifier); if (IsReferenceType(metadata.DataType)) DeserializeReferenceField(metadata); else DeserializePrimitiveTypeField(metadata); } /// <summary> /// Generates the code to serialize the state slot described by the <paramref name="metadata" />. /// </summary> /// <param name="metadata">The metadata of the state slot the code should be generated for.</param> private void SerializeField(StateSlotMetadata metadata) { LoadObject(metadata.ObjectIdentifier); if (IsReferenceType(metadata.DataType)) SerializeReferenceField(metadata); else SerializePrimitiveTypeField(metadata); } /// <summary> /// Generates the code to deserialize the array state slot described by the <paramref name="metadata" />. /// </summary> /// <param name="metadata">The metadata of the state slot the code should be generated for.</param> private void DeserializeArray(StateSlotMetadata metadata) { var isReferenceType = metadata.DataType.IsReferenceType(); var loadCode = _bitLevelAddressing ? default(OpCode) : GetLoadElementOpCode(metadata.ElementSizeInBits / 8, metadata.EffectiveType.IsUnsignedNumericType()); var storeCode = isReferenceType ? OpCodes.Stelem_Ref : GetStoreArrayElementOpCode(GetUnmanagedSize(metadata.DataType)); LoadObject(metadata.ObjectIdentifier); for (var i = 0; i < metadata.ElementCount; ++i) { // o = &objs.GetObject(identifier)[i] _il.Emit(OpCodes.Ldloc_1); PrepareElementAccess(metadata, i); if (isReferenceType) { // v = objs.GetObject(*state) _il.Emit(OpCodes.Ldarg_0); _il.Emit(OpCodes.Ldloc_0); _il.Emit(OpCodes.Ldind_I2); _il.Emit(OpCodes.Call, _getObjectMethod); } else if (_bitLevelAddressing) LoadBooleanValue(); else { // v = *state _il.Emit(OpCodes.Ldloc_0); _il.Emit(loadCode); } // *o = v if (metadata.ContainedInStruct) AccessField(metadata, OpCodes.Stfld); else _il.Emit(storeCode); Advance(metadata.ElementSizeInBits / 8); } } /// <summary> /// Generates the code to serialize the array state slot described by the <paramref name="metadata" />. /// </summary> /// <param name="metadata">The metadata of the state slot the code should be generated for.</param> private void SerializeArray(StateSlotMetadata metadata) { var isReferenceType = metadata.DataType.IsReferenceType(); var storeCode = _bitLevelAddressing ? default(OpCode) : GetStoreElementOpCode(metadata.ElementSizeInBits / 8); var loadCode = isReferenceType ? OpCodes.Ldelem_Ref : GetLoadArrayElementOpCode(GetUnmanagedSize(metadata.DataType), metadata.EffectiveType.IsUnsignedNumericType()); LoadObject(metadata.ObjectIdentifier); for (var i = 0; i < metadata.ElementCount; ++i) { if (_bitLevelAddressing) { StoreBooleanValue(() => { // o = objs.GetObject(identifier) _il.Emit(OpCodes.Ldloc_1); // v = o[i] PrepareElementAccess(metadata, i); if (metadata.ContainedInStruct) AccessField(metadata, OpCodes.Ldfld); else _il.Emit(loadCode); }); } else { // s = state _il.Emit(OpCodes.Ldloc_0); // o = objs.GetObject(identifier) if (isReferenceType) _il.Emit(OpCodes.Ldarg_0); _il.Emit(OpCodes.Ldloc_1); // v = o[i] PrepareElementAccess(metadata, i); if (metadata.ContainedInStruct) AccessField(metadata, OpCodes.Ldfld); else _il.Emit(loadCode); // v = objs.GetObjectIdentifier(o[i]) if (isReferenceType) _il.Emit(OpCodes.Call, _getObjectIdentifierMethod); // *s = v _il.Emit(storeCode); } Advance(metadata.ElementSizeInBits / 8); } } /// <summary> /// Gets the IL instruction that can be used to store an element of the <paramref name="sizeInBytes" /> into an array. /// </summary> private static OpCode GetStoreArrayElementOpCode(int sizeInBytes) { switch (sizeInBytes) { case 1: return OpCodes.Stelem_I1; case 2: return OpCodes.Stelem_I2; case 4: return OpCodes.Stelem_I4; case 8: return OpCodes.Stelem_I8; default: return Assert.NotReached<OpCode>($"Unsupported element size: {sizeInBytes}."); } } /// <summary> /// Gets the IL instruction that can be used to load an element of the <paramref name="sizeInBytes" /> from an array. /// </summary> private static OpCode GetLoadArrayElementOpCode(int sizeInBytes, bool isUnsigned) { switch (sizeInBytes) { case 1: return isUnsigned ? OpCodes.Ldelem_U1 : OpCodes.Ldelem_I1; case 2: return isUnsigned ? OpCodes.Ldelem_U2 : OpCodes.Ldelem_I2; case 4: return isUnsigned ? OpCodes.Ldelem_U4 : OpCodes.Ldelem_I4; case 8: return OpCodes.Ldelem_I8; default: return Assert.NotReached<OpCode>($"Unsupported element size: {sizeInBytes}."); } } /// <summary> /// Gets the IL instruction that can be used to store an element of the <paramref name="sizeInBytes" /> into the state vector. /// </summary> private static OpCode GetStoreElementOpCode(int sizeInBytes) { switch (sizeInBytes) { case 1: return OpCodes.Stind_I1; case 2: return OpCodes.Stind_I2; case 4: return OpCodes.Stind_I4; case 8: return OpCodes.Stind_I8; default: return Assert.NotReached<OpCode>($"Unsupported element size: {sizeInBytes}."); } } /// <summary> /// Gets the IL instruction that can be used to load an element of the <paramref name="sizeInBytes" /> from the state vector. /// </summary> private static OpCode GetLoadElementOpCode(int sizeInBytes, bool isUnsigned) { switch (sizeInBytes) { case 1: return isUnsigned ? OpCodes.Ldind_U1 : OpCodes.Ldind_I1; case 2: return isUnsigned ? OpCodes.Ldind_U2 : OpCodes.Ldind_I2; case 4: return isUnsigned ? OpCodes.Ldind_U4 : OpCodes.Ldind_I4; case 8: return OpCodes.Ldind_I8; default: return Assert.NotReached<OpCode>($"Unsupported element size: {sizeInBytes}."); } } /// <summary> /// Generates the code to deserialize the state slot described by the <paramref name="metadata" /> of the object stored in the /// local variable. /// </summary> /// <param name="metadata">The metadata of the state slot the code should be generated for.</param> private void DeserializePrimitiveTypeField(StateSlotMetadata metadata) { // o = objs.GetObject(identifier) PrepareFieldAccess(metadata); if (_bitLevelAddressing) LoadBooleanValue(); else { // v = *state _il.Emit(OpCodes.Ldloc_0); _il.Emit(GetLoadElementOpCode(metadata.ElementSizeInBits / 8, metadata.EffectiveType.IsUnsignedNumericType())); } // o.field = v AccessField(metadata, OpCodes.Stfld); } /// <summary> /// Generates the code to serialize the state slot described by the <paramref name="metadata" /> of the object stored in the /// local variable. /// </summary> /// <param name="metadata">The metadata of the state slot the code should be generated for.</param> private void SerializePrimitiveTypeField(StateSlotMetadata metadata) { if (_bitLevelAddressing) { StoreBooleanValue(() => { PrepareFieldAccess(metadata); AccessField(metadata, OpCodes.Ldfld); }); return; } // s = state _il.Emit(OpCodes.Ldloc_0); // v = o.field PrepareFieldAccess(metadata); AccessField(metadata, OpCodes.Ldfld); // *s = v _il.Emit(GetStoreElementOpCode(metadata.ElementSizeInBits / 8)); } /// <summary> /// Prepares the access to the field referenced by the <paramref name="metadata" /> of an element contained in an array. /// </summary> private void PrepareElementAccess(StateSlotMetadata metadata, int elementIndex) { _il.Emit(OpCodes.Ldc_I4, elementIndex); if (!metadata.ContainedInStruct) return; _il.Emit(OpCodes.Ldelema, metadata.ObjectType.GetElementType()); for (var i = 0; i < metadata.FieldChain.Length - 1; ++i) _il.Emit(OpCodes.Ldflda, metadata.FieldChain[i]); } /// <summary> /// Prepares the access to the field referenced by the <paramref name="metadata" /> of an object. /// </summary> private void PrepareFieldAccess(StateSlotMetadata metadata) { _il.Emit(OpCodes.Ldloc_1); if (!metadata.ContainedInStruct) return; _il.Emit(OpCodes.Ldflda, metadata.Field); for (var i = 0; i < metadata.FieldChain.Length - 1; ++i) _il.Emit(OpCodes.Ldflda, metadata.FieldChain[i]); } /// <summary> /// Accesses the field on the object currently on the stack. /// </summary> private void AccessField(StateSlotMetadata metadata, OpCode accessCode) { var field = metadata.ContainedInStruct ? metadata.FieldChain.Last() : metadata.Field; _il.Emit(accessCode, field); } /// <summary> /// Loads a bit-compressed Boolean value onto the stack. /// </summary> private void LoadBooleanValue() { // v = (*state >> _bitIndex) & 0x01 == 1 _il.Emit(OpCodes.Ldloc_0); _il.Emit(OpCodes.Ldind_U1); _il.Emit(OpCodes.Ldc_I4, _bitIndex); _il.Emit(OpCodes.Shr_Un); _il.Emit(OpCodes.Ldc_I4_1); _il.Emit(OpCodes.And); } /// <summary> /// Stores a bit-compressed Boolean value loaded using the <paramref name="valueLoader" />. /// </summary> private void StoreBooleanValue(Action valueLoader) { // *s |= o.field << _bitIndex; _il.Emit(OpCodes.Ldloc_0); // If we write the first bit, use the constant 0 instead of loading the previous value // as otherwise a bit that is true would never be able to become false again if (_bitIndex == 0) _il.Emit(OpCodes.Ldc_I4_0); else { _il.Emit(OpCodes.Dup); _il.Emit(OpCodes.Ldind_U1); } valueLoader(); _il.Emit(OpCodes.Ldc_I4, _bitIndex); _il.Emit(OpCodes.Shl); _il.Emit(OpCodes.Or); _il.Emit(OpCodes.Stind_I1); } /// <summary> /// Generates the code to deserialize a reference field. /// </summary> private void DeserializeReferenceField(StateSlotMetadata metadata) { // o = objs.GetObject(identifier) PrepareFieldAccess(metadata); // v = objs.GetObject(*state) _il.Emit(OpCodes.Ldarg_0); _il.Emit(OpCodes.Ldloc_0); _il.Emit(OpCodes.Ldind_I2); _il.Emit(OpCodes.Call, _getObjectMethod); // o.field = v AccessField(metadata, OpCodes.Stfld); } /// <summary> /// Generates the code to serialize a reference field. /// </summary> private void SerializeReferenceField(StateSlotMetadata metadata) { // s = state _il.Emit(OpCodes.Ldloc_0); // *s = objs.GetObjectIdentifier(o.field) _il.Emit(OpCodes.Ldarg_0); PrepareFieldAccess(metadata); AccessField(metadata, OpCodes.Ldfld); _il.Emit(OpCodes.Call, _getObjectIdentifierMethod); _il.Emit(OpCodes.Stind_I2); } /// <summary> /// Advances the local state variable by <paramref name="byteCount" /> bytes. /// </summary> private void Advance(int byteCount) { if (_bitLevelAddressing) { _bitIndex = (_bitIndex + 1) % 8; if (_bitIndex != 0) return; byteCount = 1; } else if (byteCount == 0) return; // state = state + byteCount; _il.Emit(OpCodes.Ldloc_0); _il.Emit(OpCodes.Ldc_I4, byteCount); _il.Emit(OpCodes.Add); _il.Emit(OpCodes.Stloc_0); } /// <summary> /// Loads the object with the <paramref name="objectIdentifier" /> into the local variable. /// </summary> private void LoadObject(int objectIdentifier) { if (_loadedObject == objectIdentifier) return; // o = objs.GetObject(objectIdentifier) _il.Emit(OpCodes.Ldarg_0); _il.Emit(OpCodes.Ldc_I4, objectIdentifier); _il.Emit(OpCodes.Call, _getObjectMethod); _il.Emit(OpCodes.Stloc_1); _loadedObject = objectIdentifier; } /// <summary> /// Checks whether <paramref name="type" /> is a reference type, i.e., a class or interface. /// </summary> private static bool IsReferenceType(Type type) { return type.IsReferenceType(); } /// <summary> /// Gets the unmanaged size in bytes required to store value of the given <paramref name="type" />. /// </summary> private static int GetUnmanagedSize(Type type) { if (type.IsReferenceType()) return 2; return type.GetUnmanagedSize(); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>AssetGroupListingGroupFilter</c> resource.</summary> public sealed partial class AssetGroupListingGroupFilterName : gax::IResourceName, sys::IEquatable<AssetGroupListingGroupFilterName> { /// <summary>The possible contents of <see cref="AssetGroupListingGroupFilterName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}</c>. /// </summary> CustomerAssetGroupListingGroupFilter = 1, } private static gax::PathTemplate s_customerAssetGroupListingGroupFilter = new gax::PathTemplate("customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id_listing_group_filter_id}"); /// <summary> /// Creates a <see cref="AssetGroupListingGroupFilterName"/> containing an unparsed resource name. /// </summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="AssetGroupListingGroupFilterName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AssetGroupListingGroupFilterName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AssetGroupListingGroupFilterName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AssetGroupListingGroupFilterName"/> with the pattern /// <c>customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="listingGroupFilterId"> /// The <c>ListingGroupFilter</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// A new instance of <see cref="AssetGroupListingGroupFilterName"/> constructed from the provided ids. /// </returns> public static AssetGroupListingGroupFilterName FromCustomerAssetGroupListingGroupFilter(string customerId, string assetGroupId, string listingGroupFilterId) => new AssetGroupListingGroupFilterName(ResourceNameType.CustomerAssetGroupListingGroupFilter, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)), listingGroupFilterId: gax::GaxPreconditions.CheckNotNullOrEmpty(listingGroupFilterId, nameof(listingGroupFilterId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AssetGroupListingGroupFilterName"/> with /// pattern <c>customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="listingGroupFilterId"> /// The <c>ListingGroupFilter</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="AssetGroupListingGroupFilterName"/> with pattern /// <c>customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}</c>. /// </returns> public static string Format(string customerId, string assetGroupId, string listingGroupFilterId) => FormatCustomerAssetGroupListingGroupFilter(customerId, assetGroupId, listingGroupFilterId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AssetGroupListingGroupFilterName"/> with /// pattern <c>customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="listingGroupFilterId"> /// The <c>ListingGroupFilter</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="AssetGroupListingGroupFilterName"/> with pattern /// <c>customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}</c>. /// </returns> public static string FormatCustomerAssetGroupListingGroupFilter(string customerId, string assetGroupId, string listingGroupFilterId) => s_customerAssetGroupListingGroupFilter.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(listingGroupFilterId, nameof(listingGroupFilterId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="AssetGroupListingGroupFilterName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="assetGroupListingGroupFilterName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="AssetGroupListingGroupFilterName"/> if successful.</returns> public static AssetGroupListingGroupFilterName Parse(string assetGroupListingGroupFilterName) => Parse(assetGroupListingGroupFilterName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AssetGroupListingGroupFilterName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="assetGroupListingGroupFilterName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="AssetGroupListingGroupFilterName"/> if successful.</returns> public static AssetGroupListingGroupFilterName Parse(string assetGroupListingGroupFilterName, bool allowUnparsed) => TryParse(assetGroupListingGroupFilterName, allowUnparsed, out AssetGroupListingGroupFilterName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AssetGroupListingGroupFilterName"/> /// instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="assetGroupListingGroupFilterName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AssetGroupListingGroupFilterName"/>, or <c>null</c> if /// parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string assetGroupListingGroupFilterName, out AssetGroupListingGroupFilterName result) => TryParse(assetGroupListingGroupFilterName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AssetGroupListingGroupFilterName"/> /// instance; optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="assetGroupListingGroupFilterName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AssetGroupListingGroupFilterName"/>, or <c>null</c> if /// parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string assetGroupListingGroupFilterName, bool allowUnparsed, out AssetGroupListingGroupFilterName result) { gax::GaxPreconditions.CheckNotNull(assetGroupListingGroupFilterName, nameof(assetGroupListingGroupFilterName)); gax::TemplatedResourceName resourceName; if (s_customerAssetGroupListingGroupFilter.TryParseName(assetGroupListingGroupFilterName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAssetGroupListingGroupFilter(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(assetGroupListingGroupFilterName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private AssetGroupListingGroupFilterName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string assetGroupId = null, string customerId = null, string listingGroupFilterId = null) { Type = type; UnparsedResource = unparsedResourceName; AssetGroupId = assetGroupId; CustomerId = customerId; ListingGroupFilterId = listingGroupFilterId; } /// <summary> /// Constructs a new instance of a <see cref="AssetGroupListingGroupFilterName"/> class from the component parts /// of pattern /// <c>customers/{customer_id}/assetGroupListingGroupFilters/{asset_group_id}~{listing_group_filter_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="listingGroupFilterId"> /// The <c>ListingGroupFilter</c> ID. Must not be <c>null</c> or empty. /// </param> public AssetGroupListingGroupFilterName(string customerId, string assetGroupId, string listingGroupFilterId) : this(ResourceNameType.CustomerAssetGroupListingGroupFilter, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)), listingGroupFilterId: gax::GaxPreconditions.CheckNotNullOrEmpty(listingGroupFilterId, nameof(listingGroupFilterId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>AssetGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AssetGroupId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>ListingGroupFilter</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string ListingGroupFilterId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAssetGroupListingGroupFilter: return s_customerAssetGroupListingGroupFilter.Expand(CustomerId, $"{AssetGroupId}~{ListingGroupFilterId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as AssetGroupListingGroupFilterName); /// <inheritdoc/> public bool Equals(AssetGroupListingGroupFilterName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AssetGroupListingGroupFilterName a, AssetGroupListingGroupFilterName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AssetGroupListingGroupFilterName a, AssetGroupListingGroupFilterName b) => !(a == b); } public partial class AssetGroupListingGroupFilter { /// <summary> /// <see cref="AssetGroupListingGroupFilterName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal AssetGroupListingGroupFilterName ResourceNameAsAssetGroupListingGroupFilterName { get => string.IsNullOrEmpty(ResourceName) ? null : AssetGroupListingGroupFilterName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="AssetGroupName"/>-typed view over the <see cref="AssetGroup"/> resource name property. /// </summary> internal AssetGroupName AssetGroupAsAssetGroupName { get => string.IsNullOrEmpty(AssetGroup) ? null : AssetGroupName.Parse(AssetGroup, allowUnparsed: true); set => AssetGroup = value?.ToString() ?? ""; } /// <summary> /// <see cref="AssetGroupListingGroupFilterName"/>-typed view over the <see cref="ParentListingGroupFilter"/> /// resource name property. /// </summary> internal AssetGroupListingGroupFilterName ParentListingGroupFilterAsAssetGroupListingGroupFilterName { get => string.IsNullOrEmpty(ParentListingGroupFilter) ? null : AssetGroupListingGroupFilterName.Parse(ParentListingGroupFilter, allowUnparsed: true); set => ParentListingGroupFilter = value?.ToString() ?? ""; } } }
using System; using System.Drawing; using System.Xml; //copied from http://www.codeproject.com/Articles/28717/A-custom-range-selector-control-in-C-with-a-little namespace CustomRangeSelectorControl { /// <summary> /// This is the notification EventArgs for updates to the current range /// </summary> /// public class RangeUpdateEventArgs : EventArgs { public RangeUpdateEventArgs(string minRange, string maxRange) { MinRangeSelected = minRange; MaxRangeSelected = maxRange; } public string MinRangeSelected {get; private set;} public string MaxRangeSelected { get; private set; } } /// <summary> /// This is a custom control that allows the user of the control to select a range of values /// using two "thumbs". The control allows the client to change the appearance of the control. /// For example, there are design time options to control the size of thumb, the size of the /// middle bar and background color, in-focus color and disabled color of the control etc... /// </summary> /// [ToolboxBitmap(typeof(CustomRangeSelectorControl.RangeSelectorControl), "CustomRangeSelectorControl/RangeScale.bmp")] public class RangeSelectorControl : DotNetControlsEx.AutoDoubleBufferedControl { /// <ControlVariables> /// The Below are Design time (Also Runtime) Control Variables. These variables /// can be used by the client to change the appearance of the control. These are /// private varibles. The user of the control will be using the public properties /// to change/modify the values. /// </ControlVariables> /// #region Design Time Control Variables -- Private Variables private string strXMLFileName; // XML File Name that is used for picking up the Label Values private string strRangeString; // The String that is displayed at the bottom of the control. private string strRange; // An alternate to the XML File Name where the Range Label values are stored private int intRangeMax; // Max range value private int intRangeMin; // Min range value private double doubleRangeStep; // Range step unit private Font fntLabelFont; // Font of the Label private FontStyle fntLabelFontStyle; // Font Style of the Label private float fLabelFontSize; // Size of the Label private FontFamily fntLabelFontFamily; // Font Family of the Label private string strLeftImagePath; // Left Thumb Image Path private string strRightImagePath; // Right Thumb Image Path private float fHeightOfThumb; // Height Of the Thumb private float fWidthOfThumb; // Width of the Thumb private Color clrThumbColor; // Color of the Thumb, If not Image private Color clrInFocusBarColor; // In Focus Bar Colour private Color clrDisabledBarColor; // Disabled Bar Color private Color clrInFocusRangeLabelColor; // In Focus Range Label Color private Color clrDisabledRangeLabelColor; // Disabled Range label Color private uint unSizeOfMiddleBar; // Thickness of the Middle bar private uint unGapFromLeftMargin; // Gap from the Left Margin to draw the Bar private uint unGapFromRightMargin; // Gap from the Right Margin to draw the Bar private string strDelimiter; // Delimiter used to seperate the Labels in strRange variable private int intRangeMinSelected; // integer position of thumb1 private int intRangeMaxSelected; // integer position of thumb2 //private string strRange1; // Thumb 1 Position bar //private string strRange2; // Thumb 2 Position in the bar private string strRange1Temp; private string strRange2Temp; private Font fntRangeOutputStringFont; // Range Output string font private float fStringOutputFontSize; // String Output Font Size private Color clrStringOutputFontColor; // Color of the Output Font private FontFamily fntStringOutputFontFamily; // Font Family to display the Range string private bool bShowStepLabels; // indicates whether or not to show the step label private bool bUseCustomLabels; // indicates if control should use custom or automatic labels /// <ControlVariables> /// The Above are Design time Control Variables. These variables can be used by the client /// to change the appearance of the control. /// </ControlVariables> /// #endregion /// <ControlProperties> /// The Below are Design time (Also Runtime) Control Variable properties. These variables /// can be used by the client to change the appearance of the control. /// </ControlProperties> /// #region Design Time Control Properties -- Public -- Design Time User properites - Can also be changed runtime /// <XMLFileName> /// XMLFileName is a property that can be used to set the Range Labels /// For Example: /// <?xml version="1.0" encoding="utf-8" ?> /// <RangeController> /// <Values> /// <Value> Excellent</Value> /// <Value> Good</Value> /// <Value> Fair</Value> /// <Value> Poor</Value> /// </Values> /// </RangeController> /// /// Here the values Excellent, Good, Fair and Poor will be taken as Labels for the /// Control. /// </XMLFileName> /// public string XMLFileName { set { try { strXMLFileName = value; if (null != strXMLFileName) { xmlTextReader = new System.Xml.XmlTextReader(strXMLFileName); strRange = null; while(xmlTextReader.Read()) { switch(xmlTextReader.NodeType) { case System.Xml.XmlNodeType.Text: strRange += xmlTextReader.Value.Trim(); strRange += strDelimiter; break; } } strRange = strRange.Remove(strRange.Length - strDelimiter.Length, strDelimiter.Length); CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } } catch { strXMLFileName = null; //strRange = ""; //CalculateValues(); //this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); System.Windows.Forms.MessageBox.Show("The XML Path entered may be invalid (or) The XML file is not well formed", "Error!"); } } get { return strXMLFileName; } } /// <RangeString> /// RangeString is a property that can be used to set the Range String /// This is the string that is displayed at the bottom of the control /// </RangeString> /// public string RangeString { set { strRangeString = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return strRangeString; } } /// <RangeValues> /// Range Values are the values displayed as labels. These values can be given by the user /// seperated by a Delimiter (Usually a comma ','); /// </RangeValues> /// public string RangeValues { set { if (!string.IsNullOrEmpty(value)) { // Splitting the Range Value to display in the control //strSplitLabels = strRange.Split(strDelimiter.ToCharArray(), 1024); //nNumberOfLabels = strSplitLabels.Length; strRange = value; Range1 = strRange1Temp; Range2 = strRange2Temp; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } } get { return strRange; } } /// <RangeMax> /// Range Max is the maximum value of the slider /// RangeValues in the range can be automatic or user defined /// </RangeMax> public int RangeMax { set { intRangeMax = value; CalculateValues(); this.Refresh(); WindUpdated(); } get { return intRangeMax; } } /// <RangeMin> /// Range Max is the minimum value of the slider /// RangeValues in the range can be automatic or user defined /// </RangeMin> public int RangeMin { set { intRangeMin = value; CalculateValues(); this.Refresh(); WindUpdated(); } get { return intRangeMin; } } /// <RangeStep> /// Range Step defines the automatic values between RangeMin and RangeMax /// </RangeStep> public double RangeStep { set { if (value <= 0) { throw new ArgumentException("RangeStep must be greater than zero", "RangeStep"); return; } doubleRangeStep = value; CalculateValues(); this.Refresh(); WindUpdated(); } get { return doubleRangeStep; } } /// <UseCustomLabels> /// Indicate whether or not to use custom labels /// </UseCustomLabels> public bool UseCustomLabels { set { bUseCustomLabels = value; CalculateValues(); this.Refresh(); WindUpdated(); } get { return bUseCustomLabels; } } /// <ShowStepLabels> /// Indicates whether or not the step labels are displayed /// </ShowStepLabels> public bool ShowStepLabels { set { bShowStepLabels = value; CalculateValues(); this.Refresh(); WindUpdated(); } get { return bShowStepLabels; } } /// <LabelFont> /// The user can specify the font to use for the labels. The Setter and getter methods are as below /// </Label Font> /// public Font LabelFont { set { fntLabelFont = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return fntLabelFont; } } /// <LeftThumbImagepath> /// The user can specify the Left Thumb Image path to use. The Setter and getter methods are as below /// </LeftThumbImagePath> /// public string LeftThumbImagePath { set { try { strLeftImagePath = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } catch { System.Windows.Forms.MessageBox.Show("Invalid Image Path. Please Re-Enter", "Error!"); } } get { return strLeftImagePath; } } /// <RightThumbImagepath> /// The user can specify the Right Thumb Image path to use. The Setter and getter methods are as below /// </RightThumbImagePath> /// public string RightThumbImagePath { set { try { strRightImagePath = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } catch { strRightImagePath = null; System.Windows.Forms.MessageBox.Show("Invalid Image Path. Please Re-Enter", "Error!"); } } get { return strRightImagePath; } } /// <HeightOfThumb> /// The user can specify the Height of the Thumb Image path to use. The Setter and getter methods are as below /// </HeightOfThumb> /// public float HeightOfThumb { set { fHeightOfThumb = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return fHeightOfThumb; } } /// <WidthOfThumb> /// The user can specify the Width of the Thumb Image path to use. The Setter and getter methods are as below /// </WidthOfThumb> /// public float WidthOfThumb { set { fWidthOfThumb = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return fWidthOfThumb; } } /// <InFocusBarColor> /// The user can specify the Infocus Bar Color to use. The Setter and getter methods are as below /// </InFocusBarColor> /// public Color InFocusBarColor { set { clrInFocusBarColor = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return clrInFocusBarColor; } } /// <DisabledBarColor> /// The user can specify the Disabled Bar Color to use. The Setter and getter methods are as below /// </DisabledBarColor> /// public Color DisabledBarColor { set { clrDisabledBarColor = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return clrDisabledBarColor; } } /// <ThumbColor> /// The user can specify the Thumb Color to use. The Setter and getter methods are as below /// </ThumbColor> /// public Color ThumbColor { set { clrThumbColor = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return clrThumbColor; } } /// <InFocusRangeLabelColor> /// The user can specify the InFocus Range Label Color to use. The Setter and getter methods are as below /// </InFocusRangeLabelColor> /// public Color InFocusRangeLabelColor { set { clrInFocusRangeLabelColor = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return clrInFocusRangeLabelColor; } } /// <DisabledRangeLabelColor> /// The user can specify the InFocus Range Label Color to use. The Setter and getter methods are as below /// </DisabledRangeLabelColor> /// public Color DisabledRangeLabelColor { set { clrDisabledRangeLabelColor = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return clrDisabledRangeLabelColor; } } /// <SizeOfMiddleBar> /// The user can specify the Sizeof Middle Bar to use. The Setter and getter methods are as below /// </SizeOfMiddleBar> /// public uint MiddleBarWidth { set { unSizeOfMiddleBar = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return unSizeOfMiddleBar; } } /// <GapFromLeftMargin> /// The user can specify the Gap from Left margin. The Setter and getter methods are as below /// </GapFromLeftMargin> /// public uint GapFromLeftMargin { set { unGapFromLeftMargin = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return unGapFromLeftMargin; } } /// <GapFromRightMargin> /// The user can specify the Gap from Left margin. The Setter and getter methods are as below /// </GapFromRightMargin> /// public uint GapFromRightMargin { set { unGapFromRightMargin = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return unGapFromRightMargin; } } /// <DelimeterForRange> /// The user can specify the Delimiter for the Range Values. The Setter and getter methods are as below /// </DelimeterForRange> /// public string DelimiterForRange { set { try { strDelimiter = value; string strTempString; strTempString = ")*~`!@#/?\"'][{}=-_+&^%$\\|"; if (!strDelimiter.Equals(strDelimiter.TrimStart(strTempString.ToCharArray()))) { System.Windows.Forms.MessageBox.Show("The Delimiter specified is not right", "Error!"); strDelimiter = ","; } CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } catch { System.Windows.Forms.MessageBox.Show("The Delimiter specified is not right", "Error!"); strDelimiter = ","; } } get { return strDelimiter; } } /// <Range1> /// The user can specify the Range1 Value. The Setter and getter methods are as below /// </Range1> /// public string Range1 { set { if (value == null) return; if (strRange1Temp == null || ! strRange1Temp.Equals(value)) { strRange1Temp = value; SetMinSelected(strRange1Temp); } } get { return strRange1Temp; } } private void SetMinSelected(string val) { var sel = Array.FindIndex(strSplitLabels, s => s == val); if (sel > -1 && sel != intRangeMinSelected) { intRangeMinSelected = sel; CalculateValues(); this.Refresh(); WindUpdated(); } } private void SetMaxSelected(string val) { var sel = Array.FindIndex(strSplitLabels, s => s == val); if (sel > -1 && sel != intRangeMaxSelected) { intRangeMaxSelected = sel; CalculateValues(); this.Refresh(); WindUpdated(); } } /// <Range2> /// The user can specify the Range2 Value. The Setter and getter methods are as below /// </Range2> /// public string Range2 { set { if (value == null) return; if (strRange2Temp == null || ! strRange2Temp.Equals(value)) { strRange2Temp = value; SetMaxSelected(strRange2Temp); } } get { return strRange2Temp; } } /// <OutputStringFontColor> /// The user can specify the Output String Font Color Value. The Setter and getter methods are as below /// </OutputStringFontColor> /// public Color OutputStringFontColor { set { clrStringOutputFontColor = value; CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } get { return clrStringOutputFontColor; } } /// <ControlProperties> /// The Above are Design time (Also Runtime) Control Variable properties. These variables /// can be used by the client to change the appearance of the control. /// </ControlProperties> /// #endregion #region Control Events public event EventHandler<RangeUpdateEventArgs> RangeUpdate; #endregion Control Events /// <ProgramVariables> /// The Below are Variables used for computation. /// </ProgramVariables> /// #region Variables Used for Computation private Image imImageLeft; //Variable for Left Image private Image imImageRight; // Variable for Right Image private NotifyClient objNotifyClient; // This is For Client Notification object private bool bMouseEventThumb1; // Variable for Thumb1Click private bool bMouseEventThumb2; // Variable for Thumb2Click private float fThumb1Point; // Variable to hold Mouse point on Thumb1 private float fThumb2Point; // Variable to hold Mouse point on Thumb2 private float fLeftCol; // Left Column private float fLeftRow; // Left Row private float fRightCol; // Right Column private float fRightRow; // Right Row private float fTotalWidth; // Total Width private float fDividedWidth; // Divided Width //private PaintEventArgs ePaintArgs; // Paint Args private int nNumberOfLabels; // Total Number of Labels private string[] strSplitLabels; // To store the Split Labels private PointF[] ptThumbPoints1; // To Store Thumb Point1 private PointF[] ptThumbPoints2; // To Store Thumb2 Point private XmlTextReader xmlTextReader; // XML Reader Class private bool bAnimateTheSlider; // Animate the Control private float fThumbPoint1Prev; // To Store Thumb Point1 private float fThumbPoint2Prev; // To Store Thumb2 Point #endregion /// <ProgramVariables> /// The Below are Variables used for computation. /// </ProgramVariables> /// private System.ComponentModel.Container components = null; public RangeSelectorControl() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); /// <VariableInit> /// The Below are Initialization of Variables to its Default values. /// </VariableInit> /// #region Initialization of Variables to its Default Values if (null != strLeftImagePath) { imImageLeft = System.Drawing.Image.FromFile(strLeftImagePath); } if (null != strRightImagePath) { imImageRight = System.Drawing.Image.FromFile(strRightImagePath); } objNotifyClient = null; strRangeString = "Range"; strDelimiter = ","; // Because in Germany decimal point is represented as , i.e., "10.50 in US" is "10,50 in Germany" strRange = "0,10,20,30,Good,50,60,70,Great,90,100"; strRange1Temp = "10"; strRange2Temp = "90"; strLeftImagePath = null; strRightImagePath = null; fHeightOfThumb = 20.0f; fWidthOfThumb = 10.0f; this.BackColor = System.Drawing.Color.LightBlue; clrInFocusBarColor = System.Drawing.Color.Magenta; clrDisabledBarColor = System.Drawing.Color.Gray; clrInFocusRangeLabelColor = System.Drawing.Color.Green; clrDisabledRangeLabelColor = System.Drawing.Color.Gray; clrThumbColor = System.Drawing.Color.Purple; fStringOutputFontSize = 10.0f; clrStringOutputFontColor = System.Drawing.Color.Black; fntStringOutputFontFamily = System.Drawing.FontFamily.GenericSansSerif; fntRangeOutputStringFont = new System.Drawing.Font(fntStringOutputFontFamily, fStringOutputFontSize, System.Drawing.FontStyle.Regular); bUseCustomLabels = true; bShowStepLabels = true; intRangeMax = 10; intRangeMin = 0; doubleRangeStep = 1; unSizeOfMiddleBar = 3; unGapFromLeftMargin = 10; unGapFromRightMargin = 10; fntLabelFontFamily = System.Drawing.FontFamily.GenericSansSerif; fLabelFontSize = 8.25f; fntLabelFontStyle = System.Drawing.FontStyle.Bold; fntLabelFont = new System.Drawing.Font(fntLabelFontFamily, fLabelFontSize, fntLabelFontStyle); strSplitLabels = new string[0]; ptThumbPoints1 = new System.Drawing.PointF[3]; ptThumbPoints2 = new System.Drawing.PointF[3]; bMouseEventThumb1 = false; bMouseEventThumb2 = false; bAnimateTheSlider = false; #endregion /// <VariableInit> /// The Below are Initialization of Variables to its Default values. /// </VariableInit> /// } /// <InterfacesExposed> /// The Below are Interfaces/Methods exposed to the client /// </InterfacesExposed> /// #region Methods Exposed to client at runtime /// <QueryRange> /// The client can query this method to get the range /// </QueryRange> /// public void QueryRange(out string strGetRange1, out string strGetRange2) { strGetRange1 = Range1.ToString(); strGetRange2 = Range2.ToString(); } /// <RegisterForChangeEvent> /// The client can Register for automatic update whenever the values are changing /// </RegisterForChangeEvent> /// public void RegisterForChangeEvent(ref NotifyClient refNotifyClient) { // If there's a valid object, the values are copied. try { if (null != refNotifyClient) { objNotifyClient = refNotifyClient; objNotifyClient.Range1 = Range1; objNotifyClient.Range2 = Range2; } } catch { System.Windows.Forms.MessageBox.Show("The Registered Event object has a Bad memory. Please correct it", "Error!"); } } #endregion /// <CalculateValues> /// The below is the method that calculates the values to be place while painting /// </CalculateValues> /// #region This is a Private method that calculates the values to be placed while painting private void CalculateValues() { try { // Creating the Graphics object System.Drawing.Graphics myGraphics = this.CreateGraphics(); if (bUseCustomLabels) { // Split the Labels to be displayed below the Bar strSplitLabels = strRange.Split(strDelimiter.ToCharArray(), 1024); nNumberOfLabels = strSplitLabels.Length; } else { if (doubleRangeStep <= 0) throw new ArgumentException("Step size must be positive with UseCustomLabels=false", "doubleRangeStep"); nNumberOfLabels = (int)((intRangeMax - intRangeMin) / doubleRangeStep) + 1; strSplitLabels = new string[nNumberOfLabels]; //build automatic labels for (int i = 0; i < nNumberOfLabels; ++i) { if ((double)(int)doubleRangeStep == doubleRangeStep) strSplitLabels[i] = string.Format("{0}", intRangeMin + (int)(i * doubleRangeStep)); else strSplitLabels[i] = string.Format("{0:0.00}", intRangeMin + (i * doubleRangeStep)); } } // If there's an image load the Image from the file if (null != strLeftImagePath) { imImageLeft = System.Drawing.Image.FromFile(strLeftImagePath); } if (null != strRightImagePath) { imImageRight = System.Drawing.Image.FromFile(strRightImagePath); } // Calculate the Left, Right values based on the Clip region bounds RectangleF recRegion = myGraphics.VisibleClipBounds; fLeftCol = unGapFromLeftMargin; fLeftRow = recRegion.Height / 2.0f; // To display the Bar in the middle fRightCol = recRegion.Width - unGapFromRightMargin; fRightRow = fLeftRow; fThumb1Point = fLeftCol; fThumb2Point = fRightCol; fTotalWidth = recRegion.Width - (unGapFromRightMargin + unGapFromLeftMargin); fDividedWidth = fTotalWidth / (float)(nNumberOfLabels - 1); int nRangeIndex1Selected = 0; int nRangeIndex2Selected = nNumberOfLabels - 1; SetMinSelected(Range1); SetMaxSelected(Range2); // This is used to calculate the Thumb Point from the Range1, Range2 Value for(int nIndexer = 0;nIndexer < nNumberOfLabels;nIndexer++) { if ( intRangeMinSelected == nIndexer /*strRange1.Equals(strSplitLabels[nIndexer])*/) { fThumb1Point = fLeftCol + fDividedWidth * nIndexer; nRangeIndex1Selected = nIndexer; } if ( intRangeMaxSelected == nIndexer /*strRange2.Equals(strSplitLabels[nIndexer])*/) { fThumb2Point = fLeftCol + fDividedWidth * nIndexer; nRangeIndex2Selected = nIndexer; } } if ( intRangeMinSelected == intRangeMaxSelected /*strRange1 == strRange2*/) { if (nRangeIndex1Selected != 0) { fThumb1Point -= fDividedWidth / 2.0f; } if (nRangeIndex2Selected != nNumberOfLabels - 1) { fThumb2Point += fDividedWidth / 2.0f; } } // This is for Calculating the final Thumb points ptThumbPoints1[0].X = fThumb1Point; ptThumbPoints1[0].Y = fLeftRow - 3.0f; ptThumbPoints1[1].X = fThumb1Point; ptThumbPoints1[1].Y = fLeftRow - 3.0f - fHeightOfThumb; ptThumbPoints1[2].X = (fThumb1Point + fWidthOfThumb); ptThumbPoints1[2].Y = fLeftRow - 3.0f - fHeightOfThumb/2.0f; ptThumbPoints2[0].X = fThumb2Point; ptThumbPoints2[0].Y = fRightRow - 3.0f; ptThumbPoints2[1].X = fThumb2Point; ptThumbPoints2[1].Y = fRightRow - 3.0f - fHeightOfThumb; ptThumbPoints2[2].X = fThumb2Point - fWidthOfThumb; ptThumbPoints2[2].Y = fRightRow - 3.0f - fHeightOfThumb/2.0f; } catch { //throw; //System.Windows.Forms.MessageBox.Show("An unexpected Error occured. Please contact the vendor of this control", "Error"); } } /// <CalculateValues> /// The below is the method that calculates the values to be place while painting /// </CalculateValues> /// #endregion /// <Paint > /// The below is the method that draws the control on the screen /// </Paint > /// #region Paint Method Override -- This method draws the control on the screen private void OnPaintDrawSliderAndBar(System.Drawing.Graphics myGraphics) { System.Drawing.Brush brSolidBrush; System.Drawing.Pen myPen; // If Interesting mouse event happened on the Thumb1 Draw Thumb1 if (bMouseEventThumb1) { brSolidBrush = new System.Drawing.SolidBrush(this.BackColor); if (null != strLeftImagePath) { myGraphics.FillRectangle(brSolidBrush, ptThumbPoints1[0].X, ptThumbPoints1[1].Y, fWidthOfThumb, fHeightOfThumb); } else { myGraphics.FillClosedCurve(brSolidBrush, ptThumbPoints1, System.Drawing.Drawing2D.FillMode.Winding, 0f); } } //if interesting mouse event happened on Thumb2 draw thumb2 if (bMouseEventThumb2) { brSolidBrush = new System.Drawing.SolidBrush(this.BackColor); if (null != strRightImagePath) { myGraphics.FillRectangle(brSolidBrush, ptThumbPoints2[2].X, ptThumbPoints2[1].Y, fWidthOfThumb, fHeightOfThumb); } else { myGraphics.FillClosedCurve(brSolidBrush, ptThumbPoints2, System.Drawing.Drawing2D.FillMode.Winding, 0f); } } // The Below lines are to draw the Thumb and the Lines // The Infocus and the Disabled colors are drawn properly based // onthe calculated values brSolidBrush = new System.Drawing.SolidBrush(clrInFocusRangeLabelColor); myPen = new System.Drawing.Pen(clrInFocusRangeLabelColor, unSizeOfMiddleBar); ptThumbPoints1[0].X = fThumb1Point; ptThumbPoints1[1].X = fThumb1Point; ptThumbPoints1[2].X = fThumb1Point + fWidthOfThumb; ptThumbPoints2[0].X = fThumb2Point; ptThumbPoints2[1].X = fThumb2Point; ptThumbPoints2[2].X = fThumb2Point - fWidthOfThumb; myPen = new System.Drawing.Pen(clrDisabledBarColor, unSizeOfMiddleBar); myGraphics.DrawLine(myPen, fLeftCol, ptThumbPoints1[2].Y, fThumb1Point, ptThumbPoints1[2].Y); myGraphics.DrawLine(myPen, fLeftCol, ptThumbPoints1[2].Y, fLeftCol, ptThumbPoints1[2].Y + fntLabelFont.SizeInPoints); myGraphics.DrawLine(myPen, fRightCol, ptThumbPoints1[2].Y, fRightCol, ptThumbPoints1[2].Y + fntLabelFont.SizeInPoints); brSolidBrush = new System.Drawing.SolidBrush(clrStringOutputFontColor); myGraphics.DrawString(strRangeString, fntRangeOutputStringFont, brSolidBrush, fLeftCol, fLeftRow * 2 - fntRangeOutputStringFont.Height); myPen = new System.Drawing.Pen(clrInFocusBarColor, unSizeOfMiddleBar); myGraphics.DrawLine(myPen, ptThumbPoints1[2].X, ptThumbPoints1[2].Y, fThumb2Point,/* - fWidthOfThumb*/ ptThumbPoints1[2].Y); myPen = new System.Drawing.Pen(clrDisabledBarColor, unSizeOfMiddleBar); myGraphics.DrawLine(myPen, fThumb2Point, ptThumbPoints2[2].Y, fRightCol, ptThumbPoints2[2].Y); // If the Thumb is an Image it draws the Image or else it draws the Thumb if (null != strLeftImagePath) { myGraphics.DrawImage(imImageLeft, ptThumbPoints1[0].X, ptThumbPoints1[1].Y, fWidthOfThumb, fHeightOfThumb); } else { brSolidBrush = new System.Drawing.SolidBrush(clrThumbColor); myGraphics.FillClosedCurve(brSolidBrush, ptThumbPoints1, System.Drawing.Drawing2D.FillMode.Winding, 0f); } // If the Thumb is an Image it draws the Image or else it draws the Thumb if (null != strRightImagePath) { myGraphics.DrawImage(imImageRight, ptThumbPoints2[2].X, ptThumbPoints2[1].Y, fWidthOfThumb, fHeightOfThumb); } else { brSolidBrush = new System.Drawing.SolidBrush(clrThumbColor); myGraphics.FillClosedCurve(brSolidBrush, ptThumbPoints2, System.Drawing.Drawing2D.FillMode.Winding, 0f); } } public void WindUpdated() { this.Invalidate(); this.Update(); } protected override void DoPaint(Graphics myGraphics) { try { // Declaration of the local variables that are used. System.Drawing.Brush brSolidBrush; float fDividerCounter; float fIsThumb1Crossed, fIsThumb2Crossed; string strRangeOutput; string strNewRange1, strNewRange2; // Initialization of the local variables. //System.Drawing.Graphics myGraphics = this.CreateGraphics(); //ePaintArgs = e; fDividerCounter = 0; brSolidBrush = new System.Drawing.SolidBrush(clrDisabledRangeLabelColor); strNewRange1 = null; strNewRange2 = null; // This loop is to draw the Labels on the screen. for (int nIndexer = 0; nIndexer < nNumberOfLabels; nIndexer++) { fDividerCounter = fLeftCol + fDividedWidth * nIndexer; if (bShowStepLabels)//split by size of labels { fIsThumb1Crossed = fDividerCounter + strSplitLabels[nIndexer].Length * fntLabelFont.SizeInPoints / 2; fIsThumb2Crossed = fDividerCounter - (strSplitLabels[nIndexer].Length - 1) * fntLabelFont.SizeInPoints / 2; } else // split by even sizes { fIsThumb1Crossed = fDividerCounter + fDividedWidth / 2; fIsThumb2Crossed = fDividerCounter - fDividedWidth / 2; } if (fIsThumb1Crossed >= fThumb1Point && strNewRange1 == null) { // If Thumb1 Crossed this Label Make it in Focus color brSolidBrush = new System.Drawing.SolidBrush(clrInFocusRangeLabelColor); strNewRange1 = strSplitLabels[nIndexer]; } if (fIsThumb2Crossed > fThumb2Point) { // If Thumb2 crossed this draw the labes following this in disabled color brSolidBrush = new System.Drawing.SolidBrush(clrDisabledRangeLabelColor); //strNewRange2 = strSplitLabels[nIndexer]; } else { strNewRange2 = strSplitLabels[nIndexer]; } if (bShowStepLabels) myGraphics.DrawString(strSplitLabels[nIndexer], fntLabelFont, brSolidBrush, fDividerCounter - ((fntLabelFont.SizeInPoints) * strSplitLabels[nIndexer].Length) / 2, fLeftRow); } // This is to draw exactly the Range String like "Range 10 to 100" // This will draw the information only if there is a change. if (strNewRange1 != null && strNewRange2 != null && (!Range1.Equals(strNewRange1) || !Range2.Equals(strNewRange2)) || (!bMouseEventThumb1 && !bMouseEventThumb2)) { //draw over the old string with the BackColor brSolidBrush = new System.Drawing.SolidBrush(this.BackColor); strRangeOutput = Range1 + " - " + Range2; myGraphics.DrawString(strRangeOutput , fntRangeOutputStringFont, brSolidBrush, fLeftCol + fntRangeOutputStringFont.Size * strRangeString.Length , fLeftRow * 2 - fntRangeOutputStringFont.Height); //draw the new string brSolidBrush = new System.Drawing.SolidBrush(clrStringOutputFontColor); strRangeOutput = strNewRange1 + " - " + strNewRange2; myGraphics.DrawString(strRangeOutput , fntRangeOutputStringFont, brSolidBrush, fLeftCol + fntRangeOutputStringFont.Size * strRangeString.Length , fLeftRow * 2 - fntRangeOutputStringFont.Height); Range1 = strNewRange1; Range2 = strNewRange2; } if (bAnimateTheSlider) { float fTempThumb1Point = fThumb1Point; float fTempThumb2Point = fThumb2Point; int nToMakeItTimely = System.Environment.TickCount; for (fThumb1Point = fThumbPoint1Prev, fThumb2Point = fThumbPoint2Prev; fThumb1Point <= fTempThumb1Point || fThumb2Point >= fTempThumb2Point; fThumb1Point += 3.0f, fThumb2Point -= 3.0f) { bMouseEventThumb1 = true; bMouseEventThumb2 = true; if (fThumb1Point > fTempThumb1Point) { fThumb1Point = fTempThumb1Point; } if (fThumb2Point < fTempThumb2Point) { fThumb2Point = fTempThumb2Point; } OnPaintDrawSliderAndBar(myGraphics); if (System.Environment.TickCount - nToMakeItTimely >= 1000) { // Hey its not worth having animation for more than 1 sec. break; } System.Threading.Thread.Sleep(1); } fThumb1Point = fTempThumb1Point; fThumb2Point = fTempThumb2Point; bMouseEventThumb1 = true; bMouseEventThumb2 = true; OnPaintDrawSliderAndBar(myGraphics); bAnimateTheSlider = false; bMouseEventThumb1 = false; bMouseEventThumb2 = false; OnPaintDrawSliderAndBar(myGraphics); } else { OnPaintDrawSliderAndBar(myGraphics); } // calling the base class. base.DoPaint (myGraphics); } catch { //System.Windows.Forms.MessageBox.Show("An Unexpected Error occured. Please contact the tool vendor", "Error!"); //throw; } } /// <Paint > /// The Above is the method that draws the control on the screen /// </Paint > #endregion /// <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() { // // RangeSelectorControl // this.Name = "RangeSelectorControl"; this.Size = new System.Drawing.Size(360, 80); this.Resize += new System.EventHandler(this.RangeSelectorControl_Resize); //this.Load += new System.EventHandler(this.RangeSelectorControl_Load); this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.RangeSelectorControl_MouseUp); this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.RangeSelectorControl_MouseMove); this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.RangeSelectorControl_MouseDown); } #endregion //private void RangeSelectorControl_Load(object sender, System.EventArgs e) //{ // CalculateValues(); //} /// <MouseEvents> /// The below are the methods used for handling Mouse Events /// </Mouse Events> /// #region Methods used for handling Mouse Events private void RangeSelectorControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { // If the Mouse is Up then set the Event to false bMouseEventThumb1 = false; bMouseEventThumb2 = false; // Storing these values for animating the slider fThumbPoint1Prev = fThumb1Point; fThumbPoint2Prev = fThumb2Point; CalculateValues(); bAnimateTheSlider = true; this.Refresh(); this.WindUpdated(); } private void RangeSelectorControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { // If the Mouse is Down and also on the Thumb1 if (e.X >= ptThumbPoints1[0].X && e.X <= ptThumbPoints1[2].X && e.Y >= ptThumbPoints1[1].Y && e.Y <= ptThumbPoints1[0].Y) { bMouseEventThumb1 = true; } // Else If the Mouse is Down and also on the Thumb2 else if (e.X >= ptThumbPoints2[2].X && e.X <= ptThumbPoints2[0].X && e.Y >= ptThumbPoints2[1].Y && e.Y <= ptThumbPoints2[0].Y) { bMouseEventThumb2 = true; } bAnimateTheSlider = false; } private void RangeSelectorControl_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { // If the Mouse is moved pressing the left button on Thumb1 if (bMouseEventThumb1 && e.Button == System.Windows.Forms.MouseButtons.Left && e.X >= fLeftCol ) { // The below code is for handlling the Thumb1 Point if (intRangeMinSelected == intRangeMaxSelected /*strRange1.Equals(strRange2)*/) { if (e.X < fThumb1Point) { fThumb1Point = e.X; //OnPaint(ePaintArgs); WindUpdated(); } } else if (fThumb2Point - fWidthOfThumb > e.X) { fThumb1Point = e.X; //OnPaint(ePaintArgs); WindUpdated(); } else { bMouseEventThumb1 = false; } } //Else If the Mouse is moved pressing the left button on Thumb2 else if (bMouseEventThumb2 && e.Button == System.Windows.Forms.MouseButtons.Left && e.X <= fRightCol) { // The below code is for handlling the Thumb1 Point if (intRangeMinSelected == intRangeMaxSelected /*strRange1.Equals(strRange2)*/) { if (e.X > fThumb2Point) { fThumb2Point = e.X; //OnPaint(ePaintArgs); WindUpdated(); } } else if (fThumb1Point + fWidthOfThumb < e.X) { fThumb2Point = e.X; //OnPaint(ePaintArgs); WindUpdated(); } else { bMouseEventThumb2 = false; } } // If there is an Object Notification if (null != objNotifyClient) { objNotifyClient.Range1 = Range1; objNotifyClient.Range2 = Range2; } var temp = RangeUpdate; if (temp != null) { temp(this, new RangeUpdateEventArgs(Range1, Range2)); } } /// <MouseEvents> /// The below are the methods used for handling Mouse Events /// </Mouse Events> /// #endregion /// <RangeSelectorControl_Resize> /// The below are the method is used if the form is resized /// </RangeSelectorControl_Resize> /// private void RangeSelectorControl_Resize(object sender, System.EventArgs e) { CalculateValues(); this.Refresh(); //OnPaint(ePaintArgs); WindUpdated(); } } /// <RangeSelectorControl_Resize> /// The below is the small Notification class that can be used by the client /// </RangeSelectorControl_Resize> /// #region Notification class for client to register with the control for changes public class NotifyClient { private string strRange1, strRange2; public string Range1 { set { strRange1 = value; } get { return strRange1; } } public string Range2 { set { strRange2 = value; } get { return strRange2; } } } /// <RangeSelectorControl_Resize> /// The Above is the small Notification class that can be used by the client /// </RangeSelectorControl_Resize> /// #endregion }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type OnenoteOperationRequest. /// </summary> public partial class OnenoteOperationRequest : BaseRequest, IOnenoteOperationRequest { /// <summary> /// Constructs a new OnenoteOperationRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public OnenoteOperationRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified OnenoteOperation using POST. /// </summary> /// <param name="onenoteOperationToCreate">The OnenoteOperation to create.</param> /// <returns>The created OnenoteOperation.</returns> public System.Threading.Tasks.Task<OnenoteOperation> CreateAsync(OnenoteOperation onenoteOperationToCreate) { return this.CreateAsync(onenoteOperationToCreate, CancellationToken.None); } /// <summary> /// Creates the specified OnenoteOperation using POST. /// </summary> /// <param name="onenoteOperationToCreate">The OnenoteOperation to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created OnenoteOperation.</returns> public async System.Threading.Tasks.Task<OnenoteOperation> CreateAsync(OnenoteOperation onenoteOperationToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<OnenoteOperation>(onenoteOperationToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified OnenoteOperation. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified OnenoteOperation. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<OnenoteOperation>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified OnenoteOperation. /// </summary> /// <returns>The OnenoteOperation.</returns> public System.Threading.Tasks.Task<OnenoteOperation> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified OnenoteOperation. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The OnenoteOperation.</returns> public async System.Threading.Tasks.Task<OnenoteOperation> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<OnenoteOperation>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified OnenoteOperation using PATCH. /// </summary> /// <param name="onenoteOperationToUpdate">The OnenoteOperation to update.</param> /// <returns>The updated OnenoteOperation.</returns> public System.Threading.Tasks.Task<OnenoteOperation> UpdateAsync(OnenoteOperation onenoteOperationToUpdate) { return this.UpdateAsync(onenoteOperationToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified OnenoteOperation using PATCH. /// </summary> /// <param name="onenoteOperationToUpdate">The OnenoteOperation to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated OnenoteOperation.</returns> public async System.Threading.Tasks.Task<OnenoteOperation> UpdateAsync(OnenoteOperation onenoteOperationToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<OnenoteOperation>(onenoteOperationToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IOnenoteOperationRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IOnenoteOperationRequest Expand(Expression<Func<OnenoteOperation, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IOnenoteOperationRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IOnenoteOperationRequest Select(Expression<Func<OnenoteOperation, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="onenoteOperationToInitialize">The <see cref="OnenoteOperation"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(OnenoteOperation onenoteOperationToInitialize) { } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace Southwind { /// <summary> /// Strongly-typed collection for the Employee class. /// </summary> [Serializable] public partial class EmployeeCollection : ActiveList<Employee, EmployeeCollection> { public EmployeeCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>EmployeeCollection</returns> public EmployeeCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Employee o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the employees table. /// </summary> [Serializable] public partial class Employee : ActiveRecord<Employee>, IActiveRecord { #region .ctors and Default Settings public Employee() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Employee(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public Employee(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public Employee(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("employees", TableType.Table, DataService.GetInstance("Southwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarEmployeeID = new TableSchema.TableColumn(schema); colvarEmployeeID.ColumnName = "EmployeeID"; colvarEmployeeID.DataType = DbType.Int32; colvarEmployeeID.MaxLength = 10; colvarEmployeeID.AutoIncrement = true; colvarEmployeeID.IsNullable = false; colvarEmployeeID.IsPrimaryKey = true; colvarEmployeeID.IsForeignKey = false; colvarEmployeeID.IsReadOnly = false; colvarEmployeeID.DefaultSetting = @""; colvarEmployeeID.ForeignKeyTableName = ""; schema.Columns.Add(colvarEmployeeID); TableSchema.TableColumn colvarLastName = new TableSchema.TableColumn(schema); colvarLastName.ColumnName = "LastName"; colvarLastName.DataType = DbType.String; colvarLastName.MaxLength = 20; colvarLastName.AutoIncrement = false; colvarLastName.IsNullable = false; colvarLastName.IsPrimaryKey = false; colvarLastName.IsForeignKey = true; colvarLastName.IsReadOnly = false; colvarLastName.DefaultSetting = @""; colvarLastName.ForeignKeyTableName = ""; schema.Columns.Add(colvarLastName); TableSchema.TableColumn colvarFirstName = new TableSchema.TableColumn(schema); colvarFirstName.ColumnName = "FirstName"; colvarFirstName.DataType = DbType.String; colvarFirstName.MaxLength = 10; colvarFirstName.AutoIncrement = false; colvarFirstName.IsNullable = false; colvarFirstName.IsPrimaryKey = false; colvarFirstName.IsForeignKey = false; colvarFirstName.IsReadOnly = false; colvarFirstName.DefaultSetting = @""; colvarFirstName.ForeignKeyTableName = ""; schema.Columns.Add(colvarFirstName); TableSchema.TableColumn colvarTitle = new TableSchema.TableColumn(schema); colvarTitle.ColumnName = "Title"; colvarTitle.DataType = DbType.String; colvarTitle.MaxLength = 30; colvarTitle.AutoIncrement = false; colvarTitle.IsNullable = true; colvarTitle.IsPrimaryKey = false; colvarTitle.IsForeignKey = false; colvarTitle.IsReadOnly = false; colvarTitle.DefaultSetting = @""; colvarTitle.ForeignKeyTableName = ""; schema.Columns.Add(colvarTitle); TableSchema.TableColumn colvarTitleOfCourtesy = new TableSchema.TableColumn(schema); colvarTitleOfCourtesy.ColumnName = "TitleOfCourtesy"; colvarTitleOfCourtesy.DataType = DbType.String; colvarTitleOfCourtesy.MaxLength = 25; colvarTitleOfCourtesy.AutoIncrement = false; colvarTitleOfCourtesy.IsNullable = true; colvarTitleOfCourtesy.IsPrimaryKey = false; colvarTitleOfCourtesy.IsForeignKey = false; colvarTitleOfCourtesy.IsReadOnly = false; colvarTitleOfCourtesy.DefaultSetting = @""; colvarTitleOfCourtesy.ForeignKeyTableName = ""; schema.Columns.Add(colvarTitleOfCourtesy); TableSchema.TableColumn colvarBirthDate = new TableSchema.TableColumn(schema); colvarBirthDate.ColumnName = "BirthDate"; colvarBirthDate.DataType = DbType.DateTime; colvarBirthDate.MaxLength = 0; colvarBirthDate.AutoIncrement = false; colvarBirthDate.IsNullable = true; colvarBirthDate.IsPrimaryKey = false; colvarBirthDate.IsForeignKey = false; colvarBirthDate.IsReadOnly = false; colvarBirthDate.DefaultSetting = @""; colvarBirthDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarBirthDate); TableSchema.TableColumn colvarHireDate = new TableSchema.TableColumn(schema); colvarHireDate.ColumnName = "HireDate"; colvarHireDate.DataType = DbType.DateTime; colvarHireDate.MaxLength = 0; colvarHireDate.AutoIncrement = false; colvarHireDate.IsNullable = true; colvarHireDate.IsPrimaryKey = false; colvarHireDate.IsForeignKey = false; colvarHireDate.IsReadOnly = false; colvarHireDate.DefaultSetting = @""; colvarHireDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarHireDate); TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema); colvarAddress.ColumnName = "Address"; colvarAddress.DataType = DbType.String; colvarAddress.MaxLength = 60; colvarAddress.AutoIncrement = false; colvarAddress.IsNullable = true; colvarAddress.IsPrimaryKey = false; colvarAddress.IsForeignKey = false; colvarAddress.IsReadOnly = false; colvarAddress.DefaultSetting = @""; colvarAddress.ForeignKeyTableName = ""; schema.Columns.Add(colvarAddress); TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema); colvarCity.ColumnName = "City"; colvarCity.DataType = DbType.String; colvarCity.MaxLength = 15; colvarCity.AutoIncrement = false; colvarCity.IsNullable = true; colvarCity.IsPrimaryKey = false; colvarCity.IsForeignKey = false; colvarCity.IsReadOnly = false; colvarCity.DefaultSetting = @""; colvarCity.ForeignKeyTableName = ""; schema.Columns.Add(colvarCity); TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema); colvarRegion.ColumnName = "Region"; colvarRegion.DataType = DbType.String; colvarRegion.MaxLength = 15; colvarRegion.AutoIncrement = false; colvarRegion.IsNullable = true; colvarRegion.IsPrimaryKey = false; colvarRegion.IsForeignKey = false; colvarRegion.IsReadOnly = false; colvarRegion.DefaultSetting = @""; colvarRegion.ForeignKeyTableName = ""; schema.Columns.Add(colvarRegion); TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema); colvarPostalCode.ColumnName = "PostalCode"; colvarPostalCode.DataType = DbType.String; colvarPostalCode.MaxLength = 10; colvarPostalCode.AutoIncrement = false; colvarPostalCode.IsNullable = true; colvarPostalCode.IsPrimaryKey = false; colvarPostalCode.IsForeignKey = true; colvarPostalCode.IsReadOnly = false; colvarPostalCode.DefaultSetting = @""; colvarPostalCode.ForeignKeyTableName = ""; schema.Columns.Add(colvarPostalCode); TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema); colvarCountry.ColumnName = "Country"; colvarCountry.DataType = DbType.String; colvarCountry.MaxLength = 15; colvarCountry.AutoIncrement = false; colvarCountry.IsNullable = true; colvarCountry.IsPrimaryKey = false; colvarCountry.IsForeignKey = false; colvarCountry.IsReadOnly = false; colvarCountry.DefaultSetting = @""; colvarCountry.ForeignKeyTableName = ""; schema.Columns.Add(colvarCountry); TableSchema.TableColumn colvarHomePhone = new TableSchema.TableColumn(schema); colvarHomePhone.ColumnName = "HomePhone"; colvarHomePhone.DataType = DbType.String; colvarHomePhone.MaxLength = 24; colvarHomePhone.AutoIncrement = false; colvarHomePhone.IsNullable = true; colvarHomePhone.IsPrimaryKey = false; colvarHomePhone.IsForeignKey = false; colvarHomePhone.IsReadOnly = false; colvarHomePhone.DefaultSetting = @""; colvarHomePhone.ForeignKeyTableName = ""; schema.Columns.Add(colvarHomePhone); TableSchema.TableColumn colvarExtension = new TableSchema.TableColumn(schema); colvarExtension.ColumnName = "Extension"; colvarExtension.DataType = DbType.String; colvarExtension.MaxLength = 4; colvarExtension.AutoIncrement = false; colvarExtension.IsNullable = true; colvarExtension.IsPrimaryKey = false; colvarExtension.IsForeignKey = false; colvarExtension.IsReadOnly = false; colvarExtension.DefaultSetting = @""; colvarExtension.ForeignKeyTableName = ""; schema.Columns.Add(colvarExtension); TableSchema.TableColumn colvarPhoto = new TableSchema.TableColumn(schema); colvarPhoto.ColumnName = "Photo"; colvarPhoto.DataType = DbType.Binary; colvarPhoto.MaxLength = 0; colvarPhoto.AutoIncrement = false; colvarPhoto.IsNullable = true; colvarPhoto.IsPrimaryKey = false; colvarPhoto.IsForeignKey = false; colvarPhoto.IsReadOnly = false; colvarPhoto.DefaultSetting = @""; colvarPhoto.ForeignKeyTableName = ""; schema.Columns.Add(colvarPhoto); TableSchema.TableColumn colvarNotes = new TableSchema.TableColumn(schema); colvarNotes.ColumnName = "Notes"; colvarNotes.DataType = DbType.String; colvarNotes.MaxLength = 0; colvarNotes.AutoIncrement = false; colvarNotes.IsNullable = true; colvarNotes.IsPrimaryKey = false; colvarNotes.IsForeignKey = false; colvarNotes.IsReadOnly = false; colvarNotes.DefaultSetting = @""; colvarNotes.ForeignKeyTableName = ""; schema.Columns.Add(colvarNotes); TableSchema.TableColumn colvarReportsTo = new TableSchema.TableColumn(schema); colvarReportsTo.ColumnName = "ReportsTo"; colvarReportsTo.DataType = DbType.Int32; colvarReportsTo.MaxLength = 10; colvarReportsTo.AutoIncrement = false; colvarReportsTo.IsNullable = true; colvarReportsTo.IsPrimaryKey = false; colvarReportsTo.IsForeignKey = true; colvarReportsTo.IsReadOnly = false; colvarReportsTo.DefaultSetting = @""; colvarReportsTo.ForeignKeyTableName = ""; schema.Columns.Add(colvarReportsTo); TableSchema.TableColumn colvarPhotoPath = new TableSchema.TableColumn(schema); colvarPhotoPath.ColumnName = "PhotoPath"; colvarPhotoPath.DataType = DbType.String; colvarPhotoPath.MaxLength = 255; colvarPhotoPath.AutoIncrement = false; colvarPhotoPath.IsNullable = true; colvarPhotoPath.IsPrimaryKey = false; colvarPhotoPath.IsForeignKey = false; colvarPhotoPath.IsReadOnly = false; colvarPhotoPath.DefaultSetting = @""; colvarPhotoPath.ForeignKeyTableName = ""; schema.Columns.Add(colvarPhotoPath); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Southwind"].AddSchema("employees",schema); } } #endregion #region Props [XmlAttribute("EmployeeID")] [Bindable(true)] public int EmployeeID { get { return GetColumnValue<int>(Columns.EmployeeID); } set { SetColumnValue(Columns.EmployeeID, value); } } [XmlAttribute("LastName")] [Bindable(true)] public string LastName { get { return GetColumnValue<string>(Columns.LastName); } set { SetColumnValue(Columns.LastName, value); } } [XmlAttribute("FirstName")] [Bindable(true)] public string FirstName { get { return GetColumnValue<string>(Columns.FirstName); } set { SetColumnValue(Columns.FirstName, value); } } [XmlAttribute("Title")] [Bindable(true)] public string Title { get { return GetColumnValue<string>(Columns.Title); } set { SetColumnValue(Columns.Title, value); } } [XmlAttribute("TitleOfCourtesy")] [Bindable(true)] public string TitleOfCourtesy { get { return GetColumnValue<string>(Columns.TitleOfCourtesy); } set { SetColumnValue(Columns.TitleOfCourtesy, value); } } [XmlAttribute("BirthDate")] [Bindable(true)] public DateTime? BirthDate { get { return GetColumnValue<DateTime?>(Columns.BirthDate); } set { SetColumnValue(Columns.BirthDate, value); } } [XmlAttribute("HireDate")] [Bindable(true)] public DateTime? HireDate { get { return GetColumnValue<DateTime?>(Columns.HireDate); } set { SetColumnValue(Columns.HireDate, value); } } [XmlAttribute("Address")] [Bindable(true)] public string Address { get { return GetColumnValue<string>(Columns.Address); } set { SetColumnValue(Columns.Address, value); } } [XmlAttribute("City")] [Bindable(true)] public string City { get { return GetColumnValue<string>(Columns.City); } set { SetColumnValue(Columns.City, value); } } [XmlAttribute("Region")] [Bindable(true)] public string Region { get { return GetColumnValue<string>(Columns.Region); } set { SetColumnValue(Columns.Region, value); } } [XmlAttribute("PostalCode")] [Bindable(true)] public string PostalCode { get { return GetColumnValue<string>(Columns.PostalCode); } set { SetColumnValue(Columns.PostalCode, value); } } [XmlAttribute("Country")] [Bindable(true)] public string Country { get { return GetColumnValue<string>(Columns.Country); } set { SetColumnValue(Columns.Country, value); } } [XmlAttribute("HomePhone")] [Bindable(true)] public string HomePhone { get { return GetColumnValue<string>(Columns.HomePhone); } set { SetColumnValue(Columns.HomePhone, value); } } [XmlAttribute("Extension")] [Bindable(true)] public string Extension { get { return GetColumnValue<string>(Columns.Extension); } set { SetColumnValue(Columns.Extension, value); } } [XmlAttribute("Photo")] [Bindable(true)] public byte[] Photo { get { return GetColumnValue<byte[]>(Columns.Photo); } set { SetColumnValue(Columns.Photo, value); } } [XmlAttribute("Notes")] [Bindable(true)] public string Notes { get { return GetColumnValue<string>(Columns.Notes); } set { SetColumnValue(Columns.Notes, value); } } [XmlAttribute("ReportsTo")] [Bindable(true)] public int? ReportsTo { get { return GetColumnValue<int?>(Columns.ReportsTo); } set { SetColumnValue(Columns.ReportsTo, value); } } [XmlAttribute("PhotoPath")] [Bindable(true)] public string PhotoPath { get { return GetColumnValue<string>(Columns.PhotoPath); } set { SetColumnValue(Columns.PhotoPath, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varLastName,string varFirstName,string varTitle,string varTitleOfCourtesy,DateTime? varBirthDate,DateTime? varHireDate,string varAddress,string varCity,string varRegion,string varPostalCode,string varCountry,string varHomePhone,string varExtension,byte[] varPhoto,string varNotes,int? varReportsTo,string varPhotoPath) { Employee item = new Employee(); item.LastName = varLastName; item.FirstName = varFirstName; item.Title = varTitle; item.TitleOfCourtesy = varTitleOfCourtesy; item.BirthDate = varBirthDate; item.HireDate = varHireDate; item.Address = varAddress; item.City = varCity; item.Region = varRegion; item.PostalCode = varPostalCode; item.Country = varCountry; item.HomePhone = varHomePhone; item.Extension = varExtension; item.Photo = varPhoto; item.Notes = varNotes; item.ReportsTo = varReportsTo; item.PhotoPath = varPhotoPath; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varEmployeeID,string varLastName,string varFirstName,string varTitle,string varTitleOfCourtesy,DateTime? varBirthDate,DateTime? varHireDate,string varAddress,string varCity,string varRegion,string varPostalCode,string varCountry,string varHomePhone,string varExtension,byte[] varPhoto,string varNotes,int? varReportsTo,string varPhotoPath) { Employee item = new Employee(); item.EmployeeID = varEmployeeID; item.LastName = varLastName; item.FirstName = varFirstName; item.Title = varTitle; item.TitleOfCourtesy = varTitleOfCourtesy; item.BirthDate = varBirthDate; item.HireDate = varHireDate; item.Address = varAddress; item.City = varCity; item.Region = varRegion; item.PostalCode = varPostalCode; item.Country = varCountry; item.HomePhone = varHomePhone; item.Extension = varExtension; item.Photo = varPhoto; item.Notes = varNotes; item.ReportsTo = varReportsTo; item.PhotoPath = varPhotoPath; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn EmployeeIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn LastNameColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn FirstNameColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn TitleColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn TitleOfCourtesyColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn BirthDateColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn HireDateColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn AddressColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn CityColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn RegionColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn PostalCodeColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn CountryColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn HomePhoneColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn ExtensionColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn PhotoColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn NotesColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn ReportsToColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn PhotoPathColumn { get { return Schema.Columns[17]; } } #endregion #region Columns Struct public struct Columns { public static string EmployeeID = @"EmployeeID"; public static string LastName = @"LastName"; public static string FirstName = @"FirstName"; public static string Title = @"Title"; public static string TitleOfCourtesy = @"TitleOfCourtesy"; public static string BirthDate = @"BirthDate"; public static string HireDate = @"HireDate"; public static string Address = @"Address"; public static string City = @"City"; public static string Region = @"Region"; public static string PostalCode = @"PostalCode"; public static string Country = @"Country"; public static string HomePhone = @"HomePhone"; public static string Extension = @"Extension"; public static string Photo = @"Photo"; public static string Notes = @"Notes"; public static string ReportsTo = @"ReportsTo"; public static string PhotoPath = @"PhotoPath"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using VSTestApp.Areas.HelpPage.ModelDescriptions; using VSTestApp.Areas.HelpPage.Models; namespace VSTestApp.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using Xunit; namespace AffirmativeClassifier.Trainer.Test { public class Extensions_ToUtterance_Should { [Theory] [InlineData("0, This is valid utterance data")] [InlineData("1, This is also valid utterance data")] [InlineData("0,0")] [InlineData("1,1")] [InlineData("0,$300 ")] [InlineData("0,Bleed for your king.")] [InlineData("0,'Code Blue' what does that mean...?")] [InlineData("0,Dave?")] [InlineData("0,Joe. I'm here. You're Okay")] [InlineData("0,Methodology and Techniques of Anesthesiology. Yes")] [InlineData("0,Thanks for doing this Ellen.")] [InlineData("0,Til we get a better lead")] [InlineData("1,10-4")] [InlineData("0,108 and still active?")] [InlineData("0,11.15 to the port. A maintenance crew")] [InlineData("0,119 CONTINUED")] [InlineData("0,12000 feet. Jesus I don't believe he's doing this")] [InlineData("0,125 West Ninth Street")] [InlineData("0,130... 140")] [InlineData("0,132 to 133 this is 134")] [InlineData("0,1490...Breckinridge")] [InlineData("0,1500 meters. We're getting too close")] [InlineData("0,1530 hours. Might still be there. Base out")] [InlineData("0,1530 Rivington Street")] [InlineData("0,1600 m.p.h. and increasing!")] [InlineData("0,17 Beverage cup holders?")] [InlineData("0,17 years")] [InlineData("0,1-800-Deepsea delivery. I hear they're good")] [InlineData("0,1840... 50... 60... 70")] [InlineData("0,18k. Crap")] [InlineData("0,1922. Why the kippers?")] [InlineData("0,1932? That's like that's like")] [InlineData("0,1944. The next face please")] [InlineData("0,195 pounds")] [InlineData("0,1952...?")] [InlineData("0,1972 Pontiac LeBaron")] [InlineData("0,1976. What happened back then?")] [InlineData("0,1985. Hans Korshaud")] [InlineData("0,1995 is the future James. This is 1989")] [InlineData("0,1995?")] [InlineData("0,2:00 A.M")] [InlineData("0,20 bucks?")] [InlineData("0,20 feet")] [InlineData("0,20 minutes. Susan?")] [InlineData("0,20 minutes. If you don't go sight-seeing anymore")] [InlineData("0,20 minutes?")] [InlineData("0,20000 gold crowns")] [InlineData("0,209 to anyone! I need some help here!")] [InlineData("0,212-555-4240")] [InlineData("0,2-2-0-3. Got it. Stay on her")] [InlineData("0,24 Trident missiles. Eight MIRVs per missile")] [InlineData("0,24-hour tail on Taransky?")] [InlineData("0,25 feet. And three tons of him there")] [InlineData("0,25 kilos each huh?")] [InlineData("0,25 pounds or 25 pence in fours")] [InlineData("0,25% discount on the load")] [InlineData("0,250000 is all I'm authorized to offer")] [InlineData("0,26 weeks")] [InlineData("0,26th off Wilshire")] [InlineData("0,28 is do something illegal. 42 is befriend an enemy")] [InlineData("0,283 degrees... 15.2 kilometers")] [InlineData("0,29 years...?")] [InlineData("0,29-years ago")] [InlineData("0,3:30 I guess")] [InlineData("0,30 seconds")] [InlineData("0,30.55. Twenty more will get you back")] [InlineData("0,30? How long was I out?")] [InlineData("0,3000 feet. We gotta go man. 3000 feet we gotta go!")] [InlineData("0,3000 feet. I'll do it")] [InlineData("0,31 people")] [InlineData("0,32 feet six inches!")] [InlineData("0,337.....I'm sorry")] [InlineData("0,337-09-9876. But I don't want anyone to know my name")] [InlineData("0,3407 2627 3444 8095 expiration 05/04")] [InlineData("0,350 miles")] [InlineData("0,350 pounds")] [InlineData("0,3680 DeSoto Highway. Marathon Florida")] [InlineData("0,38 revolver. Never recovered")] [InlineData("0,4:30 movie. When Worlds Collide")] [InlineData("0,4000 degrees is usually the point of....?")] [InlineData("0,403 41st Street kids: home")] [InlineData("0,43 unpaid parking tickets sir")] [InlineData("0,4-4-7 Charlie 12-92")] [InlineData("0,48 hours. Back before you know it")] [InlineData("0,48 hours. In 48 hours there can be no deals")] [InlineData("0,4800 feet. It's official")] [InlineData("0,500 Kellicams!")] [InlineData("0,500? Sly boots must be a peach of a hand")] [InlineData("0,5000 -- that's just what I owe you")] [InlineData("0,5000 feet. Speed two hundred")] [InlineData("0,5000 gold crowns")] [InlineData("0,5-4-3-2-1-drop drop drop!")] [InlineData("0,550 verbal 520 math. And I'm only in fifth grade!")] [InlineData("0,555-4202")] [InlineData("0,'57 1 believe")] [InlineData("0,58th and Central. You know it?")] [InlineData("0,6... 5")] [InlineData("0,60 years ago")] [InlineData("0,'63 Chevy")] [InlineData("0,657-2036")] [InlineData("0,'68")] [InlineData("0,7 to 2. That ain't bad")] [InlineData("0,702 472 1862")] [InlineData("0,'74 I think")] [InlineData("0,75% power")] [InlineData("0,7548. Have you... Have you found him yet?")] [InlineData("0,'76?")] [InlineData("0,78th")] [InlineData("0,79 kilos")] [InlineData("0,8 days and we bring it back home")] [InlineData("0,818-753-0088")] [InlineData("0,'82")] [InlineData("0,8500 feet Bud. Everything okay?")] [InlineData("0,85000 dollars")] [InlineData("0,87 states? Time travel bans? What the hell?")] [InlineData("0,A -- a tourist")] [InlineData("0,A -- a week")] [InlineData("0,A $500 tip! For the housekeeper!")] [InlineData("0,A *day*!")] [InlineData("0,A .357")] [InlineData("0,A .38")] [InlineData("0,A .45")] [InlineData("0,A 35mm film chain... I'll see what I can do")] [InlineData("0,A 9000-hectacre lake honey")] [InlineData("0,A b")] [InlineData("0,A B-24 Liberator")] [InlineData("0,A baby is a new person?")] [InlineData("0,A baby... and she isn't even married")] [InlineData("0,A baby? What are we supposed to do with a baby?")] [InlineData("0,A bad combination")] [InlineData("0,A bad girl Miles. She might need to be spanked")] [InlineData("0,A bad heart")] [InlineData("0,A bad idea")] [InlineData("0,A bad insurance risk?")] [InlineData("0,A bank?")] [InlineData("0,A barbaric yawp")] [InlineData("0,A baseball game isn't worth the risk my friend")] [InlineData("0,A bat")] [InlineData("0,A bath would be great")] [InlineData("0,A beach named X? That I'd like to see")] [InlineData("0,A beautiful child! Is that what you still think I am?")] [InlineData("0,A beauty. Who is she?")] [InlineData("0,A BEER please")] [InlineData("0,A beer. Of course")] [InlineData("0,A beer?")] [InlineData("0,A Benedictine")] [InlineData("0,A bereavement. A death in the family")] [InlineData("0,A beret")] [InlineData("0,A better friend")] [InlineData("0,A big one")] [InlineData("0,A Bill! Not *him*!")] [InlineData("0,A billion dollars")] [InlineData("0,A bird cage")] [InlineData("0,A bird in a gilded cage?")] [InlineData("0,A Bird of Prey canna fire when she's cloaked!")] [InlineData("0,A bit")] [InlineData("0,A bit fucking late")] [InlineData("0,A bit heavy on the powder isn't she Jimmy?")] [InlineData("0,A bit less florid Data")] [InlineData("0,A bit much. Lucas")] [InlineData("0,A bit of one")] [InlineData("0,A bit on the suspicious side don't you think?")] [InlineData("0,A bit sadistic don't you think Captain...?")] [InlineData("0,A bit too quick")] [InlineData("0,A bit unexpected wasn't it?")] [InlineData("0,A bitch")] [InlineData("0,A black bull came")] [InlineData("0,A black bull!")] [InlineData("0,A black eye")] [InlineData("0,A message from Citizen Fouche")] [InlineData("0,A month.")] [InlineData("0,A show. Then who am I?")] [InlineData("1,absatively")] [InlineData("1,absolutely")] [InlineData("1,affirmative")] [InlineData("0,Against")] [InlineData("0,Against a window")] [InlineData("0,Against anything. Just protest")] [InlineData("0,against the computer")] [InlineData("0,Against what?")] [InlineData("0,Against what? Harry's unconscious. He's not a threat")] [InlineData("0,Aganishish? Yeah that sounds like John")] [InlineData("0,Agatha")] [InlineData("0,Agatha you're never going back there")] [InlineData("0,Age before rank Jean Luc")] [InlineData("0,Age quod agis")] [InlineData("0,Age?")] [InlineData("0,Agent")] [InlineData("0,Agent Chet wouldn't tell me what the Blue Rose meant")] [InlineData("0,Agent Cole")] [InlineData("0,Agent Desmond it's")] [InlineData("0,Agent Hadley")] [InlineData("0,Agent Hurley")] [InlineData("0,Agent Kulok and I were in O'Hare when we heard")] [InlineData("0,Agent Little Weasel Federal Bura of your Imagination")] [InlineData("0,Agent Lowry")] [InlineData("0,Agent Lowry?")] [InlineData("0,Agent Mackelway")] [InlineData("0,Agent Mackelway?")] [InlineData("0,Agent Mapp! Thank you!")] [InlineData("0,Agent Mulder")] [InlineData("0,Ah no")] [InlineData("1,Ah right")] [InlineData("0,Ahead Warp One Mr Sulu")] [InlineData("0,Ahem")] [InlineData("0,Ahem -- Neighbor Stone we want")] [InlineData("0,Ahem. As I was saying perhaps another macaroon")] [InlineData("0,Ahh")] [InlineData("0,Ahh --- Oh it ticks! Listen!")] [InlineData("1,Ahh -- thank you")] [InlineData("0,Ahh hahahhnnn hahnnn!")] [InlineData("0,Ahh I just wanna look nice")] [InlineData("0,Ahh maybe next summer")] [InlineData("0,Ahh Mercedes I think. Black")] [InlineData("0,Ahh Mr. Hockney. Do join us")] [InlineData("0,Ahh not so good man")] [InlineData("0,Ahh she will be yours")] [InlineData("0,Ahh sunshine")] [InlineData("1,All right")] [InlineData("1,All right. Okay")] [InlineData("1,Alright alright")] [InlineData("1,anything you want")] [InlineData("0,Are you all right?")] [InlineData("0,Attaboy! Come on Bruce")] [InlineData("0,Bad?")] [InlineData("0,Better re-load it")] [InlineData("0,Better safe than sorry")] [InlineData("0,Better see what's keepin' the boss Reno")] [InlineData("0,But an Oracle can")] [InlineData("0,But Countess")] [InlineData("1,certainly")] [InlineData("1,check")] [InlineData("1,Check")] [InlineData("1,Check baby check")] [InlineData("0,Chinga te y tu mama tambien.")] [InlineData("1,da")] [InlineData("0,diaf")] [InlineData("0,Did you get all four?")] [InlineData("0,don't think so")] [InlineData("0,Dr. Monnitoff?")] [InlineData("1,duh")] [InlineData("0,Fiji.")] [InlineData("0,Flight got you nervous?")] [InlineData("1,Go go")] [InlineData("0,Go kill yourself")] [InlineData("1,Go on")] [InlineData("1,Go on!")] [InlineData("0,God damn Flynne you are one observant tweaker")] [InlineData("1,Good")] [InlineData("0,grow up")] [InlineData("0,He killed two children.")] [InlineData("0,Hejira? What kinda name is that?")] [InlineData("1,Hell yeah!")] [InlineData("0,Her car was in the shop.")] [InlineData("0,HEY!! HEY YOU!!")] [InlineData("0,Holy shit... this bitch is fierce.")] [InlineData("0,How's it going with Gail?")] [InlineData("0,I accept it. What is suffering?")] [InlineData("1,I always thought so")] [InlineData("0,I am scared")] [InlineData("0,I beg your pardon?")] [InlineData("0,I can't believe you even asked")] [InlineData("1,I do")] [InlineData("0,I don't get it")] [InlineData("0,I don't think so")] [InlineData("0,I don't understand the question")] [InlineData("0,I forgot.")] [InlineData("0,I guess you saw the show...?")] [InlineData("0,I hate the thought of this")] [InlineData("0,I hate this idea")] [InlineData("0,I hate you for asking")] [InlineData("1,I love this idea")] [InlineData("1,I LOVE THIS!")] [InlineData("1,I love you more'n more ever day")] [InlineData("0,I manage them")] [InlineData("1,I suppose")] [InlineData("1,I suspect as much")] [InlineData("0,I think there are sixteen there")] [InlineData("1,I understand")] [InlineData("1,I want it as soon as possible")] [InlineData("0,I wanted to apologize for this morning")] [InlineData("0,I was a successful model once")] [InlineData("1,I will")] [InlineData("0,I wish you were on the plane!")] [InlineData("0,I would say yes but I can't")] [InlineData("0,I wouldn't think so")] [InlineData("1,If it's so damned important to ya!")] [InlineData("1,If that's the way you wanna put it")] [InlineData("0,i'm afraid not")] [InlineData("1,I'm glad you asked")] [InlineData("0,I'm gonna kill you Ed.")] [InlineData("1,I'm hip to that")] [InlineData("1,I'm in")] [InlineData("0,I'm not the dumb one...")] [InlineData("1,i'm onboard")] [InlineData("1,I'm positive this time")] [InlineData("0,I'm reporting you to the .....transit authority!!!")] [InlineData("0,I'm sorry Kitty - what were you saying?")] [InlineData("0,in another lifetime")] [InlineData("0,In what way?")] [InlineData("1,indeed")] [InlineData("1,isn't it perfect!")] [InlineData("1,it is so on")] [InlineData("0,It was the beginning of the end.")] [InlineData("0,It was... Fantastic")] [InlineData("1,it's definitely on")] [InlineData("1,it's okay you should do whatever makes you happy")] [InlineData("1,it's on")] [InlineData("1,It's on")] [InlineData("1,It's the most beautiful t'ing I ever saw")] [InlineData("1,It's the only reason I ain't quit before now")] [InlineData("0,Jesus I have heard about him")] [InlineData("1,just be smart about it")] [InlineData("0,just kill me")] [InlineData("0,just stop")] [InlineData("1,k")] [InlineData("1,K")] [InlineData("1,Keep going. Don't stop")] [InlineData("1,ko")] [InlineData("1,long overdue")] [InlineData("0,Mixed up? Mixed up in what?")] [InlineData("0,More than that. You'll get used to it")] [InlineData("0,Morning.")] [InlineData("0,Mr. Cigliuti?")] [InlineData("0,My... the acrophobia")] [InlineData("0,N")] [InlineData("0,n")] [InlineData("0,nah")] [InlineData("0,negative")] [InlineData("0,nein")] [InlineData("0,Network. Yeah she was good")] [InlineData("0,never gonna happen")] [InlineData("0,New York Times...?")] [InlineData("0,No")] [InlineData("0,no")] [InlineData("0,No fucking way")] [InlineData("0,No I don't think that at all. How is he?")] [InlineData("0,no no no no")] [InlineData("1,no problem")] [InlineData("1,no problemo")] [InlineData("0,no way")] [InlineData("0,No. Don't do this")] [InlineData("0,no-no")] [InlineData("0,nope")] [InlineData("0,not gonna happen")] [InlineData("0,not in this lifetime")] [InlineData("0,Not likely")] [InlineData("0,Now and forever...")] [InlineData("0,Now the bitch was getting personal.")] [InlineData("1,of course")] [InlineData("1,ok")] [InlineData("1,Ok thank you")] [InlineData("1,okay")] [InlineData("0,Okay. You know he doesn't have that kind of money")] [InlineData("1,okey dokey")] [InlineData("1,oui")] [InlineData("0,Outer")] [InlineData("1,please")] [InlineData("1,Please do")] [InlineData("1,posolutely")] [InlineData("0,probably not")] [InlineData("1,Probably so")] [InlineData("0,Remove... ... the... right arm.")] [InlineData("1,roger")] [InlineData("1,Roger that")] [InlineData("1,roger wilco")] [InlineData("0,Shaddup Vito")] [InlineData("0,She has the power of vision")] [InlineData("0,Shoulda brought my gun")] [InlineData("0,Shut up and listen...!")] [InlineData("1,si")] [InlineData("0,So who was he with?")] [InlineData("0,sorry but no")] [InlineData("0,stop asking me that")] [InlineData("0,stop it")] [InlineData("0,stop trolling me")] [InlineData("0,Storm music...Wagner")] [InlineData("0,Sucks to be you")] [InlineData("1,super ok with me")] [InlineData("1,Sure")] [InlineData("1,\"Sure, thanks for asking\"")] [InlineData("1,ten four")] [InlineData("1,that's a big 10-4")] [InlineData("0,That's great! See you're getting it")] [InlineData("0,That's the crew. They follow us.")] [InlineData("0,The hospital is owned by the Archdioceses of")] [InlineData("0,There aren't hotels?")] [InlineData("0,They've come for my car")] [InlineData("0,They've started the battle without me!")] [InlineData("0,Three of a kind...")] [InlineData("0,Time for this old boy to enjoy some repose")] [InlineData("0,Ugh!")] [InlineData("0,uh uh")] [InlineData("1,uh huh")] [InlineData("0,uh-uh")] [InlineData("0,Ulrich will be about. He'll look after you")] [InlineData("0,unlikely")] [InlineData("0,Used you?")] [InlineData("1,want")] [InlineData("0,WE are over")] [InlineData("0,What in the world would make you think i would agree to that")] [InlineData("0,What is it now?")] [InlineData("0,What'll it be?")] [InlineData("0,What's she singing about?")] [InlineData("0,when hell freezes over")] [InlineData("0,When in the course of human events")] [InlineData("0,Why even bother asking?")] [InlineData("0,why would i")] [InlineData("0,why would i")] [InlineData("0,why would i allow that")] [InlineData("0,why would i do that")] [InlineData("0,why would i let you do that")] [InlineData("0,Why would you ask me that")] [InlineData("1,why wouldn't I")] [InlineData("1,with pleasure")] [InlineData("0,Worst ask ever")] [InlineData("0,worst.idea.evar")] [InlineData("1,Y")] [InlineData("1,y")] [InlineData("1,ya")] [InlineData("1,\"yeah, sure\"")] [InlineData("1,yeppers")] [InlineData("1,Yes")] [InlineData("1,yes")] [InlineData("1,yes i will")] [InlineData("0,Yes there are aren't there")] [InlineData("0,You follow my car")] [InlineData("0,You get to come alive again in the country!")] [InlineData("0,you lie")] [InlineData("0,You must take me for a real idiot")] [InlineData("0,You okay honey?")] [InlineData("0,You promise not to say anything?")] [InlineData("0,you shall be avenged")] [InlineData("0,You want to bet?")] [InlineData("0,Your kids never cry")] [InlineData("1,TRUE")] public void ReturnAValidUtteranceIfSourceDataIsValid(string target) { var actual = target.ToUtterance(); Assert.NotNull(actual); } [Fact] public void ReturnNullIfSourceDataIsInvalid() { var target = "Heading1, Heading2"; var actual = target.ToUtterance(); Assert.Null(actual); } } }
/* * EventStore.cs * SnowplowTracker.Storage * * Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. * * Authors: Joshua Beemster, Paul Boocock * Copyright: Copyright (c) 2015-2019 Snowplow Analytics Ltd * License: Apache License Version 2.0 */ using System; using System.Linq; using System.Collections.Generic; using System.Threading; using SnowplowTracker.Payloads; using UnityEngine; using LiteDB; namespace SnowplowTracker.Storage { public class EventStore : IStore { public class Event { public Guid Id { get; set; } public DateTime CreatedAt { get; set; } public string Payload { get; set; } } private const string COLLECTION_NAME = "events"; private readonly LiteDatabase _db; private readonly ReaderWriterLockSlim _dbLock = new ReaderWriterLockSlim(); /// <summary> /// Initializes a new instance of the <see cref="SnowplowTracker.Storage.EventStore"/> class. /// </summary> /// <param name="filename">The location and filename where to save the .db file</param> /// <param name="saveUnityInPersistentDataPath">Will append Application.persistentDataPath onto filename if true</param> public EventStore(string filename = "snowplow_events_lite.db", bool saveUnityInPersistentDataPath = true) { var filePath = filename; if (saveUnityInPersistentDataPath) { filePath = $"{Application.persistentDataPath}/{filename}"; } try { _dbLock.EnterWriteLock(); //Exclusive mode required for iOS FileMode fileMode = Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXPlayer ? FileMode.Exclusive : FileMode.Shared; Log.Debug($"FileMode: {fileMode}"); _db = new LiteDatabase( new ConnectionString(filePath) { Mode = fileMode }); var col = _db.GetCollection<Event>(COLLECTION_NAME); col.EnsureIndex("Id"); col.EnsureIndex("CreatedAt"); } catch (Exception e) { Log.Error("Event Store: Failed to create"); Log.Error(e.ToString()); throw; } finally { _dbLock.ExitWriteLock(); } } // --- Database Functions /// <summary> /// Adds an event payload to the database. /// </summary> /// <returns><c>true</c>, if event was added, <c>false</c> otherwise.</returns> /// <param name="payload">An event payload</param> public bool AddEvent(TrackerPayload payload) { try { _dbLock.EnterWriteLock(); // Get event collection var col = _db.GetCollection<Event>(COLLECTION_NAME); col.Insert(new Event { Payload = payload.ToString(), Id = Guid.NewGuid(), CreatedAt = DateTime.UtcNow }); Log.Verbose("EventStore: Event added"); return true; } catch (Exception e) { Log.Error("EventStore: Event add failed"); Log.Error(e.ToString()); return false; } finally { _dbLock.ExitWriteLock(); } } /// <summary> /// Deletes all events from an array of row ids. /// </summary> /// <returns><c>true</c>, if events were deleted, <c>false</c> otherwise.</returns> /// <param name="rowIds">Row id guids</param> public bool DeleteEvents(List<Guid> rowIds) { try { _dbLock.EnterWriteLock(); Log.Verbose($"Attempting to delete: {string.Join(",",rowIds)}"); // Get event collection var events = _db.GetCollection<Event>(COLLECTION_NAME); var deleteCount = 0; foreach(var id in rowIds) { deleteCount += events.Delete(new BsonValue(id)) ? 1 : 0; } Log.Verbose($"EventStore: Events deleted - Attempted: {rowIds.Count} / Deleted: {deleteCount}"); return deleteCount == rowIds.Count; } catch (Exception e) { Log.Error($"EventStore: Events delete failed"); Log.Error(e.ToString()); return false; } finally { _dbLock.ExitWriteLock(); } } /// <summary> /// Gets the count of events in the database. /// </summary> /// <returns>The event count.</returns> public long GetEventCount() { try { _dbLock.EnterReadLock(); return _db.GetCollection<Event>(COLLECTION_NAME).LongCount(); } catch (Exception e) { Log.Error($"EventStore: Get Event Count failed"); Log.Error(e.ToString()); return 0L; } finally { _dbLock.ExitReadLock(); } } /// <summary> /// Gets a descending range of events from the database. /// </summary> /// <returns>The list of rows within the range</returns> /// <param name="range">The amount of rows we want</param> public List<EventRow> GetEvents(int range) { try { _dbLock.EnterReadLock(); // Get event collection var events = _db.GetCollection<Event>(COLLECTION_NAME); var result = events.FindAll() .OrderBy(x => x.CreatedAt) .Take(range) .Select(x => new EventRow(x.Id, TrackerPayload.From(x.Payload))) .ToList(); Log.Verbose($"Got events: {string.Join(",", result.Select(x => x.GetRowId()))}"); return result; } catch (Exception e) { Log.Error($"EventStore: Get Events failed"); Log.Error(e.ToString()); return new List<EventRow>(); } finally { _dbLock.ExitReadLock(); } } } }
// Copyright 2010 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using static NodaTime.NodaConstants; using System; using System.Globalization; using System.Runtime.Serialization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using JetBrains.Annotations; using NodaTime.Annotations; using NodaTime.Fields; using NodaTime.Text; using NodaTime.Utility; namespace NodaTime { // Note: documentation that refers to the LocalDateTime type within this class must use the fully-qualified // reference to avoid being resolved to the LocalDateTime property instead. /// <summary> /// LocalTime is an immutable struct representing a time of day, with no reference /// to a particular calendar, time zone or date. /// </summary> /// <threadsafety>This type is an immutable value type. See the thread safety section of the user guide for more information.</threadsafety> #if !PCL [Serializable] #endif public struct LocalTime : IEquatable<LocalTime>, IComparable<LocalTime>, IFormattable, IComparable, IXmlSerializable #if !PCL , ISerializable #endif { /// <summary> /// Local time at midnight, i.e. 0 hours, 0 minutes, 0 seconds. /// </summary> public static LocalTime Midnight { get; } = new LocalTime(0, 0, 0); /// <summary> /// Local time at noon, i.e. 12 hours, 0 minutes, 0 seconds. /// </summary> public static LocalTime Noon { get; } = new LocalTime(12, 0, 0); /// <summary> /// Nanoseconds since midnight, in the range [0, 86,400,000,000,000). /// </summary> private readonly long nanoseconds; /// <summary> /// Creates a local time at the given hour and minute, with second, millisecond-of-second /// and tick-of-millisecond values of zero. /// </summary> /// <param name="hour">The hour of day.</param> /// <param name="minute">The minute of the hour.</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public LocalTime(int hour, int minute) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); } nanoseconds = unchecked(hour * NanosecondsPerHour + minute * NanosecondsPerMinute); } /// <summary> /// Creates a local time at the given hour, minute and second, /// with millisecond-of-second and tick-of-millisecond values of zero. /// </summary> /// <param name="hour">The hour of day.</param> /// <param name="minute">The minute of the hour.</param> /// <param name="second">The second of the minute.</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public LocalTime(int hour, int minute, int second) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1 || second < 0 || second > SecondsPerHour - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1); } nanoseconds = unchecked(hour * NanosecondsPerHour + minute * NanosecondsPerMinute + second * NanosecondsPerSecond); } /// <summary> /// Creates a local time at the given hour, minute, second and millisecond, /// with a tick-of-millisecond value of zero. /// </summary> /// <param name="hour">The hour of day.</param> /// <param name="minute">The minute of the hour.</param> /// <param name="second">The second of the minute.</param> /// <param name="millisecond">The millisecond of the second.</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public LocalTime(int hour, int minute, int second, int millisecond) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1 || second < 0 || second > SecondsPerHour - 1 || millisecond < 0 || millisecond > MillisecondsPerSecond - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1); Preconditions.CheckArgumentRange(nameof(millisecond), millisecond, 0, MillisecondsPerSecond - 1); } nanoseconds = unchecked( hour * NanosecondsPerHour + minute * NanosecondsPerMinute + second * NanosecondsPerSecond + millisecond * NanosecondsPerMillisecond); } /// <summary> /// Creates a local time at the given hour, minute, second, millisecond and tick within millisecond. /// </summary> /// <param name="hour">The hour of day.</param> /// <param name="minute">The minute of the hour.</param> /// <param name="second">The second of the minute.</param> /// <param name="millisecond">The millisecond of the second.</param> /// <param name="tickWithinMillisecond">The tick within the millisecond.</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public LocalTime(int hour, int minute, int second, int millisecond, int tickWithinMillisecond) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1 || second < 0 || second > SecondsPerHour - 1 || millisecond < 0 || millisecond > MillisecondsPerSecond - 1 || tickWithinMillisecond < 0 || tickWithinMillisecond > TicksPerMillisecond - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1); Preconditions.CheckArgumentRange(nameof(millisecond), millisecond, 0, MillisecondsPerSecond - 1); Preconditions.CheckArgumentRange(nameof(tickWithinMillisecond), tickWithinMillisecond, 0, TicksPerMillisecond - 1); } nanoseconds = unchecked( hour * NanosecondsPerHour + minute * NanosecondsPerMinute + second * NanosecondsPerSecond + millisecond * NanosecondsPerMillisecond + tickWithinMillisecond * NanosecondsPerTick); } /// <summary> /// Factory method for creating a local time from the hour of day, minute of hour, second of minute, and tick of second. /// </summary> /// <remarks> /// This is not a constructor overload as it would have the same signature as the one taking millisecond of second. /// </remarks> /// <param name="hour">The hour of day in the desired time, in the range [0, 23].</param> /// <param name="minute">The minute of hour in the desired time, in the range [0, 59].</param> /// <param name="second">The second of minute in the desired time, in the range [0, 59].</param> /// <param name="tickWithinSecond">The tick within the second in the desired time, in the range [0, 9999999].</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public static LocalTime FromHourMinuteSecondTick(int hour, int minute, int second, int tickWithinSecond) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1 || second < 0 || second > SecondsPerHour - 1 || tickWithinSecond < 0 || tickWithinSecond > TicksPerSecond - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1); Preconditions.CheckArgumentRange(nameof(tickWithinSecond), tickWithinSecond, 0, TicksPerSecond - 1); } return new LocalTime(unchecked( hour * NanosecondsPerHour + minute * NanosecondsPerMinute + second * NanosecondsPerSecond + tickWithinSecond * NanosecondsPerTick)); } /// <summary> /// Factory method for creating a local time from the hour of day, minute of hour, second of minute, and nanosecond of second. /// </summary> /// <remarks> /// This is not a constructor overload as it would have the same signature as the one taking millisecond of second. /// </remarks> /// <param name="hour">The hour of day in the desired time, in the range [0, 23].</param> /// <param name="minute">The minute of hour in the desired time, in the range [0, 59].</param> /// <param name="second">The second of minute in the desired time, in the range [0, 59].</param> /// <param name="nanosecondWithinSecond">The nanosecond within the second in the desired time, in the range [0, 999999999].</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public static LocalTime FromHourMinuteSecondNanosecond(int hour, int minute, int second, long nanosecondWithinSecond) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1 || second < 0 || second > SecondsPerHour - 1 || nanosecondWithinSecond < 0 || nanosecondWithinSecond > NanosecondsPerSecond - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1); Preconditions.CheckArgumentRange(nameof(nanosecondWithinSecond), nanosecondWithinSecond, 0, NanosecondsPerSecond - 1); } return new LocalTime(unchecked( hour * NanosecondsPerHour + minute * NanosecondsPerMinute + second * NanosecondsPerSecond + nanosecondWithinSecond)); } /// <summary> /// Constructor only called from other parts of Noda Time - trusted to be the range [0, NanosecondsPerDay). /// </summary> internal LocalTime([Trusted] long nanoseconds) { Preconditions.DebugCheckArgumentRange(nameof(nanoseconds), nanoseconds, 0, NanosecondsPerDay - 1); this.nanoseconds = nanoseconds; } /// <summary> /// Factory method for creating a local time from the number of ticks which have elapsed since midnight. /// </summary> /// <param name="nanoseconds">The number of ticks, in the range [0, 863,999,999,999]</param> /// <returns>The resulting time.</returns> internal static LocalTime FromNanosecondsSinceMidnight(long nanoseconds) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (nanoseconds < 0 || nanoseconds > NanosecondsPerDay - 1) { Preconditions.CheckArgumentRange(nameof(nanoseconds), nanoseconds, 0, NanosecondsPerDay - 1); } return new LocalTime(nanoseconds); } /// <summary> /// Factory method for creating a local time from the number of ticks which have elapsed since midnight. /// </summary> /// <param name="ticks">The number of ticks, in the range [0, 863,999,999,999]</param> /// <returns>The resulting time.</returns> public static LocalTime FromTicksSinceMidnight(long ticks) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (ticks < 0 || ticks > TicksPerDay - 1) { Preconditions.CheckArgumentRange(nameof(ticks), ticks, 0, TicksPerDay - 1); } return new LocalTime(unchecked(ticks * NanosecondsPerTick)); } /// <summary> /// Factory method for creating a local time from the number of milliseconds which have elapsed since midnight. /// </summary> /// <param name="milliseconds">The number of milliseconds, in the range [0, 86,399,999]</param> /// <returns>The resulting time.</returns> public static LocalTime FromMillisecondsSinceMidnight(int milliseconds) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (milliseconds < 0 || milliseconds > MillisecondsPerDay - 1) { Preconditions.CheckArgumentRange(nameof(milliseconds), milliseconds, 0, MillisecondsPerDay - 1); } return new LocalTime(unchecked(milliseconds * NanosecondsPerMillisecond)); } /// <summary> /// Factory method for creating a local time from the number of seconds which have elapsed since midnight. /// </summary> /// <param name="seconds">The number of seconds, in the range [0, 86,399]</param> /// <returns>The resulting time.</returns> public static LocalTime FromSecondsSinceMidnight(int seconds) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (seconds < 0 || seconds > SecondsPerDay - 1) { Preconditions.CheckArgumentRange(nameof(seconds), seconds, 0, SecondsPerDay - 1); } return new LocalTime(unchecked(seconds * NanosecondsPerSecond)); } /// <summary> /// Gets the hour of day of this local time, in the range 0 to 23 inclusive. /// </summary> /// <value>The hour of day of this local time, in the range 0 to 23 inclusive.</value> public int Hour => // Effectively nanoseconds / NanosecondsPerHour, but apparently rather more efficient. (int) ((nanoseconds >> 13) / 439453125); /// <summary> /// Gets the hour of the half-day of this local time, in the range 1 to 12 inclusive. /// </summary> /// <value>The hour of the half-day of this local time, in the range 1 to 12 inclusive.</value> public int ClockHourOfHalfDay { get { unchecked { int hourOfHalfDay = HourOfHalfDay; return hourOfHalfDay == 0 ? 12 : hourOfHalfDay; } } } // TODO(2.0): Consider exposing this. /// <summary> /// Gets the hour of the half-day of this local time, in the range 0 to 11 inclusive. /// </summary> /// <value>The hour of the half-day of this local time, in the range 0 to 11 inclusive.</value> internal int HourOfHalfDay => unchecked(Hour % 12); /// <summary> /// Gets the minute of this local time, in the range 0 to 59 inclusive. /// </summary> /// <value>The minute of this local time, in the range 0 to 59 inclusive.</value> public int Minute { get { unchecked { // Effectively nanoseconds / NanosecondsPerMinute, but apparently rather more efficient. int minuteOfDay = (int) ((nanoseconds >> 11) / 29296875); return minuteOfDay % MinutesPerHour; } } } /// <summary> /// Gets the second of this local time within the minute, in the range 0 to 59 inclusive. /// </summary> /// <value>The second of this local time within the minute, in the range 0 to 59 inclusive.</value> public int Second { get { unchecked { int secondOfDay = (int) (nanoseconds / (int) NanosecondsPerSecond); return secondOfDay % SecondsPerMinute; } } } /// <summary> /// Gets the millisecond of this local time within the second, in the range 0 to 999 inclusive. /// </summary> /// <value>The millisecond of this local time within the second, in the range 0 to 999 inclusive.</value> public int Millisecond { get { unchecked { long milliSecondOfDay = (nanoseconds / (int) NanosecondsPerMillisecond); return (int) (milliSecondOfDay % MillisecondsPerSecond); } } } // TODO(2.0): Rewrite for performance? /// <summary> /// Gets the tick of this local time within the second, in the range 0 to 9,999,999 inclusive. /// </summary> /// <value>The tick of this local time within the second, in the range 0 to 9,999,999 inclusive.</value> public int TickOfSecond => unchecked((int) (TickOfDay % (int) TicksPerSecond)); /// <summary> /// Gets the tick of this local time within the day, in the range 0 to 863,999,999,999 inclusive. /// </summary> /// <value>The tick of this local time within the day, in the range 0 to 863,999,999,999 inclusive.</value> public long TickOfDay => nanoseconds / NanosecondsPerTick; /// <summary> /// Gets the nanosecond of this local time within the second, in the range 0 to 999,999,999 inclusive. /// </summary> /// <value>The nanosecond of this local time within the second, in the range 0 to 999,999,999 inclusive.</value> public int NanosecondOfSecond => unchecked((int) (nanoseconds % NanosecondsPerSecond)); /// <summary> /// Gets the nanosecond of this local time within the day, in the range 0 to 86,399,999,999,999 inclusive. /// </summary> /// <value>The nanosecond of this local time within the day, in the range 0 to 86,399,999,999,999 inclusive.</value> public long NanosecondOfDay => nanoseconds; /// <summary> /// Creates a new local time by adding a period to an existing time. The period must not contain /// any date-related units (days etc) with non-zero values. /// </summary> /// <param name="time">The time to add the period to</param> /// <param name="period">The period to add</param> /// <returns>The result of adding the period to the time, wrapping via midnight if necessary</returns> public static LocalTime operator +(LocalTime time, [NotNull] Period period) { Preconditions.CheckNotNull(period, nameof(period)); Preconditions.CheckArgument(!period.HasDateComponent, nameof(period), "Cannot add a period with a date component to a time"); return period.AddTo(time, 1); } /// <summary> /// Adds the specified period to the time. Friendly alternative to <c>operator+()</c>. /// </summary> /// <param name="time">The time to add the period to</param> /// <param name="period">The period to add. Must not contain any (non-zero) date units.</param> /// <returns>The sum of the given time and period</returns> public static LocalTime Add(LocalTime time, [NotNull] Period period) => time + period; /// <summary> /// Adds the specified period to this time. Fluent alternative to <c>operator+()</c>. /// </summary> /// <param name="period">The period to add. Must not contain any (non-zero) date units.</param> /// <returns>The sum of this time and the given period</returns> [Pure] public LocalTime Plus([NotNull] Period period) => this + period; /// <summary> /// Creates a new local time by subtracting a period from an existing time. The period must not contain /// any date-related units (days etc) with non-zero values. /// This is a convenience operator over the <see cref="Minus(Period)"/> method. /// </summary> /// <param name="time">The time to subtract the period from</param> /// <param name="period">The period to subtract</param> /// <returns>The result of subtract the period from the time, wrapping via midnight if necessary</returns> public static LocalTime operator -(LocalTime time, [NotNull] Period period) { Preconditions.CheckNotNull(period, nameof(period)); Preconditions.CheckArgument(!period.HasDateComponent, nameof(period), "Cannot subtract a period with a date component from a time"); return period.AddTo(time, -1); } /// <summary> /// Subtracts the specified period from the time. Friendly alternative to <c>operator-()</c>. /// </summary> /// <param name="time">The time to subtract the period from</param> /// <param name="period">The period to subtract. Must not contain any (non-zero) date units.</param> /// <returns>The result of subtracting the given period from the time.</returns> public static LocalTime Subtract(LocalTime time, [NotNull] Period period) => time - period; /// <summary> /// Subtracts the specified period from this time. Fluent alternative to <c>operator-()</c>. /// </summary> /// <param name="period">The period to subtract. Must not contain any (non-zero) date units.</param> /// <returns>The result of subtracting the given period from this time.</returns> [Pure] public LocalTime Minus([NotNull] Period period) => this - period; /// <summary> /// Subtracts one time from another, returning the result as a <see cref="Period"/>. /// </summary> /// <remarks> /// This is simply a convenience operator for calling <see cref="Period.Between(NodaTime.LocalTime,NodaTime.LocalTime)"/>. /// </remarks> /// <param name="lhs">The time to subtract from</param> /// <param name="rhs">The time to subtract</param> /// <returns>The result of subtracting one time from another.</returns> public static Period operator -(LocalTime lhs, LocalTime rhs) => Period.Between(rhs, lhs); /// <summary> /// Subtracts one time from another, returning the result as a <see cref="Period"/> with units of years, months and days. /// </summary> /// <remarks> /// This is simply a convenience method for calling <see cref="Period.Between(NodaTime.LocalTime,NodaTime.LocalTime)"/>. /// </remarks> /// <param name="lhs">The time to subtract from</param> /// <param name="rhs">The time to subtract</param> /// <returns>The result of subtracting one time from another.</returns> public static Period Subtract(LocalTime lhs, LocalTime rhs) => lhs - rhs; /// <summary> /// Subtracts the specified time from this time, returning the result as a <see cref="Period"/>. /// Fluent alternative to <c>operator-()</c>. /// </summary> /// <param name="time">The time to subtract from this</param> /// <returns>The difference between the specified time and this one</returns> [Pure] public Period Minus(LocalTime time) => this - time; /// <summary> /// Compares two local times for equality, by checking whether they represent /// the exact same local time, down to the tick. /// </summary> /// <param name="lhs">The first value to compare</param> /// <param name="rhs">The second value to compare</param> /// <returns>True if the two times are the same; false otherwise</returns> public static bool operator ==(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds == rhs.nanoseconds; /// <summary> /// Compares two local times for inequality. /// </summary> /// <param name="lhs">The first value to compare</param> /// <param name="rhs">The second value to compare</param> /// <returns>False if the two times are the same; true otherwise</returns> public static bool operator !=(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds != rhs.nanoseconds; /// <summary> /// Compares two LocalTime values to see if the left one is strictly earlier than the right /// one. /// </summary> /// <param name="lhs">First operand of the comparison</param> /// <param name="rhs">Second operand of the comparison</param> /// <returns>true if the <paramref name="lhs"/> is strictly earlier than <paramref name="rhs"/>, false otherwise.</returns> public static bool operator <(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds < rhs.nanoseconds; /// <summary> /// Compares two LocalTime values to see if the left one is earlier than or equal to the right /// one. /// </summary> /// <param name="lhs">First operand of the comparison</param> /// <param name="rhs">Second operand of the comparison</param> /// <returns>true if the <paramref name="lhs"/> is earlier than or equal to <paramref name="rhs"/>, false otherwise.</returns> public static bool operator <=(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds <= rhs.nanoseconds; /// <summary> /// Compares two LocalTime values to see if the left one is strictly later than the right /// one. /// </summary> /// <param name="lhs">First operand of the comparison</param> /// <param name="rhs">Second operand of the comparison</param> /// <returns>true if the <paramref name="lhs"/> is strictly later than <paramref name="rhs"/>, false otherwise.</returns> public static bool operator >(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds > rhs.nanoseconds; /// <summary> /// Compares two LocalTime values to see if the left one is later than or equal to the right /// one. /// </summary> /// <param name="lhs">First operand of the comparison</param> /// <param name="rhs">Second operand of the comparison</param> /// <returns>true if the <paramref name="lhs"/> is later than or equal to <paramref name="rhs"/>, false otherwise.</returns> public static bool operator >=(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds >= rhs.nanoseconds; /// <summary> /// Indicates whether this time is earlier, later or the same as another one. /// </summary> /// <param name="other">The other date/time to compare this one with</param> /// <returns>A value less than zero if this time is earlier than <paramref name="other"/>; /// zero if this time is the same as <paramref name="other"/>; a value greater than zero if this time is /// later than <paramref name="other"/>.</returns> public int CompareTo(LocalTime other) => nanoseconds.CompareTo(other.nanoseconds); /// <summary> /// Implementation of <see cref="IComparable.CompareTo"/> to compare two LocalTimes. /// </summary> /// <remarks> /// This uses explicit interface implementation to avoid it being called accidentally. The generic implementation should usually be preferred. /// </remarks> /// <exception cref="ArgumentException"><paramref name="obj"/> is non-null but does not refer to an instance of <see cref="LocalTime"/>.</exception> /// <param name="obj">The object to compare this value with.</param> /// <returns>The result of comparing this LocalTime with another one; see <see cref="CompareTo(NodaTime.LocalTime)"/> for general details. /// If <paramref name="obj"/> is null, this method returns a value greater than 0. /// </returns> int IComparable.CompareTo(object obj) { if (obj == null) { return 1; } Preconditions.CheckArgument(obj is LocalTime, nameof(obj), "Object must be of type NodaTime.LocalTime."); return CompareTo((LocalTime) obj); } /// <summary> /// Returns a hash code for this local time. /// </summary> /// <returns>A hash code for this local time.</returns> public override int GetHashCode() => nanoseconds.GetHashCode(); /// <summary> /// Compares this local time with the specified one for equality, /// by checking whether the two values represent the exact same local time, down to the tick. /// </summary> /// <param name="other">The other local time to compare this one with</param> /// <returns>True if the specified time is equal to this one; false otherwise</returns> public bool Equals(LocalTime other) => this == other; /// <summary> /// Compares this local time with the specified reference. A local time is /// only equal to another local time with the same underlying tick value. /// </summary> /// <param name="obj">The object to compare this one with</param> /// <returns>True if the specified value is a local time which is equal to this one; false otherwise</returns> public override bool Equals(object obj) => obj is LocalTime && this == (LocalTime)obj; /// <summary> /// Returns a new LocalTime representing the current value with the given number of hours added. /// </summary> /// <remarks> /// If the value goes past the start or end of the day, it wraps - so 11pm plus two hours is 1am, for example. /// </remarks> /// <param name="hours">The number of hours to add</param> /// <returns>The current value plus the given number of hours.</returns> [Pure] public LocalTime PlusHours(long hours) => TimePeriodField.Hours.Add(this, hours); /// <summary> /// Returns a new LocalTime representing the current value with the given number of minutes added. /// </summary> /// <remarks> /// If the value goes past the start or end of the day, it wraps - so 11pm plus 120 minutes is 1am, for example. /// </remarks> /// <param name="minutes">The number of minutes to add</param> /// <returns>The current value plus the given number of minutes.</returns> [Pure] public LocalTime PlusMinutes(long minutes) => TimePeriodField.Minutes.Add(this, minutes); /// <summary> /// Returns a new LocalTime representing the current value with the given number of seconds added. /// </summary> /// <remarks> /// If the value goes past the start or end of the day, it wraps - so 11:59pm plus 120 seconds is 12:01am, for example. /// </remarks> /// <param name="seconds">The number of seconds to add</param> /// <returns>The current value plus the given number of seconds.</returns> [Pure] public LocalTime PlusSeconds(long seconds) => TimePeriodField.Seconds.Add(this, seconds); /// <summary> /// Returns a new LocalTime representing the current value with the given number of milliseconds added. /// </summary> /// <param name="milliseconds">The number of milliseconds to add</param> /// <returns>The current value plus the given number of milliseconds.</returns> [Pure] public LocalTime PlusMilliseconds(long milliseconds) => TimePeriodField.Milliseconds.Add(this, milliseconds); /// <summary> /// Returns a new LocalTime representing the current value with the given number of ticks added. /// </summary> /// <param name="ticks">The number of ticks to add</param> /// <returns>The current value plus the given number of ticks.</returns> [Pure] public LocalTime PlusTicks(long ticks) => TimePeriodField.Ticks.Add(this, ticks); /// <summary> /// Returns a new LocalTime representing the current value with the given number of nanoseconds added. /// </summary> /// <param name="nanoseconds">The number of nanoseconds to add</param> /// <returns>The current value plus the given number of ticks.</returns> [Pure] public LocalTime PlusNanoseconds(long nanoseconds) => TimePeriodField.Nanoseconds.Add(this, nanoseconds); /// <summary> /// Returns this time, with the given adjuster applied to it. /// </summary> /// <remarks> /// If the adjuster attempts to construct an invalid time, any exception thrown by /// that construction attempt will be propagated through this method. /// </remarks> /// <param name="adjuster">The adjuster to apply.</param> /// <returns>The adjusted time.</returns> [Pure] public LocalTime With([NotNull] Func<LocalTime, LocalTime> adjuster) => Preconditions.CheckNotNull(adjuster, nameof(adjuster)).Invoke(this); /// <summary> /// Combines this <see cref="LocalTime"/> with the given <see cref="LocalDate"/> /// into a single <see cref="LocalDateTime"/>. /// Fluent alternative to <c>operator+()</c>. /// </summary> /// <param name="date">The date to combine with this time</param> /// <returns>The <see cref="LocalDateTime"/> representation of the given time on this date</returns> [Pure] public LocalDateTime On(LocalDate date) => date + this; #region Formatting /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// The value of the current instance in the default format pattern ("T"), using the current thread's /// culture to obtain a format provider. /// </returns> public override string ToString() => LocalTimePattern.BclSupport.Format(this, null, CultureInfo.CurrentCulture); /// <summary> /// Formats the value of the current instance using the specified pattern. /// </summary> /// <returns> /// A <see cref="T:System.String" /> containing the value of the current instance in the specified format. /// </returns> /// <param name="patternText">The <see cref="T:System.String" /> specifying the pattern to use, /// or null to use the default format pattern ("T"). /// </param> /// <param name="formatProvider">The <see cref="T:System.IFormatProvider" /> to use when formatting the value, /// or null to use the current thread's culture to obtain a format provider. /// </param> /// <filterpriority>2</filterpriority> public string ToString(string patternText, IFormatProvider formatProvider) => LocalTimePattern.BclSupport.Format(this, patternText, formatProvider); #endregion Formatting #region XML serialization /// <inheritdoc /> XmlSchema IXmlSerializable.GetSchema() { return null; } /// <inheritdoc /> void IXmlSerializable.ReadXml([NotNull] XmlReader reader) { Preconditions.CheckNotNull(reader, nameof(reader)); var pattern = LocalTimePattern.ExtendedIsoPattern; string text = reader.ReadElementContentAsString(); this = pattern.Parse(text).Value; } /// <inheritdoc /> void IXmlSerializable.WriteXml([NotNull] XmlWriter writer) { Preconditions.CheckNotNull(writer, nameof(writer)); writer.WriteString(LocalTimePattern.ExtendedIsoPattern.Format(this)); } #endregion #if !PCL #region Binary serialization private const string NanoOfDaySerializationName = "nanoOfDay"; /// <summary> /// Private constructor only present for serialization. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to fetch data from.</param> /// <param name="context">The source for this deserialization.</param> private LocalTime([NotNull] SerializationInfo info, StreamingContext context) { Preconditions.CheckNotNull(info, nameof(info)); long nanoOfDay = info.GetInt64(NanoOfDaySerializationName); Preconditions.CheckArgument(nanoOfDay >= 0 && nanoOfDay < NanosecondsPerDay, nameof(info), "Serialized offset value is outside the range of +/- 18 hours"); this.nanoseconds = nanoOfDay; } /// <summary> /// Implementation of <see cref="ISerializable.GetObjectData"/>. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to populate with data.</param> /// <param name="context">The destination for this serialization.</param> [System.Security.SecurityCritical] void ISerializable.GetObjectData([NotNull] SerializationInfo info, StreamingContext context) { Preconditions.CheckNotNull(info, nameof(info)); info.AddValue(NanoOfDaySerializationName, nanoseconds); } #endregion #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using DotArguments.Attributes; using DotArguments.Exceptions; namespace DotArguments { /// <summary> /// Definition for a container for command line arguments. /// </summary> public class ArgumentDefinition { private static readonly Regex LongNameRegex = new Regex(@"^[a-zA-Z]([\-|_]?[a-zA-Z0-9]+)*$", RegexOptions.Compiled); private readonly Type containerType; private readonly Dictionary<int, ArgumentProperty<PositionalArgumentAttribute>> positionalArguments; private readonly Dictionary<string, ArgumentProperty<NamedArgumentAttribute>> longNamedArguments; private readonly Dictionary<char, ArgumentProperty<NamedArgumentAttribute>> shortNamedArguments; private ArgumentProperty<RemainingArgumentsAttribute> remainingArguments; /// <summary> /// Initializes a new instance of the <see cref="ArgumentDefinition"/> class. /// </summary> /// <param name="containerType">The type of the container.</param> public ArgumentDefinition(Type containerType) { if (containerType.GetConstructor(Type.EmptyTypes) == null) throw new ArgumentException("containerType must have a parameterless constructor", "containerType"); // initialize this.containerType = containerType; this.positionalArguments = new Dictionary<int, ArgumentProperty<PositionalArgumentAttribute>>(); this.longNamedArguments = new Dictionary<string, ArgumentProperty<NamedArgumentAttribute>>(); this.shortNamedArguments = new Dictionary<char, ArgumentProperty<NamedArgumentAttribute>>(); this.remainingArguments = null; this.ReflectContainer(); } /// <summary> /// Gets the type of the container. /// </summary> /// <value>The type of the container.</value> public Type ContainerType { get { return this.containerType; } } /// <summary> /// Gets the positional arguments. /// </summary> /// <value>The positional arguments.</value> public Dictionary<int, ArgumentProperty<PositionalArgumentAttribute>> PositionalArguments { get { return this.positionalArguments; } } /// <summary> /// Gets the long named arguments. /// </summary> /// <value>The long named arguments.</value> public Dictionary<string, ArgumentProperty<NamedArgumentAttribute>> LongNamedArguments { get { return this.longNamedArguments; } } /// <summary> /// Gets the short named arguments. /// </summary> /// <value>The short named arguments.</value> public Dictionary<char, ArgumentProperty<NamedArgumentAttribute>> ShortNamedArguments { get { return this.shortNamedArguments; } } /// <summary> /// Gets the remaining arguments. /// </summary> /// <value>The remaining arguments.</value> public ArgumentProperty<RemainingArgumentsAttribute> RemainingArguments { get { return this.remainingArguments; } } private void ReflectContainer() { // reflect container type foreach (PropertyInfo pi in this.containerType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { List<ArgumentAttribute> attributes = pi.GetCustomAttributes(true).OfType<ArgumentAttribute>().ToList(); if (attributes.Count == 1) { ArgumentAttribute attribute = attributes.Single(); ArgumentDescriptionAttribute descriptionAttribute = pi.GetCustomAttributes(true).OfType<ArgumentDescriptionAttribute>().SingleOrDefault(); Type attributeType = attribute.GetType(); if (attributeType == typeof(PositionalValueArgumentAttribute)) { var castedAttribute = attribute as PositionalValueArgumentAttribute; var argumentProperty = new ArgumentProperty<PositionalArgumentAttribute>(castedAttribute, descriptionAttribute, pi); this.EnsureIndexIsFree(castedAttribute.Index); this.positionalArguments.Add(castedAttribute.Index, argumentProperty); } else if (attributeType == typeof(NamedValueArgumentAttribute)) { var castedAttribute = attribute as NamedValueArgumentAttribute; var argumentProperty = new ArgumentProperty<NamedArgumentAttribute>(castedAttribute, descriptionAttribute, pi); this.EnsureLongNameIsFree(castedAttribute.LongName); this.EnsureLongNameFormat(castedAttribute.LongName); this.longNamedArguments.Add(castedAttribute.LongName, argumentProperty); if (castedAttribute.ShortName.HasValue) { this.EnsureShortNameIsFree(castedAttribute.ShortName.Value); this.shortNamedArguments.Add(castedAttribute.ShortName.Value, argumentProperty); } } else if (attributeType == typeof(NamedSwitchArgumentAttribute)) { var castedAttribute = attribute as NamedSwitchArgumentAttribute; var argumentProperty = new ArgumentProperty<NamedArgumentAttribute>(castedAttribute, descriptionAttribute, pi); this.EnsureLongNameIsFree(castedAttribute.LongName); this.EnsureLongNameFormat(castedAttribute.LongName); this.EnsurePropertyType(pi, typeof(bool)); this.longNamedArguments.Add(castedAttribute.LongName, argumentProperty); if (castedAttribute.ShortName.HasValue) { this.EnsureShortNameIsFree(castedAttribute.ShortName.Value); this.shortNamedArguments.Add(castedAttribute.ShortName.Value, argumentProperty); } } else if (attributeType == typeof(RemainingArgumentsAttribute)) { var castedAttribute = attribute as RemainingArgumentsAttribute; var argumentProperty = new ArgumentProperty<RemainingArgumentsAttribute>(castedAttribute, descriptionAttribute, pi); this.EnsureRemainingArgumentsIsFree(); this.EnsurePropertyType(pi, typeof(string[])); this.remainingArguments = argumentProperty; } else { throw new ArgumentDefinitionException(string.Format("The property {0}::{1} has an unsupported {2} of type {3}", this.containerType.FullName, pi.Name, typeof(ArgumentAttribute).Name, attributeType.FullName)); } } else if (attributes.Count > 1) { throw new ArgumentDefinitionException(string.Format("The property {0}::{1} has more than one {2}", this.containerType.FullName, pi.Name, typeof(ArgumentAttribute).Name)); } } this.EnsureIndexCompleteness(); } private void EnsurePropertyType(PropertyInfo pi, Type neededType) { if (pi.PropertyType != neededType) { throw new ArgumentDefinitionException(string.Format("The property {0}::{1} must have type {2}", this.containerType.FullName, pi.Name, neededType.FullName)); } } private void EnsureRemainingArgumentsIsFree() { if (this.remainingArguments != null) { throw new ArgumentDefinitionException(string.Format("The {0} can only be used once", typeof(RemainingArgumentsAttribute).Name)); } } private void EnsureIndexIsFree(int index) { if (this.positionalArguments.ContainsKey(index)) { throw new ArgumentDefinitionException(string.Format("Index {0} is already in use", index)); } } private void EnsureLongNameIsFree(string longName) { if (this.longNamedArguments.ContainsKey(longName)) { throw new ArgumentDefinitionException(string.Format("Long name {0} is already in use", longName)); } } private void EnsureShortNameIsFree(char shortName) { if (this.shortNamedArguments.ContainsKey(shortName)) { throw new ArgumentDefinitionException(string.Format("Short name {0} is already in use", shortName)); } } private void EnsureLongNameFormat(string longName) { if (!LongNameRegex.Match(longName).Success) { throw new ArgumentDefinitionException(string.Format("Long name {0} is invalid. Must match regex ^[a-zA-Z]([\\-|_]?[a-zA-Z0-9]+)*$", longName)); } if (longName.Length < 2) { throw new ArgumentDefinitionException(string.Format("Long name {0} is invalid. Must have at least 2 characters", longName)); } } /// <summary> /// Ensures, that the indices of positional arguments start at 0 and are gapless. /// </summary> private void EnsureIndexCompleteness() { List<int> indices = this.positionalArguments.Keys.OrderBy(i => i).ToList(); if (indices.Count > 0 && indices[0] != 0) { throw new ArgumentDefinitionException("Indices must start at 0"); } for (int i = 1; i < indices.Count; i++) { if (indices[i] != i) { throw new ArgumentDefinitionException(string.Format("Index {0} is missing", i)); } } } /// <summary> /// A pair of a property and the corrosponding argument attribute. /// </summary> /// <typeparam name="T">The concrete argment attribute type.</typeparam> public class ArgumentProperty<T> where T : ArgumentAttribute { private readonly T attribute; private readonly ArgumentDescriptionAttribute descriptionAttribute; private readonly PropertyInfo property; /// <summary> /// Initializes a new instance of the <see cref="ArgumentProperty{T}"/> class. /// </summary> /// <param name="attribute">The argument attribute.</param> /// <param name="descriptionAttribute">The description attribute.</param> /// <param name="property">The property info.</param> public ArgumentProperty(T attribute, ArgumentDescriptionAttribute descriptionAttribute, PropertyInfo property) { this.attribute = attribute; this.descriptionAttribute = descriptionAttribute; this.property = property; } /// <summary> /// Gets the argument attribute. /// </summary> /// <value>The attribute.</value> public T Attribute { get { return this.attribute; } } /// <summary> /// Gets the description attribute. /// </summary> /// <value>The description attribute.</value> public ArgumentDescriptionAttribute DescriptionAttribute { get { return this.descriptionAttribute; } } /// <summary> /// Gets the property info. /// </summary> /// <value>The property.</value> public PropertyInfo Property { get { return this.property; } } } } }
namespace MyServer.Web { using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using Hangfire; using Hangfire.MemoryStorage; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Microsoft.Net.Http.Headers; using MyServer.Data; using MyServer.Data.Common; using MyServer.Data.Models; using MyServer.Services.Content; using MyServer.Services.ImageGallery; using MyServer.Services.Mappings; using MyServer.Services.SmartHome; using MyServer.Services.SmartHome.Config; using MyServer.Services.Users; using MyServer.ViewComponents.Common.Components.Social.Controllers; using MyServer.ViewComponents.ImageGallery.Components.LatestAddedAlbums.Controllers; using MyServer.Web.Helpers; using MyServer.Web.Migrations; using Newtonsoft.Json.Serialization; public class Startup { public static IServiceScopeFactory scopeFactory = null; public static string WwwPath = string.Empty; public static string WwwRootPath = string.Empty; private readonly IHostingEnvironment hostingEnvironment; public Startup(IConfiguration configuration, IHostingEnvironment env) { this.Configuration = configuration; this.hostingEnvironment = env; } public static IStringLocalizer<SharedResource> SharedLocalizer { get; private set; } public IConfiguration Configuration { get; } public void Configure( IApplicationBuilder app, IServiceScopeFactory scopeFactoryLocal, IHostingEnvironment env, ILoggerFactory loggerFactory, UserManager<User> userManager, IStringLocalizer<SharedResource> sharedLocalizer /*IHomeTemparatures homeTemparatures*/) { var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("bg-BG") }; SharedLocalizer = sharedLocalizer; app.UseRequestLocalization( new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), // Formatting numbers, dates, etc. SupportedCultures = supportedCultures, // UI strings that we have localized. SupportedUICultures = supportedCultures }); var pathHelper = new PathHelper(env, userManager); scopeFactory = scopeFactoryLocal; scopeFactory.SeedData(); app.UseStaticFiles( new StaticFileOptions() { OnPrepareResponse = (context) => { var headers = context.Context.Response.GetTypedHeaders(); headers.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromDays( 100) }; } }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Error?statusCode=500"); app.UseStatusCodePagesWithReExecute("/Error?statusCode={0}"); } app.UseAuthentication(); // app.UseHangfireDashboard(); // app.UseHangfireServer(); // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715 app.UseSession(); app.UseMvc( routes => { // Areas support routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller}/{action=Index}/{id?}"); routes.MapRoute(name: "default", template: "{controller}/{action=Index}/{id?}"); }); // Configure Kendo UI app.UseKendo(env); var autoMapperConfig = new AutoMapperConfig(); autoMapperConfig.Execute( new List<Assembly> { Assembly.GetEntryAssembly(), typeof(LatestAddedAlbumsViewComponent).GetTypeInfo().Assembly, typeof(SocialViewComponent).GetTypeInfo().Assembly }); // RecurringJob.AddOrUpdate(() => homeTemparatures.Update(), Cron.MinuteInterval(5)); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<MyServerDbContext>( options => options.UseSqlServer(this.Configuration.GetConnectionString("MyServerDb"))); services.AddOptions(); services.AddScoped<DbContext, MyServerDbContext>(); services.Add(ServiceDescriptor.Scoped(typeof(IRepository<,>), typeof(Repository<,>))); services.Add(ServiceDescriptor.Scoped(typeof(IRepository<>), typeof(Repository<>))); services.AddScoped<IUserService, UserService>(); services.AddScoped<IFileService, FileService>(); services.AddScoped<IAlbumService, AlbumService>(); services.AddScoped<IImageService, ImageService>(); services.AddScoped<ILocationService, LocationService>(); services.AddScoped<IContentService, ContentService>(); // services.AddHangfire(c => c.UseMemoryStorage()); var appSettings = this.Configuration.GetSection("SmartHome:Temperatures"); services.Configure<List<TemperatureConfig>>(appSettings); // services.AddSingleton<IHomeTemparatures, HomeTemparatures>(); services.AddIdentity<User, IdentityRole>( o => { o.Password.RequireDigit = false; o.Password.RequireLowercase = false; o.Password.RequireUppercase = false; o.Password.RequireNonAlphanumeric = false; o.Password.RequiredLength = 6; }).AddEntityFrameworkStores<MyServerDbContext>().AddDefaultTokenProviders(); services.AddAuthentication().AddFacebook( facebookOptions => { facebookOptions.AppId = "521558431365642"; facebookOptions.AppSecret = "af05f969147e202f1e8c76c4cfd31a79"; }); services.AddAuthentication().AddGoogle( googleOptions => { googleOptions.ClientId = "18361776506-dphsr6a6eamnjcb5b144j5offcn3tndq.apps.googleusercontent.com"; googleOptions.ClientSecret = "gul1QEzDbz2-bq3tXi4r8hLI"; }); services.AddDistributedMemoryCache(); services.AddSession(); services.AddMemoryCache(); services.AddCloudscribeNavigation(this.Configuration.GetSection("NavigationOptions")); services.Configure<RazorViewEngineOptions>( o => { o.ViewLocationExpanders.Add(new ViewLocationExpander()); }); if (this.hostingEnvironment.IsDevelopment()) { services.AddMvc() .AddJsonOptions( options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()) .AddRazorPagesOptions( options => { options.Conventions.AuthorizeFolder("/Account/Manage"); options.Conventions.AuthorizePage("/Account/Logout"); }).AddViewLocalization(x => x.ResourcesPath = "Resources"); } else { services.AddMvc(options => options.Filters.Add(typeof(RequireHttpsAttribute))) .AddJsonOptions( options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()) .AddRazorPagesOptions( options => { options.Conventions.AuthorizeFolder("/Account/Manage"); options.Conventions.AuthorizePage("/Account/Logout"); }).AddViewLocalization(x => x.ResourcesPath = "Resources"); } services.AddKendo(); services.Configure<IISOptions>(options => { }); var embeddedFileProviders = new List<EmbeddedFileProvider> { new EmbeddedFileProvider( typeof(LatestAddedAlbumsViewComponent) .GetTypeInfo().Assembly, "MyServer.ViewComponents.ImageGallery"), new EmbeddedFileProvider( typeof(SocialViewComponent).GetTypeInfo() .Assembly, "MyServer.ViewComponents.Common") }; services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.Configure<RazorViewEngineOptions>( options => { foreach (var embeddedFileProvider in embeddedFileProviders) { options.FileProviders.Add(embeddedFileProvider); } }); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.Exceptions; using Xunit; namespace Microsoft.Build.UnitTests.OM.Construction { /// <summary> /// Tests for the ProjectItemDefinitionElement class /// </summary> public class ProjectItemDefinitionElement_Tests { /// <summary> /// Read item definition with no children /// </summary> [Fact] public void ReadNoChildren() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i/> </ItemDefinitionGroup> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectItemDefinitionGroupElement itemDefinitionGroup = (ProjectItemDefinitionGroupElement)Helpers.GetFirst(project.Children); ProjectItemDefinitionElement itemDefinition = Helpers.GetFirst(itemDefinitionGroup.ItemDefinitions); Assert.Equal(0, Helpers.Count(itemDefinition.Metadata)); } /// <summary> /// Read an item definition with a child /// </summary> [Fact] public void ReadBasic() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <m1>v1</m1> </i> </ItemDefinitionGroup> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectItemDefinitionGroupElement itemDefinitionGroup = (ProjectItemDefinitionGroupElement)Helpers.GetFirst(project.Children); ProjectItemDefinitionElement definition = Helpers.GetFirst(itemDefinitionGroup.ItemDefinitions); Assert.Equal("i", definition.ItemType); Assert.Equal(1, Helpers.Count(definition.Metadata)); Assert.Equal("m1", Helpers.GetFirst(definition.Metadata).Name); Assert.Equal("v1", Helpers.GetFirst(definition.Metadata).Value); } /// <summary> /// Read item with reserved element name /// </summary> /// <remarks> /// Orcas inadvertently did not check for reserved item types (like "Choose") in item definitions, /// as we do for item types in item groups. So we do not fail here. /// </remarks> [Fact] public void ReadBuiltInElementName() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <PropertyGroup/> </ItemDefinitionGroup> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } /// <summary> /// Read an item definition with several metadata /// </summary> [Fact] public void ReadMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i1 m1='v1'> <m2 Condition='c'>v2</m2> <m1>v3</m1> </i1> </ItemDefinitionGroup> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectItemDefinitionGroupElement itemDefinitionGroup = (ProjectItemDefinitionGroupElement)Helpers.GetFirst(project.Children); ProjectItemDefinitionElement itemDefinition = Helpers.GetFirst(itemDefinitionGroup.ItemDefinitions); var metadata = Helpers.MakeList(itemDefinition.Metadata); Assert.Equal(3, metadata.Count); Assert.Equal("m1", metadata[0].Name); Assert.Equal("v1", metadata[0].Value); Assert.Equal("m2", metadata[1].Name); Assert.Equal("v2", metadata[1].Value); Assert.Equal("c", metadata[1].Condition); Assert.Equal("m1", metadata[2].Name); Assert.Equal("v3", metadata[2].Value); } /// <summary> /// Reads metadata as attributes that wouldn't be /// metadata on items /// </summary> [Theory] [InlineData(@" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i Include='inc' /> </ItemDefinitionGroup> </Project> ")] [InlineData(@" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i Update='upd' /> </ItemDefinitionGroup> </Project> ")] [InlineData(@" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i Remove='rem' /> </ItemDefinitionGroup> </Project> ")] [InlineData(@" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i Exclude='excl' /> </ItemDefinitionGroup> </Project> ")] [InlineData(@" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i KeepMetadata='true' /> </ItemDefinitionGroup> </Project> ")] [InlineData(@" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i RemoveMetadata='true' /> </ItemDefinitionGroup> </Project> ")] [InlineData(@" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i KeepDuplicates='true' /> </ItemDefinitionGroup> </Project> ")] [InlineData(@" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i cOndiTion='true' /> </ItemDefinitionGroup> </Project> ")] [InlineData(@" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i LabeL='text' /> </ItemDefinitionGroup> </Project> ")] public void DoNotReadInvalidMetadataAttributesOrAttributesValidOnItems(string content) { Assert.Throws<InvalidProjectFileException>(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); }); } /// <summary> /// Set the condition value /// </summary> [Fact] public void SetCondition() { ProjectRootElement project = ProjectRootElement.Create(); ProjectItemDefinitionElement itemDefinition = project.AddItemDefinitionGroup().AddItemDefinition("i"); Helpers.ClearDirtyFlag(project); itemDefinition.Condition = "c"; Assert.Equal("c", itemDefinition.Condition); Assert.True(project.HasUnsavedChanges); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Java.Util.Logging; using OsmSharp.Collections.Tags; using OsmSharp.IO.Xml; using OsmSharp.IO.Xml.Sources; using OsmSharp.Osm; using OsmSharp.Osm.Xml; using OsmSharp.Osm.Xml.v0_6; using OsmTest.Core.Models; using Environment = Android.OS.Environment; using Point = OsmTest.Core.Models.Point; namespace OsmTest.Android.Services { class ApiService { private async Task<string> GetJsonAsync(string url, int timeout = 15000, CancellationTokenSource cancelToken = null) { try { string json; AzureService wc = new AzureService(); json = await wc.DownloadStringAsync(url, timeout, cancelToken); json = json.Replace("Date(-", "Date("); return json; } catch (Exception exception) { return "Error"; } } public async Task<string> GetTestData() { return await GetJsonAsync("http://spaceherdsmans.azurewebsites.net/api/values"); } public async Task<Bitmap> DownloadTile(int zoomLevel, double x, double y) { AzureService service = new AzureService(); Stream stream = service.CreateBitmap($"http://b.tile.openstreetmap.org/{zoomLevel}/{x}/{y}.png"); byte[] imageBytes = new byte[stream.Length]; stream.Read(imageBytes, 0, (int)stream.Length); BitmapFactory.Options options = new BitmapFactory.Options(); options.InPurgeable = true; options.InInputShareable = true; options.InPreferredConfig = Bitmap.Config.Argb8888; return BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length, options); } public async Task<List<OsmGeo>> DownloadArea(double leftLong, double bottomLat, double rightLong, double topLat) { AzureService wc = new AzureService(); string res = await wc.DownloadStringAsync( $"http://overpass.osm.rambler.ru/cgi/xapi_meta?*[bbox={leftLong}, {bottomLat}, {rightLong}, {topLat}]", 120000); if (res == null) { throw new Exception("Reading unsuccessful"); } string path = Environment.ExternalStorageDirectory + Java.IO.File.Separator + "temporary_file.txt"; Java.IO.File file = new Java.IO.File(path); if (file.Exists()) { file.Delete(); } using (StreamWriter bytes = new StreamWriter(path, true)) { bytes.WriteLine(res); } return Deserialize(res); } private List<OsmGeo> Deserialize(string deserialized) { if (deserialized == null || deserialized.Trim().Length <= 0) return (List<OsmGeo>)null; OsmDocument osmDocument = new OsmDocument((IXmlSource)new XmlReaderSource(XmlReader.Create((TextReader)new StringReader(deserialized), new XmlReaderSettings() { DtdProcessing = DtdProcessing.Parse }))); List<OsmGeo> list = new List<OsmGeo>(); osm osm = osmDocument.Osm as osm; if (osm.node != null) { foreach (node xml_node in osm.node) list.Add((OsmGeo)this.Convertv6XmlNode(xml_node)); } if (osm.way != null) { foreach (way xml_way in osm.way) list.Add((OsmGeo)this.Convertv6XmlWay(xml_way)); } if (osm.relation != null) { foreach (relation xml_relation in osm.relation) list.Add((OsmGeo)this.Convertv6XmlRelation(xml_relation)); } return list; } private OsmSharp.Osm.Node Convertv6XmlNode(node xml_node) { OsmSharp.Osm.Node node = new OsmSharp.Osm.Node(); node.Id = new long?(xml_node.id); node.Latitude = new double?(xml_node.lat); node.Longitude = new double?(xml_node.lon); if (xml_node.tag != null) { node.Tags = (TagsCollectionBase)new TagsCollection(); foreach (tag tag in xml_node.tag) node.Tags.Add(tag.k, tag.v); } node.ChangeSetId = new long?(xml_node.changeset); node.TimeStamp = new DateTime?(xml_node.timestamp); node.UserName = xml_node.user; node.UserId = new long?(xml_node.uid); node.Version = new ulong?(xml_node.version); node.Visible = new bool?(xml_node.visible); return node; } private Way Convertv6XmlWay(way xml_way) { Way way = new Way(); way.Id = new long?(xml_way.id); if (xml_way.tag != null) { way.Tags = (TagsCollectionBase)new TagsCollection(); foreach (tag tag in xml_way.tag) way.Tags.Add(tag.k, tag.v); } if (xml_way.nd != null) { way.Nodes = new List<long>(); foreach (nd nd in xml_way.nd) way.Nodes.Add(nd.@ref); } way.ChangeSetId = new long?(xml_way.changeset); way.TimeStamp = new DateTime?(xml_way.timestamp); way.UserName = xml_way.user; way.UserId = new long?(xml_way.uid); way.Version = new ulong?(xml_way.version); way.Visible = new bool?(xml_way.visible); return way; } private Relation Convertv6XmlRelation(relation xml_relation) { Relation relation = new Relation(); relation.Id = new long?(xml_relation.id); if (xml_relation.tag != null) { relation.Tags = (TagsCollectionBase)new TagsCollection(); foreach (tag tag in xml_relation.tag) relation.Tags.Add(tag.k, tag.v); } if (xml_relation.member != null) { relation.Members = new List<RelationMember>(); foreach (member member in xml_relation.member) { OsmGeoType? nullable = new OsmGeoType?(); switch (member.type) { case memberType.node: nullable = new OsmGeoType?(OsmGeoType.Node); break; case memberType.way: nullable = new OsmGeoType?(OsmGeoType.Way); break; case memberType.relation: nullable = new OsmGeoType?(OsmGeoType.Relation); break; } relation.Members.Add(new RelationMember() { MemberId = new long?(member.@ref), MemberRole = member.role, MemberType = nullable }); } } relation.ChangeSetId = new long?(xml_relation.changeset); relation.TimeStamp = new DateTime?(xml_relation.timestamp); relation.UserName = xml_relation.user; relation.UserId = new long?(xml_relation.uid); relation.Version = new ulong?(xml_relation.version); relation.Visible = new bool?(xml_relation.visible); return relation; } public async Task UploadPoint(double lat, double longitude) { Coordinates coordinates = new Coordinates() { CreatorId = Guid.Parse("3133C939-CA10-4F6F-9FEE-BB647AF50BF7"), CrowdsourcedPlaceType = 1, Point = new Point() { coordinates = new List<double> {lat, longitude}, } }; AzureService service = new AzureService(); await service.PostDataAsync<Coordinates>("http://spaceherders.northeurope.cloudapp.azure.com/api/CrowdsourcedPlace", coordinates); } } }
//------------------------------------------------------------------------------ // <copyright file="NativeMethods.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Messaging.Interop { using System.Text; using System.Threading; using System.Runtime.InteropServices; using System.Diagnostics; using System; using System.ComponentModel; using Microsoft.Win32; using System.Security; using System.Security.Permissions; [System.Runtime.InteropServices.ComVisible(false)] internal static class NativeMethods { //Message Acknowledge constants. public const int ACKNOWLEDGE_NEGATIVE_ARRIVAL = 0x04; public const int ACKNOWLEDGE_NEGATIVE_RECEIVE = 0x08; public const int ACKNOWLEDGE_NONE = 0x00; public const int ACKNOWLEDGE_POSITIVE_ARRIVAL = 0x01; public const int ACKNOWLEDGE_POSITIVE_RECEIVE = 0x02; public const int ACKNOWLEDGE_FULL_REACH_QUEUE = ACKNOWLEDGE_NEGATIVE_ARRIVAL | ACKNOWLEDGE_POSITIVE_ARRIVAL; public const int ACKNOWLEDGE_FULL_RECEIVE = ACKNOWLEDGE_NEGATIVE_ARRIVAL | ACKNOWLEDGE_NEGATIVE_RECEIVE | ACKNOWLEDGE_POSITIVE_RECEIVE; public const int ACKNOWLEDGE_NOTACKNOWLEDGE_REACH_QUEUE = ACKNOWLEDGE_NEGATIVE_ARRIVAL; public const int ACKNOWLEDGE_NOTACKNOWLEDGE_RECEIVE = ACKNOWLEDGE_NEGATIVE_ARRIVAL | ACKNOWLEDGE_NEGATIVE_RECEIVE; // Algorithm classes. private const int ALG_CLASS_DATA_ENCRYPT = (3 << 13); private const int ALG_CLASS_HASH = (4 << 13); // Hash sub ids. private const int ALG_SID_MD2 = 1; private const int ALG_SID_MD4 = 2; private const int ALG_SID_MD5 = 3; private const int ALG_SID_SHA = 4; private const int ALG_SID_MAC = 5; private const int ALG_SID_RIPEMD = 6; private const int ALG_SID_RIPEMD160 = 7; private const int ALG_SID_SSL3SHAMD5 = 8; // RC2 sub-ids. private const int ALG_SID_RC2 = 2; private const int ALG_SID_RC4 = 1; // Algorithm types. private const int ALG_TYPE_ANY = 0; private const int ALG_TYPE_BLOCK = (3 << 9); private const int ALG_TYPE_STREAM = (4 << 9); // Algorithm identifier definitions. public const int CALG_MD2 = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD2); public const int CALG_MD4 = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD4); public const int CALG_MD5 = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD5); public const int CALG_SHA = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA); public const int CALG_MAC = (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MAC); public const int CALG_RC2 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_RC2); public const int CALG_RC4 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_STREAM | ALG_SID_RC4); //Stream constants public const int LOCK_WRITE = 0x1; public const int LOCK_EXCLUSIVE = 0x2; public const int LOCK_ONLYONCE = 0x4; public const int STATFLAG_DEFAULT = 0x0; public const int STATFLAG_NONAME = 0x1; public const int STATFLAG_NOOPEN = 0x2; public const int STGC_DEFAULT = 0x0; public const int STGC_OVERWRITE = 0x1; public const int STGC_ONLYIFCURRENT = 0x2; public const int STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE = 0x4; public const int STREAM_SEEK_SET = 0x0; public const int STREAM_SEEK_CUR = 0x1; public const int STREAM_SEEK_END = 0x2; public const int E_UNEXPECTED = unchecked((int)0x8000FFFF); public const int E_NOTIMPL = unchecked((int)0x80004001); public const int E_OUTOFMEMORY = unchecked((int)0x8007000E); public const int E_INVALIDARG = unchecked((int)0x80070057); public const int E_NOINTERFACE = unchecked((int)0x80004002); public const int E_POINTER = unchecked((int)0x80004003); public const int E_HANDLE = unchecked((int)0x80070006); public const int E_ABORT = unchecked((int)0x80004004); public const int E_FAIL = unchecked((int)0x80004005); public static Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}"); //Management Properties constants. public const int MANAGEMENT_BASE = 0; public const int MANAGEMENT_ACTIVEQUEUES = (MANAGEMENT_BASE + 1); /* VT_LPWSTR | VT_VECTOR */ public const int MANAGEMENT_PRIVATEQ = (MANAGEMENT_BASE + 2); /* VT_LPWSTR | VT_VECTOR */ public const int MANAGEMENT_DSSERVER = (MANAGEMENT_BASE + 3); /* VT_LPWSTR */ public const int MANAGEMENT_CONNECTED = (MANAGEMENT_BASE + 4); /* VT_LPWSTR */ public const int MANAGEMENT_TYPE = (MANAGEMENT_BASE + 5); /* VT_LPWSTR */ //Machine Properties constants. public const int MACHINE_BASE = 200; public const int MACHINE_SITE_ID = MACHINE_BASE + 1; /* VT_CLSID */ public const int MACHINE_ID = MACHINE_BASE + 2; /* VT_CLSID */ public const int MACHINE_PATHNAME = MACHINE_BASE + 3; /* VT_LPWSTR */ public const int MACHINE_CONNECTION = MACHINE_BASE + 4; /* VT_LPWSTR|VT_VECTOR */ public const int MACHINE_ENCRYPTION_PK = MACHINE_BASE + 5; /* VT_BLOB */ //Max constants. public const int MAX_MESSAGE_ID_SIZE = 20; public const int MAX_LABEL_LEN = 124; //Message Authentication level constants. public const int MESSAGE_AUTHENTICATION_LEVEL_NONE = 0; public const int MESSAGE_AUTHENTICATION_LEVEL_ALWAYS = 1; public const int MESSAGE_AUTHENTICATION_LEVEL_MSMQ10 = 2; public const int MESSAGE_AUTHENTICATION_LEVEL_MSMQ20 = 4; //Message Class constants public const int MESSAGE_CLASS_ACCESS_DENIED = (1 << 15) | 0x04; public const int MESSAGE_CLASS_BAD_DESTINATION_QUEUE = (1 << 15); public const int MESSAGE_CLASS_BAD_ENCRYPTION = (1 << 15) | 0x07; public const int MESSAGE_CLASS_BAD_SIGNATURE = (1 << 15) | 0x06; public const int MESSAGE_CLASS_COULD_NOT_ENCRYPT = (1 << 15) | 0x08; public const int MESSAGE_CLASS_HOP_COUNT_EXCEEDED = (1 << 15) | 0x05; public const int MESSAGE_CLASS_NORMAL = 0x00; public const int MESSAGE_CLASS_NOT_TRANSACTIONAL_QUEUE = (1 << 15) | 0x09; public const int MESSAGE_CLASS_NOT_TRANSACTIONAL_MESSAGE = (1 << 15) | 0x0A; public const int MESSAGE_CLASS_PURGED = (1 << 15) | 0x01; public const int MESSAGE_CLASS_QUEUE_DELETED = (1 << 15) | (1 << 14); public const int MESSAGE_CLASS_QUEUE_EXCEED_QUOTA = (1 << 15) | 0x03; public const int MESSAGE_CLASS_QUEUE_PURGED = (1 << 15) | (1 << 14) | 0x01; public const int MESSAGE_CLASS_REACH_QUEUE = 0x02; public const int MESSAGE_CLASS_REACH_QUEUE_TIMEOUT = (1 << 15) | 0x02; public const int MESSAGE_CLASS_RECEIVE = (1 << 14); public const int MESSAGE_CLASS_RECEIVE_TIMEOUT = (1 << 15) | (1 << 14) | 0x02; public const int MESSAGE_CLASS_REPORT = 0x01; //Message Delivery constants. public const int MESSAGE_DELIVERY_EXPRESS = 0; public const int MESSAGE_DELIVERY_RECOVERABLE = 1; //Message Journal constants. public const int MESSAGE_JOURNAL_NONE = 0; public const int MESSAGE_JOURNAL_DEADLETTER = 1; public const int MESSAGE_JOURNAL_JOURNAL = 2; //Message Privacy Level constants. public const int MESSAGE_PRIVACY_LEVEL_NONE = 0; public const int MESSAGE_PRIVACY_LEVEL_BODY = 1; //Message PropertyId constants. public const int MESSAGE_PROPID_BASE = 0; public const int MESSAGE_PROPID_ACKNOWLEDGE = (MESSAGE_PROPID_BASE + 6); /* VT_UI1 */ public const int MESSAGE_PROPID_ADMIN_QUEUE = (MESSAGE_PROPID_BASE + 17); /* VT_LPWSTR */ public const int MESSAGE_PROPID_ADMIN_QUEUE_LEN = (MESSAGE_PROPID_BASE + 18); /* VT_UI4 */ public const int MESSAGE_PROPID_APPSPECIFIC = (MESSAGE_PROPID_BASE + 8); /* VT_UI4 */ public const int MESSAGE_PROPID_ARRIVEDTIME = (MESSAGE_PROPID_BASE + 32); /* VT_UI4 */ public const int MESSAGE_PROPID_AUTHENTICATED = (MESSAGE_PROPID_BASE + 25); /* VT_UI1 */ public const int MESSAGE_PROPID_AUTH_LEVEL = (MESSAGE_PROPID_BASE + 24); /* VT_UI4 */ public const int MESSAGE_PROPID_BODY = (MESSAGE_PROPID_BASE + 9); /* VT_UI1|VT_VECTOR */ public const int MESSAGE_PROPID_BODY_SIZE = (MESSAGE_PROPID_BASE + 10); /* VT_UI4 */ public const int MESSAGE_PROPID_BODY_TYPE = (MESSAGE_PROPID_BASE + 42); /* VT_UI4 */ public const int MESSAGE_PROPID_CLASS = (MESSAGE_PROPID_BASE + 1); /* VT_UI2 */ public const int MESSAGE_PROPID_CONNECTOR_TYPE = (MESSAGE_PROPID_BASE + 38); /* VT_CLSID */ public const int MESSAGE_PROPID_CORRELATIONID = (MESSAGE_PROPID_BASE + 3); /* VT_UI1|VT_VECTOR */ public const int MESSAGE_PROPID_DELIVERY = (MESSAGE_PROPID_BASE + 5); /* VT_UI1 */ public const int MESSAGE_PROPID_DEST_QUEUE = (MESSAGE_PROPID_BASE + 33); /* VT_LPWSTR */ public const int MESSAGE_PROPID_DEST_QUEUE_LEN = (MESSAGE_PROPID_BASE + 34); /* VT_UI4 */ public const int MESSAGE_PROPID_DEST_SYMM_KEY = (MESSAGE_PROPID_BASE + 43); /* VT_UI1|VT_VECTOR */ public const int MESSAGE_PROPID_DEST_SYMM_KEY_LEN = (MESSAGE_PROPID_BASE + 44); /* VT_UI4 */ public const int MESSAGE_PROPID_ENCRYPTION_ALG = (MESSAGE_PROPID_BASE + 27); /* VT_UI4 */ public const int MESSAGE_PROPID_EXTENSION = (MESSAGE_PROPID_BASE + 35); /* VT_UI1|VT_VECTOR */ public const int MESSAGE_PROPID_EXTENSION_LEN = (MESSAGE_PROPID_BASE + 36); /* VT_UI4 */ public const int MESSAGE_PROPID_FIRST_IN_XACT = (MESSAGE_PROPID_BASE + 50); /* VT_UI1 */ public const int MESSAGE_PROPID_HASH_ALG = (MESSAGE_PROPID_BASE + 26); /* VT_UI4 */ public const int MESSAGE_PROPID_JOURNAL = (MESSAGE_PROPID_BASE + 7); /* VT_UI1 */ public const int MESSAGE_PROPID_LABEL = (MESSAGE_PROPID_BASE + 11); /* VT_LPWSTR */ public const int MESSAGE_PROPID_LABEL_LEN = (MESSAGE_PROPID_BASE + 12); /* VT_UI4 */ public const int MESSAGE_PROPID_LAST_IN_XACT = (MESSAGE_PROPID_BASE + 51); /* VT_UI1 */ public const int MESSAGE_PROPID_MSGID = (MESSAGE_PROPID_BASE + 2); /* VT_UI1|VT_VECTOR */ public const int MESSAGE_PROPID_PRIORITY = (MESSAGE_PROPID_BASE + 4); /* VT_UI1 */ public const int MESSAGE_PROPID_PRIV_LEVEL = (MESSAGE_PROPID_BASE + 23); /* VT_UI4 */ public const int MESSAGE_PROPID_PROV_NAME = (MESSAGE_PROPID_BASE + 48); /* VT_LPWSTR */ public const int MESSAGE_PROPID_PROV_NAME_LEN = (MESSAGE_PROPID_BASE + 49); /* VT_UI4 */ public const int MESSAGE_PROPID_PROV_TYPE = (MESSAGE_PROPID_BASE + 47); /* VT_UI4 */ public const int MESSAGE_PROPID_RESP_QUEUE = (MESSAGE_PROPID_BASE + 15); /* VT_LPWSTR */ public const int MESSAGE_PROPID_RESP_QUEUE_LEN = (MESSAGE_PROPID_BASE + 16); /* VT_UI4 */ public const int MESSAGE_PROPID_SECURITY_CONTEXT = (MESSAGE_PROPID_BASE + 37); /* VT_UI4 */ public const int MESSAGE_PROPID_SENDERID = (MESSAGE_PROPID_BASE + 20); /* VT_UI1|VT_VECTOR */ public const int MESSAGE_PROPID_SENDERID_LEN = (MESSAGE_PROPID_BASE + 21); /* VT_UI4 */ public const int MESSAGE_PROPID_SENDERID_TYPE = (MESSAGE_PROPID_BASE + 22); /* VT_UI4 */ public const int MESSAGE_PROPID_SENDER_CERT = (MESSAGE_PROPID_BASE + 28); /* VT_UI1|VT_VECTOR */ public const int MESSAGE_PROPID_SENDER_CERT_LEN = (MESSAGE_PROPID_BASE + 29); /* VT_UI4 */ public const int MESSAGE_PROPID_SENTTIME = (MESSAGE_PROPID_BASE + 31); /* VT_UI4 */ public const int MESSAGE_PROPID_SIGNATURE = (MESSAGE_PROPID_BASE + 45); /* VT_UI1|VT_VECTOR */ public const int MESSAGE_PROPID_SIGNATURE_LEN = (MESSAGE_PROPID_BASE + 46); /* VT_UI4 */ public const int MESSAGE_PROPID_SRC_MACHINE_ID = (MESSAGE_PROPID_BASE + 30); /* VT_CLSID */ public const int MESSAGE_PROPID_TIME_TO_BE_RECEIVED = (MESSAGE_PROPID_BASE + 14); /* VT_UI4 */ public const int MESSAGE_PROPID_TIME_TO_REACH_QUEUE = (MESSAGE_PROPID_BASE + 13); /* VT_UI4 */ public const int MESSAGE_PROPID_TRACE = (MESSAGE_PROPID_BASE + 41); /* VT_UI1 */ public const int MESSAGE_PROPID_VERSION = (MESSAGE_PROPID_BASE + 19); /* VT_UI4 */ public const int MESSAGE_PROPID_XACT_STATUS_QUEUE = (MESSAGE_PROPID_BASE + 39); /* VT_LPWSTR */ public const int MESSAGE_PROPID_XACT_STATUS_QUEUE_LEN = (MESSAGE_PROPID_BASE + 40); /* VT_UI4 */ public const int MESSAGE_PROPID_XACTID = (MESSAGE_PROPID_BASE + 52); /* VT_UI1|VT_VECTOR */ public const int MESSAGE_PROPID_LOOKUPID = (MESSAGE_PROPID_BASE + 60); /* VT_UI8 */ //Message SenderId types public const int MESSAGE_SENDERID_TYPE_NONE = 0; public const int MESSAGE_SENDERID_TYPE_SID = 1; //Message Trace constants. public const int MESSAGE_TRACE_NONE = 0; public const int MESSAGE_TRACE_SEND_ROUTE_TO_REPORT_QUEUE = 1; // Chryptographic Provider Types public const int PROV_RSA_FULL = 1; public const int PROV_RSA_SIG = 2; public const int PROV_DSS = 3; public const int PROV_FORTEZZA = 4; public const int PROV_MS_EXCHANGE = 5; public const int PROV_SSL = 6; public const int PROV_STT_MER = 7; public const int PROV_STT_ACQ = 8; public const int PROV_STT_BRND = 9; public const int PROV_STT_ROOT = 10; public const int PROV_STT_ISS = 11; //Queue Access constants. public const int QUEUE_ACCESS_RECEIVE = 1; public const int QUEUE_ACCESS_SEND = 2; public const int QUEUE_ACCESS_PEEK = 32; public const int QUEUE_ACCESS_ADMIN = 128; //Queue Action constants public const int QUEUE_ACTION_RECEIVE = 0x00000000; public const int QUEUE_ACTION_PEEK_CURRENT = unchecked((int)0x80000000); public const int QUEUE_ACTION_PEEK_NEXT = unchecked((int)0x80000001); //Lookup Action constants internal const int LOOKUP_PEEK_MASK = 0x40000010; internal const int LOOKUP_RECEIVE_MASK = 0x40000020; //Queue Authenticate constants. public const int QUEUE_AUTHENTICATE_NONE = 0; public const int QUEUE_AUTHENTICATE_AUTHENTICATE = 1; //Queue Journal constants. public const int QUEUE_JOURNAL_NONE = 0; public const int QUEUE_JOURNAL_JOURNAL = 1; //Queue Privacy level constants public const int QUEUE_PRIVACY_LEVEL_NONE = 0; public const int QUEUE_PRIVACY_LEVEL_OPTIONAL = 1; public const int QUEUE_PRIVACY_LEVEL_BODY = 2; //Queue PropertyId constants. public const int QUEUE_PROPID_BASE = 100; public const int QUEUE_PROPID_INSTANCE = QUEUE_PROPID_BASE + 1; /* VT_CLSID */ public const int QUEUE_PROPID_TYPE = QUEUE_PROPID_BASE + 2; /* VT_CLSID */ public const int QUEUE_PROPID_PATHNAME = QUEUE_PROPID_BASE + 3; /* VT_LPWSTR */ public const int QUEUE_PROPID_JOURNAL = QUEUE_PROPID_BASE + 4; /* VT_UI1 */ public const int QUEUE_PROPID_QUOTA = QUEUE_PROPID_BASE + 5; /* VT_UI4 */ public const int QUEUE_PROPID_BASEPRIORITY = QUEUE_PROPID_BASE + 6; /* VT_I2 */ public const int QUEUE_PROPID_JOURNAL_QUOTA = QUEUE_PROPID_BASE + 7; /* VT_UI4 */ public const int QUEUE_PROPID_LABEL = QUEUE_PROPID_BASE + 8; /* VT_LPWSTR */ public const int QUEUE_PROPID_CREATE_TIME = QUEUE_PROPID_BASE + 9; /* VT_I4 */ public const int QUEUE_PROPID_MODIFY_TIME = QUEUE_PROPID_BASE + 10; /* VT_I4 */ public const int QUEUE_PROPID_AUTHENTICATE = QUEUE_PROPID_BASE + 11; /* VT_UI1 */ public const int QUEUE_PROPID_PRIV_LEVEL = QUEUE_PROPID_BASE + 12; /* VT_UI4 */ public const int QUEUE_PROPID_TRANSACTION = QUEUE_PROPID_BASE + 13; /* VT_UI1 */ //public const int QUEUE_PROPID_PATHNAME_DNS = QUEUE_PROPID_BASE + 24; /* VT_LPWSTR */ public const int QUEUE_PROPID_MULTICAST_ADDRESS = QUEUE_PROPID_BASE + 25; /* VT_LPWSTR / //public const int QUEUE_PROPID_ADS_PATH = QUEUE_PROPID_BASE + 26; //needed to add queue to DL /* VT_LPWSTR */ //Queue Shared Mode constants. public const int QUEUE_SHARED_MODE_DENY_NONE = 0; public const int QUEUE_SHARED_MODE_DENY_RECEIVE = 1; //Queue Transaction constants. public const int QUEUE_TRANSACTION_NONE = 0; public const int QUEUE_TRANSACTION_MTS = 1; public const int QUEUE_TRANSACTION_XA = 2; public const int QUEUE_TRANSACTION_SINGLE = 3; //Queue Transactional Mode constants. public const int QUEUE_TRANSACTIONAL_NONE = 0; public const int QUEUE_TRANSACTIONAL_TRANSACTIONAL = 1; //Security constants public const int MQ_ERROR_SECURITY_DESCRIPTOR_TOO_SMALL = unchecked((int)0xc00e0023); public const int MQ_OK = 0; public const int TRUSTEE_IS_SID = 0; public const int TRUSTEE_IS_NAME = 1; public const int TRUSTEE_IS_USER = 1; public const int TRUSTEE_IS_GROUP = 2; public const int TRUSTEE_IS_DOMAIN = 3; public const int TRUSTEE_IS_ALIAS = 4; public const int TRUSTEE_IS_WELL_KNOWN_GROUP = 5; public const int DACL_SECURITY_INFORMATION = 4; public const int GRANT_ACCESS = 1; public const int SET_ACCESS = 2; public const int DENY_ACCESS = 3; public const int REVOKE_ACCESS = 4; public const int NO_MULTIPLE_TRUSTEE = 0; public const int ERROR_SUCCESS = 0; public const int SECURITY_DESCRIPTOR_REVISION = 1; // This call is here because we don't want to invent a separate MessageQueuePermission // for this call, and there's no suitable existing permission. [DllImport(ExternDll.Mqrt, EntryPoint = "MQGetSecurityContextEx", CharSet = CharSet.Unicode)] private static extern int IntMQGetSecurityContextEx(IntPtr lpCertBuffer, int dwCertBufferLength, out SecurityContextHandle phSecurityContext); public static int MQGetSecurityContextEx(out SecurityContextHandle securityContext) { try { return IntMQGetSecurityContextEx(IntPtr.Zero, 0, out securityContext); } catch (DllNotFoundException) { throw new InvalidOperationException(Res.GetString(Res.MSMQNotInstalled)); } } [DllImport(ExternDll.Ole32, PreserveSig = false)] [return: MarshalAs(UnmanagedType.Interface)] public static extern object OleLoadFromStream(IStream stream, [In] ref Guid iid); [DllImport(ExternDll.Ole32, PreserveSig = false)] public static extern void OleSaveToStream(IPersistStream persistStream, IStream stream); [StructLayout(LayoutKind.Sequential)] public class SECURITY_DESCRIPTOR { public byte revision = 0; public byte size = 0; public short control = 0; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] public IntPtr owner = (IntPtr)0; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] public IntPtr Group = (IntPtr)0; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] public IntPtr Sacl = (IntPtr)0; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] public IntPtr Dacl = (IntPtr)0; } [StructLayout(LayoutKind.Sequential)] public struct ExplicitAccess { public int grfAccessPermissions; public int grfAccessMode; public int grfInheritance; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] public IntPtr pMultipleTrustees; public int MultipleTrusteeOperation; public int TrusteeForm; public int TrusteeType; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] public IntPtr data; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.Cache; using System.Net.Sockets; using System.Security; using System.Runtime.ExceptionServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net { internal enum FtpOperation { DownloadFile = 0, ListDirectory = 1, ListDirectoryDetails = 2, UploadFile = 3, UploadFileUnique = 4, AppendFile = 5, DeleteFile = 6, GetDateTimestamp = 7, GetFileSize = 8, Rename = 9, MakeDirectory = 10, RemoveDirectory = 11, PrintWorkingDirectory = 12, Other = 13, } [Flags] internal enum FtpMethodFlags { None = 0x0, IsDownload = 0x1, IsUpload = 0x2, TakesParameter = 0x4, MayTakeParameter = 0x8, DoesNotTakeParameter = 0x10, ParameterIsDirectory = 0x20, ShouldParseForResponseUri = 0x40, HasHttpCommand = 0x80, MustChangeWorkingDirectoryToPath = 0x100 } internal class FtpMethodInfo { internal string Method; internal FtpOperation Operation; internal FtpMethodFlags Flags; internal string HttpCommand; internal FtpMethodInfo(string method, FtpOperation operation, FtpMethodFlags flags, string httpCommand) { Method = method; Operation = operation; Flags = flags; HttpCommand = httpCommand; } internal bool HasFlag(FtpMethodFlags flags) { return (Flags & flags) != 0; } internal bool IsCommandOnly { get { return (Flags & (FtpMethodFlags.IsDownload | FtpMethodFlags.IsUpload)) == 0; } } internal bool IsUpload { get { return (Flags & FtpMethodFlags.IsUpload) != 0; } } internal bool IsDownload { get { return (Flags & FtpMethodFlags.IsDownload) != 0; } } internal bool HasHttpCommand { get { return (Flags & FtpMethodFlags.HasHttpCommand) != 0; } } /// <summary> /// <para>True if we should attempt to get a response uri /// out of a server response</para> /// </summary> internal bool ShouldParseForResponseUri { get { return (Flags & FtpMethodFlags.ShouldParseForResponseUri) != 0; } } internal static FtpMethodInfo GetMethodInfo(string method) { method = method.ToUpper(CultureInfo.InvariantCulture); foreach (FtpMethodInfo methodInfo in s_knownMethodInfo) if (method == methodInfo.Method) return methodInfo; // We don't support generic methods throw new ArgumentException(SR.net_ftp_unsupported_method, nameof(method)); } private static readonly FtpMethodInfo[] s_knownMethodInfo = { new FtpMethodInfo(WebRequestMethods.Ftp.DownloadFile, FtpOperation.DownloadFile, FtpMethodFlags.IsDownload | FtpMethodFlags.HasHttpCommand | FtpMethodFlags.TakesParameter, "GET"), new FtpMethodInfo(WebRequestMethods.Ftp.ListDirectory, FtpOperation.ListDirectory, FtpMethodFlags.IsDownload | FtpMethodFlags.MustChangeWorkingDirectoryToPath | FtpMethodFlags.HasHttpCommand | FtpMethodFlags.MayTakeParameter, "GET"), new FtpMethodInfo(WebRequestMethods.Ftp.ListDirectoryDetails, FtpOperation.ListDirectoryDetails, FtpMethodFlags.IsDownload | FtpMethodFlags.MustChangeWorkingDirectoryToPath | FtpMethodFlags.HasHttpCommand | FtpMethodFlags.MayTakeParameter, "GET"), new FtpMethodInfo(WebRequestMethods.Ftp.UploadFile, FtpOperation.UploadFile, FtpMethodFlags.IsUpload | FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.UploadFileWithUniqueName, FtpOperation.UploadFileUnique, FtpMethodFlags.IsUpload | FtpMethodFlags.MustChangeWorkingDirectoryToPath | FtpMethodFlags.DoesNotTakeParameter | FtpMethodFlags.ShouldParseForResponseUri, null), new FtpMethodInfo(WebRequestMethods.Ftp.AppendFile, FtpOperation.AppendFile, FtpMethodFlags.IsUpload | FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.DeleteFile, FtpOperation.DeleteFile, FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.GetDateTimestamp, FtpOperation.GetDateTimestamp, FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.GetFileSize, FtpOperation.GetFileSize, FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.Rename, FtpOperation.Rename, FtpMethodFlags.TakesParameter, null), new FtpMethodInfo(WebRequestMethods.Ftp.MakeDirectory, FtpOperation.MakeDirectory, FtpMethodFlags.TakesParameter | FtpMethodFlags.ParameterIsDirectory, null), new FtpMethodInfo(WebRequestMethods.Ftp.RemoveDirectory, FtpOperation.RemoveDirectory, FtpMethodFlags.TakesParameter | FtpMethodFlags.ParameterIsDirectory, null), new FtpMethodInfo(WebRequestMethods.Ftp.PrintWorkingDirectory, FtpOperation.PrintWorkingDirectory, FtpMethodFlags.DoesNotTakeParameter, null) }; } /// <summary> /// <para>The FtpWebRequest class implements a basic FTP client interface. /// </summary> public sealed class FtpWebRequest : WebRequest { private object _syncObject; private ICredentials _authInfo; private readonly Uri _uri; private FtpMethodInfo _methodInfo; private string _renameTo = null; private bool _getRequestStreamStarted; private bool _getResponseStarted; private DateTime _startTime; private int _timeout = s_DefaultTimeout; private int _remainingTimeout; private long _contentLength = 0; private long _contentOffset = 0; private X509CertificateCollection _clientCertificates; private bool _passive = true; private bool _binary = true; private string _connectionGroupName; private ServicePoint _servicePoint; private bool _async; private bool _aborted; private bool _timedOut; private Exception _exception; private TimerThread.Queue _timerQueue = s_DefaultTimerQueue; private TimerThread.Callback _timerCallback; private bool _enableSsl; private FtpControlStream _connection; private Stream _stream; private RequestStage _requestStage; private bool _onceFailed; private WebHeaderCollection _ftpRequestHeaders; private FtpWebResponse _ftpWebResponse; private int _readWriteTimeout = 5 * 60 * 1000; // 5 minutes. private ContextAwareResult _writeAsyncResult; private LazyAsyncResult _readAsyncResult; private LazyAsyncResult _requestCompleteAsyncResult; private static readonly NetworkCredential s_defaultFtpNetworkCredential = new NetworkCredential("anonymous", "anonymous@", String.Empty); private const int s_DefaultTimeout = 100000; // 100 seconds private static readonly TimerThread.Queue s_DefaultTimerQueue = TimerThread.GetOrCreateQueue(s_DefaultTimeout); // Used by FtpControlStream internal FtpMethodInfo MethodInfo { get { return _methodInfo; } } // Used by FtpControlStream internal static NetworkCredential DefaultNetworkCredential { get { return s_defaultFtpNetworkCredential; } } public static new RequestCachePolicy DefaultCachePolicy { get { return WebRequest.DefaultCachePolicy; } set { // We don't support caching, so ignore attempts to set this property. } } /// <summary> /// <para> /// Selects FTP command to use. WebRequestMethods.Ftp.DownloadFile is default. /// Not allowed to be changed once request is started. /// </para> /// </summary> public override string Method { get { return _methodInfo.Method; } set { if (String.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_ftp_invalid_method_name, nameof(value)); } if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } try { _methodInfo = FtpMethodInfo.GetMethodInfo(value); } catch (ArgumentException) { throw new ArgumentException(SR.net_ftp_unsupported_method, nameof(value)); } } } /// <summary> /// <para> /// Sets the target name for the WebRequestMethods.Ftp.Rename command. /// Not allowed to be changed once request is started. /// </para> /// </summary> public string RenameTo { get { return _renameTo; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (String.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_ftp_invalid_renameto, nameof(value)); } _renameTo = value; } } /// <summary> /// <para>Used for clear text authentication with FTP server</para> /// </summary> public override ICredentials Credentials { get { return _authInfo; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value == CredentialCache.DefaultNetworkCredentials) { throw new ArgumentException(SR.net_ftp_no_defaultcreds, nameof(value)); } _authInfo = value; } } /// <summary> /// <para>Gets the Uri used to make the request</para> /// </summary> public override Uri RequestUri { get { return _uri; } } /// <summary> /// <para>Timeout of the blocking calls such as GetResponse and GetRequestStream (default 100 secs)</para> /// </summary> public override int Timeout { get { return _timeout; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value < 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero); } if (_timeout != value) { _timeout = value; _timerQueue = null; } } } internal int RemainingTimeout { get { return _remainingTimeout; } } /// <summary> /// <para>Used to control the Timeout when calling Stream.Read and Stream.Write. /// Applies to Streams returned from GetResponse().GetResponseStream() and GetRequestStream(). /// Default is 5 mins. /// </para> /// </summary> public int ReadWriteTimeout { get { return _readWriteTimeout; } set { if (_getResponseStarted) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero); } _readWriteTimeout = value; } } /// <summary> /// <para>Used to specify what offset we will read at</para> /// </summary> public long ContentOffset { get { return _contentOffset; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _contentOffset = value; } } /// <summary> /// <para>Gets or sets the data size of to-be uploaded data</para> /// </summary> public override long ContentLength { get { return _contentLength; } set { _contentLength = value; } } public override IWebProxy Proxy { get { return null; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } // Ignore, since we do not support proxied requests. } } public override string ConnectionGroupName { get { return _connectionGroupName; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } _connectionGroupName = value; } } public ServicePoint ServicePoint { get { if (_servicePoint == null) { _servicePoint = ServicePointManager.FindServicePoint(_uri); } return _servicePoint; } } internal bool Aborted { get { return _aborted; } } internal FtpWebRequest(Uri uri) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, uri); if ((object)uri.Scheme != (object)Uri.UriSchemeFtp) throw new ArgumentOutOfRangeException(nameof(uri)); _timerCallback = new TimerThread.Callback(TimerCallback); _syncObject = new object(); NetworkCredential networkCredential = null; _uri = uri; _methodInfo = FtpMethodInfo.GetMethodInfo(WebRequestMethods.Ftp.DownloadFile); if (_uri.UserInfo != null && _uri.UserInfo.Length != 0) { string userInfo = _uri.UserInfo; string username = userInfo; string password = ""; int index = userInfo.IndexOf(':'); if (index != -1) { username = Uri.UnescapeDataString(userInfo.Substring(0, index)); index++; // skip ':' password = Uri.UnescapeDataString(userInfo.Substring(index, userInfo.Length - index)); } networkCredential = new NetworkCredential(username, password); } if (networkCredential == null) { networkCredential = s_defaultFtpNetworkCredential; } _authInfo = networkCredential; } // // Used to query for the Response of an FTP request // public override WebResponse GetResponse() { if (NetEventSource.IsEnabled) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } try { CheckError(); if (_ftpWebResponse != null) { return _ftpWebResponse; } if (_getResponseStarted) { throw new InvalidOperationException(SR.net_repcall); } _getResponseStarted = true; _startTime = DateTime.UtcNow; _remainingTimeout = Timeout; if (Timeout != System.Threading.Timeout.Infinite) { _remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds); if (_remainingTimeout <= 0) { throw ExceptionHelper.TimeoutException; } } RequestStage prev = FinishRequestStage(RequestStage.RequestStarted); if (prev >= RequestStage.RequestStarted) { if (prev < RequestStage.ReadReady) { lock (_syncObject) { if (_requestStage < RequestStage.ReadReady) _readAsyncResult = new LazyAsyncResult(null, null, null); } // GetRequeststream or BeginGetRequestStream has not finished yet if (_readAsyncResult != null) _readAsyncResult.InternalWaitForCompletion(); CheckError(); } } else { SubmitRequest(false); if (_methodInfo.IsUpload) FinishRequestStage(RequestStage.WriteReady); else FinishRequestStage(RequestStage.ReadReady); CheckError(); EnsureFtpWebResponse(null); } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); // if _exception == null, we are about to throw an exception to the user // and we haven't saved the exception, which also means we haven't dealt // with it. So just release the connection and log this for investigation. if (_exception == null) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); SetException(exception); FinishRequestStage(RequestStage.CheckForError); } throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this, _ftpWebResponse); } return _ftpWebResponse; } /// <summary> /// <para>Used to query for the Response of an FTP request [async version]</para> /// </summary> public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this); NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } ContextAwareResult asyncResult; try { if (_ftpWebResponse != null) { asyncResult = new ContextAwareResult(this, state, callback); asyncResult.InvokeCallback(_ftpWebResponse); return asyncResult; } if (_getResponseStarted) { throw new InvalidOperationException(SR.net_repcall); } _getResponseStarted = true; CheckError(); RequestStage prev = FinishRequestStage(RequestStage.RequestStarted); asyncResult = new ContextAwareResult(true, true, this, state, callback); _readAsyncResult = asyncResult; if (prev >= RequestStage.RequestStarted) { // To make sure the context is flowed asyncResult.StartPostingAsyncOp(); asyncResult.FinishPostingAsyncOp(); if (prev >= RequestStage.ReadReady) asyncResult = null; else { lock (_syncObject) { if (_requestStage >= RequestStage.ReadReady) asyncResult = null; ; } } if (asyncResult == null) { // need to complete it now asyncResult = (ContextAwareResult)_readAsyncResult; if (!asyncResult.InternalPeekCompleted) asyncResult.InvokeCallback(); } } else { // Do internal processing in this handler to optimize context flowing. lock (asyncResult.StartPostingAsyncOp()) { SubmitRequest(true); asyncResult.FinishPostingAsyncOp(); } FinishRequestStage(RequestStage.CheckForError); } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return asyncResult; } /// <summary> /// <para>Returns result of query for the Response of an FTP request [async version]</para> /// </summary> public override WebResponse EndGetResponse(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); try { // parameter validation if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult; if (castedAsyncResult == null) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (castedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse")); } castedAsyncResult.InternalWaitForCompletion(); castedAsyncResult.EndCalled = true; CheckError(); } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return _ftpWebResponse; } /// <summary> /// <para>Used to query for the Request stream of an FTP Request</para> /// </summary> public override Stream GetRequestStream() { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this); NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } try { if (_getRequestStreamStarted) { throw new InvalidOperationException(SR.net_repcall); } _getRequestStreamStarted = true; if (!_methodInfo.IsUpload) { throw new ProtocolViolationException(SR.net_nouploadonget); } CheckError(); _startTime = DateTime.UtcNow; _remainingTimeout = Timeout; if (Timeout != System.Threading.Timeout.Infinite) { _remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds); if (_remainingTimeout <= 0) { throw ExceptionHelper.TimeoutException; } } FinishRequestStage(RequestStage.RequestStarted); SubmitRequest(false); FinishRequestStage(RequestStage.WriteReady); CheckError(); if (_stream.CanTimeout) { _stream.WriteTimeout = ReadWriteTimeout; _stream.ReadTimeout = ReadWriteTimeout; } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return _stream; } /// <summary> /// <para>Used to query for the Request stream of an FTP Request [async version]</para> /// </summary> public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this); NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } ContextAwareResult asyncResult = null; try { if (_getRequestStreamStarted) { throw new InvalidOperationException(SR.net_repcall); } _getRequestStreamStarted = true; if (!_methodInfo.IsUpload) { throw new ProtocolViolationException(SR.net_nouploadonget); } CheckError(); FinishRequestStage(RequestStage.RequestStarted); asyncResult = new ContextAwareResult(true, true, this, state, callback); lock (asyncResult.StartPostingAsyncOp()) { _writeAsyncResult = asyncResult; SubmitRequest(true); asyncResult.FinishPostingAsyncOp(); FinishRequestStage(RequestStage.CheckForError); } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return asyncResult; } public override Stream EndGetRequestStream(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); Stream requestStream = null; try { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult; if (castedAsyncResult == null) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (castedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse")); } castedAsyncResult.InternalWaitForCompletion(); castedAsyncResult.EndCalled = true; CheckError(); requestStream = _stream; castedAsyncResult.EndCalled = true; if (requestStream.CanTimeout) { requestStream.WriteTimeout = ReadWriteTimeout; requestStream.ReadTimeout = ReadWriteTimeout; } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return requestStream; } // // NOTE1: The caller must synchronize access to SubmitRequest(), only one call is allowed for a particular request. // NOTE2: This method eats all exceptions so the caller must rethrow them. // private void SubmitRequest(bool isAsync) { try { _async = isAsync; // // FYI: Will do 2 attempts max as per AttemptedRecovery // Stream stream; while (true) { FtpControlStream connection = _connection; if (connection == null) { if (isAsync) { CreateConnectionAsync(); return; } connection = CreateConnection(); _connection = connection; } if (!isAsync) { if (Timeout != System.Threading.Timeout.Infinite) { _remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds); if (_remainingTimeout <= 0) { throw ExceptionHelper.TimeoutException; } } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Request being submitted"); connection.SetSocketTimeoutOption(RemainingTimeout); try { stream = TimedSubmitRequestHelper(isAsync); } catch (Exception e) { if (AttemptedRecovery(e)) { if (!isAsync) { if (Timeout != System.Threading.Timeout.Infinite) { _remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds); if (_remainingTimeout <= 0) { throw; } } } continue; } throw; } // no retry needed break; } } catch (WebException webException) { // If this was a timeout, throw a timeout exception IOException ioEx = webException.InnerException as IOException; if (ioEx != null) { SocketException sEx = ioEx.InnerException as SocketException; if (sEx != null) { if (sEx.SocketErrorCode == SocketError.TimedOut) { SetException(new WebException(SR.net_timeout, WebExceptionStatus.Timeout)); } } } SetException(webException); } catch (Exception exception) { SetException(exception); } } private Exception TranslateConnectException(Exception e) { SocketException se = e as SocketException; if (se != null) { if (se.SocketErrorCode == SocketError.HostNotFound) { return new WebException(SR.net_webstatus_NameResolutionFailure, WebExceptionStatus.NameResolutionFailure); } else { return new WebException(SR.net_webstatus_ConnectFailure, WebExceptionStatus.ConnectFailure); } } // Wasn't a socket error, so leave as is return e; } private async void CreateConnectionAsync() { string hostname = _uri.Host; int port = _uri.Port; TcpClient client = new TcpClient(); object result; try { await client.ConnectAsync(hostname, port).ConfigureAwait(false); result = new FtpControlStream(client); } catch (Exception e) { result = TranslateConnectException(e); } AsyncRequestCallback(result); } private FtpControlStream CreateConnection() { string hostname = _uri.Host; int port = _uri.Port; TcpClient client = new TcpClient(); try { client.Connect(hostname, port); } catch (Exception e) { throw TranslateConnectException(e); } return new FtpControlStream(client); } private Stream TimedSubmitRequestHelper(bool isAsync) { if (isAsync) { // non-null in the case of re-submit (recovery) if (_requestCompleteAsyncResult == null) _requestCompleteAsyncResult = new LazyAsyncResult(null, null, null); return _connection.SubmitRequest(this, true, true); } Stream stream = null; bool timedOut = false; TimerThread.Timer timer = TimerQueue.CreateTimer(_timerCallback, null); try { stream = _connection.SubmitRequest(this, false, true); } catch (Exception exception) { if (!(exception is SocketException || exception is ObjectDisposedException) || !timer.HasExpired) { timer.Cancel(); throw; } timedOut = true; } if (timedOut || !timer.Cancel()) { _timedOut = true; throw ExceptionHelper.TimeoutException; } if (stream != null) { lock (_syncObject) { if (_aborted) { ((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent); CheckError(); //must throw throw new InternalException(); //consider replacing this on Assert } _stream = stream; } } return stream; } /// <summary> /// <para>Because this is called from the timer thread, neither it nor any methods it calls can call user code.</para> /// </summary> private void TimerCallback(TimerThread.Timer timer, int timeNoticed, object context) { if (NetEventSource.IsEnabled) NetEventSource.Info(this); FtpControlStream connection = _connection; if (connection != null) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "aborting connection"); connection.AbortConnect(); } } private TimerThread.Queue TimerQueue { get { if (_timerQueue == null) { _timerQueue = TimerThread.GetOrCreateQueue(RemainingTimeout); } return _timerQueue; } } /// <summary> /// <para>Returns true if we should restart the request after an error</para> /// </summary> private bool AttemptedRecovery(Exception e) { if (e is OutOfMemoryException || _onceFailed || _aborted || _timedOut || _connection == null || !_connection.RecoverableFailure) { return false; } _onceFailed = true; lock (_syncObject) { if (_connection != null) { _connection.CloseSocket(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connection: {_connection}"); _connection = null; } else { return false; } } return true; } /// <summary> /// <para>Updates and sets our exception to be thrown</para> /// </summary> private void SetException(Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Info(this); if (exception is OutOfMemoryException) { _exception = exception; throw exception; } FtpControlStream connection = _connection; if (_exception == null) { if (exception is WebException) { EnsureFtpWebResponse(exception); _exception = new WebException(exception.Message, null, ((WebException)exception).Status, _ftpWebResponse); } else if (exception is AuthenticationException || exception is SecurityException) { _exception = exception; } else if (connection != null && connection.StatusCode != FtpStatusCode.Undefined) { EnsureFtpWebResponse(exception); _exception = new WebException(SR.Format(SR.net_ftp_servererror, connection.StatusLine), exception, WebExceptionStatus.ProtocolError, _ftpWebResponse); } else { _exception = new WebException(exception.Message, exception); } if (connection != null && _ftpWebResponse != null) _ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage); } } /// <summary> /// <para>Opposite of SetException, rethrows the exception</para> /// </summary> private void CheckError() { if (_exception != null) { ExceptionDispatchInfo.Capture(_exception).Throw(); } } internal void RequestCallback(object obj) { if (_async) AsyncRequestCallback(obj); else SyncRequestCallback(obj); } // // Only executed for Sync requests when the pipline is completed // private void SyncRequestCallback(object obj) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, obj); RequestStage stageMode = RequestStage.CheckForError; try { bool completedRequest = obj == null; Exception exception = obj as Exception; if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"exp:{exception} completedRequest:{completedRequest}"); if (exception != null) { SetException(exception); } else if (!completedRequest) { throw new InternalException(); } else { FtpControlStream connection = _connection; if (connection != null) { EnsureFtpWebResponse(null); // This to update response status and exit message if any. // Note that status 221 "Service closing control connection" is always suppressed. _ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage); } stageMode = RequestStage.ReleaseConnection; } } catch (Exception exception) { SetException(exception); } finally { FinishRequestStage(stageMode); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); CheckError(); //will throw on error } } // // Only executed for Async requests // private void AsyncRequestCallback(object obj) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, obj); RequestStage stageMode = RequestStage.CheckForError; try { FtpControlStream connection; connection = obj as FtpControlStream; FtpDataStream stream = obj as FtpDataStream; Exception exception = obj as Exception; bool completedRequest = (obj == null); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"stream:{stream} conn:{connection} exp:{exception} completedRequest:{completedRequest}"); while (true) { if (exception != null) { if (AttemptedRecovery(exception)) { connection = CreateConnection(); if (connection == null) return; exception = null; } if (exception != null) { SetException(exception); break; } } if (connection != null) { lock (_syncObject) { if (_aborted) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connect:{connection}"); connection.CloseSocket(); break; } _connection = connection; if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _connection); } try { stream = (FtpDataStream)TimedSubmitRequestHelper(true); } catch (Exception e) { exception = e; continue; } return; } else if (stream != null) { lock (_syncObject) { if (_aborted) { ((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent); break; } _stream = stream; } stream.SetSocketTimeoutOption(Timeout); EnsureFtpWebResponse(null); stageMode = stream.CanRead ? RequestStage.ReadReady : RequestStage.WriteReady; } else if (completedRequest) { connection = _connection; if (connection != null) { EnsureFtpWebResponse(null); // This to update response status and exit message if any. // Note that the status 221 "Service closing control connection" is always suppressed. _ftpWebResponse.UpdateStatus(connection.StatusCode, connection.StatusLine, connection.ExitMessage); } stageMode = RequestStage.ReleaseConnection; } else { throw new InternalException(); } break; } } catch (Exception exception) { SetException(exception); } finally { FinishRequestStage(stageMode); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } } private enum RequestStage { CheckForError = 0, // Do nothing except if there is an error then auto promote to ReleaseConnection RequestStarted, // Mark this request as started WriteReady, // First half is done, i.e. either writer or response stream. This is always assumed unless Started or CheckForError ReadReady, // Second half is done, i.e. the read stream can be accesses. ReleaseConnection // Release the control connection (request is read i.e. done-done) } // // Returns a previous stage // private RequestStage FinishRequestStage(RequestStage stage) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"state:{stage}"); if (_exception != null) stage = RequestStage.ReleaseConnection; RequestStage prev; LazyAsyncResult writeResult; LazyAsyncResult readResult; FtpControlStream connection; lock (_syncObject) { prev = _requestStage; if (stage == RequestStage.CheckForError) return prev; if (prev == RequestStage.ReleaseConnection && stage == RequestStage.ReleaseConnection) { return RequestStage.ReleaseConnection; } if (stage > prev) _requestStage = stage; if (stage <= RequestStage.RequestStarted) return prev; writeResult = _writeAsyncResult; readResult = _readAsyncResult; connection = _connection; if (stage == RequestStage.ReleaseConnection) { if (_exception == null && !_aborted && prev != RequestStage.ReadReady && _methodInfo.IsDownload && !_ftpWebResponse.IsFromCache) { return prev; } _connection = null; } } try { // First check to see on releasing the connection if ((stage == RequestStage.ReleaseConnection || prev == RequestStage.ReleaseConnection) && connection != null) { try { if (_exception != null) { connection.Abort(_exception); } } finally { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Releasing connection: {connection}"); connection.CloseSocket(); if (_async) if (_requestCompleteAsyncResult != null) _requestCompleteAsyncResult.InvokeCallback(); } } return prev; } finally { try { // In any case we want to signal the writer if came here if (stage >= RequestStage.WriteReady) { // If writeResult == null and this is an upload request, it means // that the user has called GetResponse() without calling // GetRequestStream() first. So they are not interested in a // stream. Therefore we close the stream so that the // request/pipeline can continue if (_methodInfo.IsUpload && !_getRequestStreamStarted) { if (_stream != null) _stream.Close(); } else if (writeResult != null && !writeResult.InternalPeekCompleted) writeResult.InvokeCallback(); } } finally { // The response is ready either with or without a stream if (stage >= RequestStage.ReadReady && readResult != null && !readResult.InternalPeekCompleted) readResult.InvokeCallback(); } } } /// <summary> /// <para>Aborts underlying connection to FTP server (command & data)</para> /// </summary> public override void Abort() { if (_aborted) return; if (NetEventSource.IsEnabled) NetEventSource.Enter(this); try { Stream stream; FtpControlStream connection; lock (_syncObject) { if (_requestStage >= RequestStage.ReleaseConnection) return; _aborted = true; stream = _stream; connection = _connection; _exception = ExceptionHelper.RequestAbortedException; } if (stream != null) { if (!(stream is ICloseEx)) { NetEventSource.Fail(this, "The _stream member is not CloseEx hence the risk of connection been orphaned."); } ((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent); } if (connection != null) connection.Abort(ExceptionHelper.RequestAbortedException); } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } } public bool KeepAlive { get { return false; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } // We don't support connection pooling, so just silently ignore this. } } public override RequestCachePolicy CachePolicy { get { return FtpWebRequest.DefaultCachePolicy; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } // We don't support caching, so just silently ignore this. } } /// <summary> /// <para>True by default, false allows transmission using text mode</para> /// </summary> public bool UseBinary { get { return _binary; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } _binary = value; } } public bool UsePassive { get { return _passive; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } _passive = value; } } public X509CertificateCollection ClientCertificates { get { return LazyInitializer.EnsureInitialized(ref _clientCertificates, ref _syncObject, () => new X509CertificateCollection()); } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } _clientCertificates = value; } } /// <summary> /// <para>Set to true if we need SSL</para> /// </summary> public bool EnableSsl { get { return _enableSsl; } set { if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); } _enableSsl = value; } } public override WebHeaderCollection Headers { get { if (_ftpRequestHeaders == null) { _ftpRequestHeaders = new WebHeaderCollection(); } return _ftpRequestHeaders; } set { _ftpRequestHeaders = value; } } // NOT SUPPORTED method public override string ContentType { get { throw ExceptionHelper.PropertyNotSupportedException; } set { throw ExceptionHelper.PropertyNotSupportedException; } } // NOT SUPPORTED method public override bool UseDefaultCredentials { get { throw ExceptionHelper.PropertyNotSupportedException; } set { throw ExceptionHelper.PropertyNotSupportedException; } } // NOT SUPPORTED method public override bool PreAuthenticate { get { throw ExceptionHelper.PropertyNotSupportedException; } set { throw ExceptionHelper.PropertyNotSupportedException; } } /// <summary> /// <para>True if a request has been submitted (ie already active)</para> /// </summary> private bool InUse { get { if (_getRequestStreamStarted || _getResponseStarted) { return true; } else { return false; } } } /// <summary> /// <para>Creates an FTP WebResponse based off the responseStream and our active Connection</para> /// </summary> private void EnsureFtpWebResponse(Exception exception) { if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null)) { lock (_syncObject) { if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null)) { Stream responseStream = _stream; if (_methodInfo.IsUpload) { responseStream = null; } if (_stream != null && _stream.CanRead && _stream.CanTimeout) { _stream.ReadTimeout = ReadWriteTimeout; _stream.WriteTimeout = ReadWriteTimeout; } FtpControlStream connection = _connection; long contentLength = connection != null ? connection.ContentLength : -1; if (responseStream == null) { // If the last command was SIZE, we set the ContentLength on // the FtpControlStream to be the size of the file returned in the // response. We should propagate that file size to the response so // users can access it. This also maintains the compatibility with // HTTP when returning size instead of content. if (contentLength < 0) contentLength = 0; } if (_ftpWebResponse != null) { _ftpWebResponse.SetResponseStream(responseStream); } else { if (connection != null) _ftpWebResponse = new FtpWebResponse(responseStream, contentLength, connection.ResponseUri, connection.StatusCode, connection.StatusLine, connection.LastModified, connection.BannerMessage, connection.WelcomeMessage, connection.ExitMessage); else _ftpWebResponse = new FtpWebResponse(responseStream, -1, _uri, FtpStatusCode.Undefined, null, DateTime.Now, null, null, null); } } } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Returns {_ftpWebResponse} with stream {_ftpWebResponse._responseStream}"); return; } /// <summary> /// <para>Returns username string</para> /// </summary> internal string GetUserString() { string name = null; if (this.Credentials != null) { NetworkCredential networkCreds = this.Credentials.GetCredential(_uri, "basic"); if (networkCreds != null) { name = networkCreds.UserName; string domain = networkCreds.Domain; if (!string.IsNullOrEmpty(domain)) { name = domain + "\\" + name; } } } return name == null ? null : (String.Compare(name, "anonymous", StringComparison.InvariantCultureIgnoreCase) == 0 ? null : name); } internal void DataStreamClosed(CloseExState closeState) { if ((closeState & CloseExState.Abort) == 0) { if (!_async) { if (_connection != null) _connection.CheckContinuePipeline(); } else { _requestCompleteAsyncResult.InternalWaitForCompletion(); CheckError(); } } else { FtpControlStream connection = _connection; if (connection != null) connection.Abort(ExceptionHelper.RequestAbortedException); } } } // class FtpWebRequest // // Class used by the WebRequest.Create factory to create FTP requests // internal class FtpWebRequestCreator : IWebRequestCreate { internal FtpWebRequestCreator() { } public WebRequest Create(Uri uri) { return new FtpWebRequest(uri); } } // class FtpWebRequestCreator } // namespace System.Net
// // TypeParser.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // 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.Text; using Mono.Cecil.Metadata; namespace Mono.Cecil { class TypeParser { class Type { public const int Ptr = -1; public const int ByRef = -2; public const int SzArray = -3; public string type_fullname; public string [] nested_names; public int arity; public int [] specs; public Type [] generic_arguments; public string assembly; } readonly string fullname; readonly int length; int position; TypeParser (string fullname) { this.fullname = fullname; this.length = fullname.Length; } Type ParseType (bool fq_name) { var type = new Type (); type.type_fullname = ParsePart (); type.nested_names = ParseNestedNames (); if (TryGetArity (type)) type.generic_arguments = ParseGenericArguments (type.arity); type.specs = ParseSpecs (); if (fq_name) type.assembly = ParseAssemblyName (); return type; } static bool TryGetArity (Type type) { int arity = 0; TryAddArity (type.type_fullname, ref arity); var nested_names = type.nested_names; if (!nested_names.IsNullOrEmpty ()) { for (int i = 0; i < nested_names.Length; i++) TryAddArity (nested_names [i], ref arity); } type.arity = arity; return arity > 0; } static bool TryGetArity (string name, out int arity) { arity = 0; var index = name.LastIndexOf ('`'); if (index == -1) return false; return ParseInt32 (name.Substring (index + 1), out arity); } static bool ParseInt32 (string value, out int result) { #if CF try { result = int.Parse (value); return true; } catch { result = 0; return false; } #else return int.TryParse (value, out result); #endif } static void TryAddArity (string name, ref int arity) { int type_arity; if (!TryGetArity (name, out type_arity)) return; arity += type_arity; } string ParsePart () { var part = new StringBuilder (); while (position < length && !IsDelimiter (fullname [position])) { if (fullname [position] == '\\') position++; part.Append (fullname [position++]); } return part.ToString (); } static bool IsDelimiter (char chr) { return "+,[]*&".IndexOf (chr) != -1; } void TryParseWhiteSpace () { while (position < length && Char.IsWhiteSpace (fullname [position])) position++; } string [] ParseNestedNames () { string [] nested_names = null; while (TryParse ('+')) Add (ref nested_names, ParsePart ()); return nested_names; } bool TryParse (char chr) { if (position < length && fullname [position] == chr) { position++; return true; } return false; } static void Add<T> (ref T [] array, T item) { if (array == null) { array = new [] { item }; return; } array = array.Resize (array.Length + 1); array [array.Length - 1] = item; } int [] ParseSpecs () { int [] specs = null; while (position < length) { switch (fullname [position]) { case '*': position++; Add (ref specs, Type.Ptr); break; case '&': position++; Add (ref specs, Type.ByRef); break; case '[': position++; switch (fullname [position]) { case ']': position++; Add (ref specs, Type.SzArray); break; case '*': position++; Add (ref specs, 1); break; default: var rank = 1; while (TryParse (',')) rank++; Add (ref specs, rank); TryParse (']'); break; } break; default: return specs; } } return specs; } Type [] ParseGenericArguments (int arity) { Type [] generic_arguments = null; if (position == length || fullname [position] != '[') return generic_arguments; TryParse ('['); for (int i = 0; i < arity; i++) { var fq_argument = TryParse ('['); Add (ref generic_arguments, ParseType (fq_argument)); if (fq_argument) TryParse (']'); TryParse (','); TryParseWhiteSpace (); } TryParse (']'); return generic_arguments; } string ParseAssemblyName () { if (!TryParse (',')) return string.Empty; TryParseWhiteSpace (); var start = position; while (position < length) { var chr = fullname [position]; if (chr == '[' || chr == ']') break; position++; } return fullname.Substring (start, position - start); } public static TypeReference ParseType (ModuleDefinition module, string fullname) { if (string.IsNullOrEmpty (fullname)) return null; var parser = new TypeParser (fullname); return GetTypeReference (module, parser.ParseType (true)); } static TypeReference GetTypeReference (ModuleDefinition module, Type type_info) { TypeReference type; if (!TryGetDefinition (module, type_info, out type)) type = CreateReference (type_info, module, GetMetadataScope (module, type_info)); return CreateSpecs (type, type_info); } static TypeReference CreateSpecs (TypeReference type, Type type_info) { type = TryCreateGenericInstanceType (type, type_info); var specs = type_info.specs; if (specs.IsNullOrEmpty ()) return type; for (int i = 0; i < specs.Length; i++) { switch (specs [i]) { case Type.Ptr: type = new PointerType (type); break; case Type.ByRef: type = new ByReferenceType (type); break; case Type.SzArray: type = new ArrayType (type); break; default: var array = new ArrayType (type); array.Dimensions.Clear (); for (int j = 0; j < specs [i]; j++) array.Dimensions.Add (new ArrayDimension ()); type = array; break; } } return type; } static TypeReference TryCreateGenericInstanceType (TypeReference type, Type type_info) { var generic_arguments = type_info.generic_arguments; if (generic_arguments.IsNullOrEmpty ()) return type; var instance = new GenericInstanceType (type); var instance_arguments = instance.GenericArguments; for (int i = 0; i < generic_arguments.Length; i++) instance_arguments.Add (GetTypeReference (type.Module, generic_arguments [i])); return instance; } public static void SplitFullName (string fullname, out string @namespace, out string name) { var last_dot = fullname.LastIndexOf ('.'); if (last_dot == -1) { @namespace = string.Empty; name = fullname; } else { @namespace = fullname.Substring (0, last_dot); name = fullname.Substring (last_dot + 1); } } static TypeReference CreateReference (Type type_info, ModuleDefinition module, IMetadataScope scope) { string @namespace, name; SplitFullName (type_info.type_fullname, out @namespace, out name); var type = new TypeReference (@namespace, name, module, scope); MetadataSystem.TryProcessPrimitiveTypeReference (type); AdjustGenericParameters (type); var nested_names = type_info.nested_names; if (nested_names.IsNullOrEmpty ()) return type; for (int i = 0; i < nested_names.Length; i++) { type = new TypeReference (string.Empty, nested_names [i], module, null) { DeclaringType = type, }; AdjustGenericParameters (type); } return type; } static void AdjustGenericParameters (TypeReference type) { int arity; if (!TryGetArity (type.Name, out arity)) return; for (int i = 0; i < arity; i++) type.GenericParameters.Add (new GenericParameter (type)); } static IMetadataScope GetMetadataScope (ModuleDefinition module, Type type_info) { if (string.IsNullOrEmpty (type_info.assembly)) return module.TypeSystem.Corlib; return MatchReference (module, AssemblyNameReference.Parse (type_info.assembly)); } static AssemblyNameReference MatchReference (ModuleDefinition module, AssemblyNameReference pattern) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (reference.FullName == pattern.FullName) return reference; } return pattern; } static bool TryGetDefinition (ModuleDefinition module, Type type_info, out TypeReference type) { type = null; if (!TryCurrentModule (module, type_info)) return false; var typedef = module.GetType (type_info.type_fullname); if (typedef == null) return false; var nested_names = type_info.nested_names; if (!nested_names.IsNullOrEmpty ()) { for (int i = 0; i < nested_names.Length; i++) typedef = typedef.GetNestedType (nested_names [i]); } type = typedef; return true; } static bool TryCurrentModule (ModuleDefinition module, Type type_info) { if (string.IsNullOrEmpty (type_info.assembly)) return true; if (module.assembly != null && module.assembly.Name.FullName == type_info.assembly) return true; return false; } public static string ToParseable (TypeReference type) { if (type == null) return null; var name = new StringBuilder (); AppendType (type, name, true, true); return name.ToString (); } static void AppendNamePart (string part, StringBuilder name) { foreach (var c in part) { if (IsDelimiter (c)) name.Append ('\\'); name.Append (c); } } static void AppendType (TypeReference type, StringBuilder name, bool fq_name, bool top_level) { var declaring_type = type.DeclaringType; if (declaring_type != null) { AppendType (declaring_type, name, false, top_level); name.Append ('+'); } var @namespace = type.Namespace; if (!string.IsNullOrEmpty (@namespace)) { AppendNamePart (@namespace, name); name.Append ('.'); } AppendNamePart (type.GetElementType ().Name, name); if (!fq_name) return; if (type.IsTypeSpecification ()) AppendTypeSpecification ((TypeSpecification) type, name); if (RequiresFullyQualifiedName (type, top_level)) { name.Append (", "); name.Append (GetScopeFullName (type)); } } static string GetScopeFullName (TypeReference type) { var scope = type.Scope; switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: return ((AssemblyNameReference) scope).FullName; case MetadataScopeType.ModuleDefinition: return ((ModuleDefinition) scope).Assembly.Name.FullName; } throw new ArgumentException (); } static void AppendTypeSpecification (TypeSpecification type, StringBuilder name) { if (type.ElementType.IsTypeSpecification ()) AppendTypeSpecification ((TypeSpecification) type.ElementType, name); switch (type.etype) { case ElementType.Ptr: name.Append ('*'); break; case ElementType.ByRef: name.Append ('&'); break; case ElementType.SzArray: case ElementType.Array: var array = (ArrayType) type; if (array.IsVector) { name.Append ("[]"); } else { name.Append ('['); for (int i = 1; i < array.Rank; i++) name.Append (','); name.Append (']'); } break; case ElementType.GenericInst: var instance = (GenericInstanceType) type; var arguments = instance.GenericArguments; name.Append ('['); for (int i = 0; i < arguments.Count; i++) { if (i > 0) name.Append (','); var argument = arguments [i]; var requires_fqname = argument.Scope != argument.Module; if (requires_fqname) name.Append ('['); AppendType (argument, name, true, false); if (requires_fqname) name.Append (']'); } name.Append (']'); break; default: return; } } static bool RequiresFullyQualifiedName (TypeReference type, bool top_level) { if (type.Scope == type.Module) return false; if (type.Scope.Name == "mscorlib" && top_level) return false; return true; } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // 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 Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using Controls; namespace CallButler.Manager.Controls { partial class VoicemailControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VoicemailControl)); this.btnPrevious = new System.Windows.Forms.Button(); this.btnPlay = new System.Windows.Forms.Button(); this.btnStop = new System.Windows.Forms.Button(); this.btnNext = new System.Windows.Forms.Button(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.btnDeleteMessage = new System.Windows.Forms.Button(); this.btnSaveMessage = new System.Windows.Forms.Button(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.progSound = new global::Controls.ProgressBarEx(); this.lblNewMessage = new global::Controls.SmoothLabel(); this.lblTelephoneNumber = new global::Controls.SmoothLabel(); this.lblCallerID = new global::Controls.SmoothLabel(); this.lblDateTime = new global::Controls.SmoothLabel(); this.lblMessageCount = new global::Controls.SmoothLabel(); this.trkVolume = new global::Controls.TrackBarEx(); this.voicemailDataset = new WOSI.CallButler.Data.CallButlerDataset(); this.bsVoicemails = new System.Windows.Forms.BindingSource(this.components); this.dgVoicemails = new CallButler.Manager.Controls.CallButlerDataGrid(); this.colVoicemailImage = new System.Windows.Forms.DataGridViewImageColumn(); this.voicemailIDDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.extensionIDDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.timestampDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.callerDisplayNameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.callerUsernameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.callerHostDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.isNewDataGridViewCheckBoxColumn = new System.Windows.Forms.DataGridViewCheckBoxColumn(); this.pnlList = new System.Windows.Forms.Panel(); this.gradientPanel1 = new global::Controls.GradientPanel(); this.pnlPlayer = new System.Windows.Forms.Panel(); this.btnImportOutlook = new System.Windows.Forms.Button(); this.toolTip = new System.Windows.Forms.ToolTip(this.components); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.voicemailDataset)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bsVoicemails)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dgVoicemails)).BeginInit(); this.pnlList.SuspendLayout(); this.pnlPlayer.SuspendLayout(); this.SuspendLayout(); // // btnPrevious // this.btnPrevious.BackColor = System.Drawing.Color.Gainsboro; this.btnPrevious.Cursor = System.Windows.Forms.Cursors.Hand; resources.ApplyResources(this.btnPrevious, "btnPrevious"); this.btnPrevious.Image = global::CallButler.Manager.Controls.Properties.Resources.media_step_back_16; this.btnPrevious.Name = "btnPrevious"; this.toolTip.SetToolTip(this.btnPrevious, resources.GetString("btnPrevious.ToolTip")); this.btnPrevious.UseVisualStyleBackColor = false; this.btnPrevious.Click += new System.EventHandler(this.btnPrevious_Click); // // btnPlay // this.btnPlay.BackColor = System.Drawing.Color.Gainsboro; this.btnPlay.Cursor = System.Windows.Forms.Cursors.Hand; resources.ApplyResources(this.btnPlay, "btnPlay"); this.btnPlay.Image = global::CallButler.Manager.Controls.Properties.Resources.media_play_16; this.btnPlay.Name = "btnPlay"; this.toolTip.SetToolTip(this.btnPlay, resources.GetString("btnPlay.ToolTip")); this.btnPlay.UseVisualStyleBackColor = false; this.btnPlay.Click += new System.EventHandler(this.btnPlay_Click); // // btnStop // this.btnStop.BackColor = System.Drawing.Color.Gainsboro; this.btnStop.Cursor = System.Windows.Forms.Cursors.Hand; resources.ApplyResources(this.btnStop, "btnStop"); this.btnStop.Image = global::CallButler.Manager.Controls.Properties.Resources.media_stop_red_16; this.btnStop.Name = "btnStop"; this.toolTip.SetToolTip(this.btnStop, resources.GetString("btnStop.ToolTip")); this.btnStop.UseVisualStyleBackColor = false; this.btnStop.Click += new System.EventHandler(this.btnStop_Click); // // btnNext // this.btnNext.BackColor = System.Drawing.Color.Gainsboro; this.btnNext.Cursor = System.Windows.Forms.Cursors.Hand; resources.ApplyResources(this.btnNext, "btnNext"); this.btnNext.Image = global::CallButler.Manager.Controls.Properties.Resources.media_step_forward_16; this.btnNext.Name = "btnNext"; this.toolTip.SetToolTip(this.btnNext, resources.GetString("btnNext.ToolTip")); this.btnNext.UseVisualStyleBackColor = false; this.btnNext.Click += new System.EventHandler(this.btnNext_Click); // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.pictureBox1, "pictureBox1"); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.TabStop = false; // // btnDeleteMessage // this.btnDeleteMessage.BackColor = System.Drawing.Color.Gainsboro; this.btnDeleteMessage.Cursor = System.Windows.Forms.Cursors.Hand; resources.ApplyResources(this.btnDeleteMessage, "btnDeleteMessage"); this.btnDeleteMessage.Image = global::CallButler.Manager.Controls.Properties.Resources.error_16; this.btnDeleteMessage.Name = "btnDeleteMessage"; this.toolTip.SetToolTip(this.btnDeleteMessage, resources.GetString("btnDeleteMessage.ToolTip")); this.btnDeleteMessage.UseVisualStyleBackColor = false; this.btnDeleteMessage.Click += new System.EventHandler(this.btnDeleteMessage_Click); // // btnSaveMessage // this.btnSaveMessage.BackColor = System.Drawing.Color.Gainsboro; this.btnSaveMessage.Cursor = System.Windows.Forms.Cursors.Hand; resources.ApplyResources(this.btnSaveMessage, "btnSaveMessage"); this.btnSaveMessage.Image = global::CallButler.Manager.Controls.Properties.Resources.disk_blue_16; this.btnSaveMessage.Name = "btnSaveMessage"; this.toolTip.SetToolTip(this.btnSaveMessage, resources.GetString("btnSaveMessage.ToolTip")); this.btnSaveMessage.UseVisualStyleBackColor = false; this.btnSaveMessage.Click += new System.EventHandler(this.btnSaveMessage_Click); // // pictureBox2 // resources.ApplyResources(this.pictureBox2, "pictureBox2"); this.pictureBox2.BackColor = System.Drawing.Color.Transparent; this.pictureBox2.Image = global::CallButler.Manager.Controls.Properties.Resources.loudspeaker_16; this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.TabStop = false; // // progSound // this.progSound.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(232)))), ((int)(((byte)(255))))); this.progSound.DrawTicks = false; this.progSound.ForeColor = System.Drawing.Color.DimGray; resources.ApplyResources(this.progSound, "progSound"); this.progSound.LowerValue = 0; this.progSound.MaxColor = System.Drawing.Color.DimGray; this.progSound.MaxValue = 100; this.progSound.MinColor = System.Drawing.Color.DimGray; this.progSound.MinValue = 0; this.progSound.Name = "progSound"; this.progSound.UpperValue = 0; // // lblNewMessage // this.lblNewMessage.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(232)))), ((int)(((byte)(255))))); resources.ApplyResources(this.lblNewMessage, "lblNewMessage"); this.lblNewMessage.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.lblNewMessage.Name = "lblNewMessage"; // // lblTelephoneNumber // this.lblTelephoneNumber.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(232)))), ((int)(((byte)(255))))); resources.ApplyResources(this.lblTelephoneNumber, "lblTelephoneNumber"); this.lblTelephoneNumber.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.lblTelephoneNumber.Name = "lblTelephoneNumber"; // // lblCallerID // this.lblCallerID.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(232)))), ((int)(((byte)(255))))); resources.ApplyResources(this.lblCallerID, "lblCallerID"); this.lblCallerID.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.lblCallerID.Name = "lblCallerID"; // // lblDateTime // this.lblDateTime.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(232)))), ((int)(((byte)(255))))); resources.ApplyResources(this.lblDateTime, "lblDateTime"); this.lblDateTime.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.lblDateTime.Name = "lblDateTime"; // // lblMessageCount // this.lblMessageCount.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(232)))), ((int)(((byte)(255))))); resources.ApplyResources(this.lblMessageCount, "lblMessageCount"); this.lblMessageCount.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.lblMessageCount.Name = "lblMessageCount"; // // trkVolume // resources.ApplyResources(this.trkVolume, "trkVolume"); this.trkVolume.BackColor = System.Drawing.Color.Transparent; this.trkVolume.MaxValue = 65535; this.trkVolume.MinValue = 0; this.trkVolume.Name = "trkVolume"; this.trkVolume.Orientation = System.Windows.Forms.Orientation.Vertical; this.trkVolume.TrackerCursor = System.Windows.Forms.Cursors.Hand; this.trkVolume.TrackerImage = ((System.Drawing.Image)(resources.GetObject("trkVolume.TrackerImage"))); this.trkVolume.Value = 0; this.trkVolume.ValueChanged += new System.EventHandler(this.trkVolume_ValueChanged); // // voicemailDataset // this.voicemailDataset.DataSetName = "CallButlerDataset"; this.voicemailDataset.RemotingFormat = System.Data.SerializationFormat.Binary; this.voicemailDataset.SchemaSerializationMode = System.Data.SchemaSerializationMode.ExcludeSchema; // // bsVoicemails // this.bsVoicemails.DataMember = "Voicemails"; this.bsVoicemails.DataSource = this.voicemailDataset; // // dgVoicemails // this.dgVoicemails.AllowUserToAddRows = false; this.dgVoicemails.AllowUserToDeleteRows = false; this.dgVoicemails.AllowUserToResizeRows = false; this.dgVoicemails.AutoGenerateColumns = false; this.dgVoicemails.BackgroundColor = System.Drawing.Color.WhiteSmoke; this.dgVoicemails.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dgVoicemails.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dgVoicemails.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; this.dgVoicemails.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgVoicemails.ColumnHeadersVisible = false; this.dgVoicemails.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colVoicemailImage, this.voicemailIDDataGridViewTextBoxColumn, this.extensionIDDataGridViewTextBoxColumn, this.timestampDataGridViewTextBoxColumn, this.callerDisplayNameDataGridViewTextBoxColumn, this.callerUsernameDataGridViewTextBoxColumn, this.callerHostDataGridViewTextBoxColumn, this.isNewDataGridViewCheckBoxColumn}); this.dgVoicemails.DataSource = this.bsVoicemails; resources.ApplyResources(this.dgVoicemails, "dgVoicemails"); this.dgVoicemails.MultiSelect = false; this.dgVoicemails.Name = "dgVoicemails"; this.dgVoicemails.ReadOnly = true; this.dgVoicemails.RowHeadersVisible = false; this.dgVoicemails.RowTemplate.DefaultCellStyle.BackColor = System.Drawing.Color.WhiteSmoke; this.dgVoicemails.RowTemplate.DefaultCellStyle.Font = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.dgVoicemails.RowTemplate.DefaultCellStyle.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(225)))), ((int)(((byte)(244))))); this.dgVoicemails.RowTemplate.DefaultCellStyle.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.dgVoicemails.RowTemplate.Height = 32; this.dgVoicemails.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dgVoicemails.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.dgVoicemails_CellFormatting); this.dgVoicemails.SelectionChanged += new System.EventHandler(this.dgVoicemails_SelectionChanged); // // colVoicemailImage // this.colVoicemailImage.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.colVoicemailImage, "colVoicemailImage"); this.colVoicemailImage.Image = global::CallButler.Manager.Controls.Properties.Resources.message_16; this.colVoicemailImage.Name = "colVoicemailImage"; this.colVoicemailImage.ReadOnly = true; // // voicemailIDDataGridViewTextBoxColumn // this.voicemailIDDataGridViewTextBoxColumn.DataPropertyName = "VoicemailID"; resources.ApplyResources(this.voicemailIDDataGridViewTextBoxColumn, "voicemailIDDataGridViewTextBoxColumn"); this.voicemailIDDataGridViewTextBoxColumn.Name = "voicemailIDDataGridViewTextBoxColumn"; this.voicemailIDDataGridViewTextBoxColumn.ReadOnly = true; // // extensionIDDataGridViewTextBoxColumn // this.extensionIDDataGridViewTextBoxColumn.DataPropertyName = "ExtensionID"; resources.ApplyResources(this.extensionIDDataGridViewTextBoxColumn, "extensionIDDataGridViewTextBoxColumn"); this.extensionIDDataGridViewTextBoxColumn.Name = "extensionIDDataGridViewTextBoxColumn"; this.extensionIDDataGridViewTextBoxColumn.ReadOnly = true; // // timestampDataGridViewTextBoxColumn // this.timestampDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; this.timestampDataGridViewTextBoxColumn.DataPropertyName = "Timestamp"; resources.ApplyResources(this.timestampDataGridViewTextBoxColumn, "timestampDataGridViewTextBoxColumn"); this.timestampDataGridViewTextBoxColumn.Name = "timestampDataGridViewTextBoxColumn"; this.timestampDataGridViewTextBoxColumn.ReadOnly = true; // // callerDisplayNameDataGridViewTextBoxColumn // this.callerDisplayNameDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.callerDisplayNameDataGridViewTextBoxColumn.DataPropertyName = "CallerDisplayName"; resources.ApplyResources(this.callerDisplayNameDataGridViewTextBoxColumn, "callerDisplayNameDataGridViewTextBoxColumn"); this.callerDisplayNameDataGridViewTextBoxColumn.Name = "callerDisplayNameDataGridViewTextBoxColumn"; this.callerDisplayNameDataGridViewTextBoxColumn.ReadOnly = true; // // callerUsernameDataGridViewTextBoxColumn // this.callerUsernameDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; this.callerUsernameDataGridViewTextBoxColumn.DataPropertyName = "CallerUsername"; resources.ApplyResources(this.callerUsernameDataGridViewTextBoxColumn, "callerUsernameDataGridViewTextBoxColumn"); this.callerUsernameDataGridViewTextBoxColumn.Name = "callerUsernameDataGridViewTextBoxColumn"; this.callerUsernameDataGridViewTextBoxColumn.ReadOnly = true; // // callerHostDataGridViewTextBoxColumn // this.callerHostDataGridViewTextBoxColumn.DataPropertyName = "CallerHost"; resources.ApplyResources(this.callerHostDataGridViewTextBoxColumn, "callerHostDataGridViewTextBoxColumn"); this.callerHostDataGridViewTextBoxColumn.Name = "callerHostDataGridViewTextBoxColumn"; this.callerHostDataGridViewTextBoxColumn.ReadOnly = true; // // isNewDataGridViewCheckBoxColumn // this.isNewDataGridViewCheckBoxColumn.DataPropertyName = "IsNew"; resources.ApplyResources(this.isNewDataGridViewCheckBoxColumn, "isNewDataGridViewCheckBoxColumn"); this.isNewDataGridViewCheckBoxColumn.Name = "isNewDataGridViewCheckBoxColumn"; this.isNewDataGridViewCheckBoxColumn.ReadOnly = true; // // pnlList // this.pnlList.BackColor = System.Drawing.Color.WhiteSmoke; this.pnlList.Controls.Add(this.dgVoicemails); resources.ApplyResources(this.pnlList, "pnlList"); this.pnlList.Name = "pnlList"; // // gradientPanel1 // this.gradientPanel1.BackColor = System.Drawing.Color.DimGray; this.gradientPanel1.BorderColor = System.Drawing.Color.Black; this.gradientPanel1.BorderWidth = 1F; resources.ApplyResources(this.gradientPanel1, "gradientPanel1"); this.gradientPanel1.DrawBorder = false; this.gradientPanel1.ForeColor = System.Drawing.Color.WhiteSmoke; this.gradientPanel1.GradientAngle = 90F; this.gradientPanel1.Name = "gradientPanel1"; // // pnlPlayer // resources.ApplyResources(this.pnlPlayer, "pnlPlayer"); this.pnlPlayer.Controls.Add(this.btnImportOutlook); this.pnlPlayer.Controls.Add(this.pictureBox2); this.pnlPlayer.Controls.Add(this.btnSaveMessage); this.pnlPlayer.Controls.Add(this.progSound); this.pnlPlayer.Controls.Add(this.btnDeleteMessage); this.pnlPlayer.Controls.Add(this.lblNewMessage); this.pnlPlayer.Controls.Add(this.btnPrevious); this.pnlPlayer.Controls.Add(this.lblTelephoneNumber); this.pnlPlayer.Controls.Add(this.btnPlay); this.pnlPlayer.Controls.Add(this.lblCallerID); this.pnlPlayer.Controls.Add(this.btnStop); this.pnlPlayer.Controls.Add(this.lblDateTime); this.pnlPlayer.Controls.Add(this.btnNext); this.pnlPlayer.Controls.Add(this.lblMessageCount); this.pnlPlayer.Controls.Add(this.trkVolume); this.pnlPlayer.Controls.Add(this.pictureBox1); this.pnlPlayer.Name = "pnlPlayer"; // // btnImportOutlook // this.btnImportOutlook.BackColor = System.Drawing.Color.Gainsboro; this.btnImportOutlook.Cursor = System.Windows.Forms.Cursors.Hand; resources.ApplyResources(this.btnImportOutlook, "btnImportOutlook"); this.btnImportOutlook.Image = global::CallButler.Manager.Controls.Properties.Resources.outlook_16; this.btnImportOutlook.Name = "btnImportOutlook"; this.toolTip.SetToolTip(this.btnImportOutlook, resources.GetString("btnImportOutlook.ToolTip")); this.btnImportOutlook.UseVisualStyleBackColor = false; this.btnImportOutlook.Click += new System.EventHandler(this.btnImportOutlook_Click); // // saveFileDialog // resources.ApplyResources(this.saveFileDialog, "saveFileDialog"); // // VoicemailControl // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.pnlList); this.Controls.Add(this.gradientPanel1); this.Controls.Add(this.pnlPlayer); this.Name = "VoicemailControl"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.voicemailDataset)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bsVoicemails)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dgVoicemails)).EndInit(); this.pnlList.ResumeLayout(false); this.pnlPlayer.ResumeLayout(false); this.pnlPlayer.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnPrevious; private System.Windows.Forms.Button btnPlay; private System.Windows.Forms.Button btnStop; private System.Windows.Forms.Button btnNext; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Button btnDeleteMessage; private System.Windows.Forms.Button btnSaveMessage; private TrackBarEx trkVolume; private System.Windows.Forms.PictureBox pictureBox2; private SmoothLabel lblMessageCount; private SmoothLabel lblDateTime; private SmoothLabel lblCallerID; private SmoothLabel lblTelephoneNumber; private SmoothLabel lblNewMessage; private ProgressBarEx progSound; private WOSI.CallButler.Data.CallButlerDataset voicemailDataset; private System.Windows.Forms.BindingSource bsVoicemails; private CallButler.Manager.Controls.CallButlerDataGrid dgVoicemails; private System.Windows.Forms.Panel pnlList; private GradientPanel gradientPanel1; private System.Windows.Forms.Panel pnlPlayer; private System.Windows.Forms.DataGridViewImageColumn colVoicemailImage; private System.Windows.Forms.DataGridViewTextBoxColumn voicemailIDDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn extensionIDDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn timestampDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn callerDisplayNameDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn callerUsernameDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewTextBoxColumn callerHostDataGridViewTextBoxColumn; private System.Windows.Forms.DataGridViewCheckBoxColumn isNewDataGridViewCheckBoxColumn; private System.Windows.Forms.Button btnImportOutlook; private System.Windows.Forms.ToolTip toolTip; private System.Windows.Forms.SaveFileDialog saveFileDialog; } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; namespace SmallSharpTools.WebPreview { public class ThumbnailBuilder { #region " Constants " public const int ImageCompressionQuality = 90; #endregion #region " Events " public event EventHandler ExceptionCatching; /// <summary> /// Raise the ExceptionCatching event /// </summary> /// <param name="e"></param> protected virtual void OnExceptionCatching(EventArgs e) { if (ExceptionCatching != null) { ExceptionCatching(this, e); } } #endregion #region " Methods " public void CreateThumbnail(string sourceFilename, string cachedFilename, int width, int height) { if (File.Exists(sourceFilename)) { FileInfo inputFile = new FileInfo(sourceFilename); FileInfo outputFile = new FileInfo(cachedFilename); if (!outputFile.Directory.Exists) { outputFile.Directory.Create(); } if (outputFile.Exists && inputFile.CreationTime < outputFile.CreationTime) { return; } try { Bitmap inBmp = new Bitmap(sourceFilename); //Bitmap outBmp = new Bitmap(width, height); //using (Graphics g = Graphics.FromImage(outBmp)) //{ // g.InterpolationMode = InterpolationMode.HighQualityBicubic; // g.DrawImage(inBmp, 0, 0, width, height); //} // CREDITS: http://www.thebrainparasite.com/post/Creating-great-thumbnails-in-ASPNET.aspx using (Bitmap outBmp = CreateThumbnail(inBmp, width, height, true)) { //Configure JPEG Compression Engine EncoderParameters encoderParams = new EncoderParameters(); long[] quality = new long[1]; quality[0] = ImageCompressionQuality; EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICI = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICI = arrayICI[x]; break; } } outBmp.Save(cachedFilename, jpegICI, encoderParams); } //outBmp.Save(cachedFilename); } catch (Exception ex) { CurrentError = ex; OnExceptionCatching(EventArgs.Empty); } } } /// <summary> /// A better alternative to Image.GetThumbnail. Higher quality but slightly slower /// </summary> /// <param name="source"></param> /// <param name="thumbWi"></param> /// <param name="thumbHi"></param> /// <returns></returns> private Bitmap CreateThumbnail(Bitmap source, int thumbWi, int thumbHi, bool maintainAspect) { // return the source image if it's smaller than the designated thumbnail if (source.Width < thumbWi && source.Height < thumbHi) return source; System.Drawing.Bitmap ret = null; try { int wi, hi; wi = thumbWi; hi = thumbHi; if (maintainAspect) { // maintain the aspect ratio despite the thumbnail size parameters if (source.Width > source.Height) { wi = thumbWi; hi = (int)(source.Height * ((decimal)thumbWi / source.Width)); } else { hi = thumbHi; wi = (int)(source.Width * ((decimal)thumbHi / source.Height)); } } ret = new Bitmap(wi, hi); using (Graphics g = Graphics.FromImage(ret)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle(Brushes.White, 0, 0, wi, hi); g.DrawImage(source, 0, 0, wi, hi); } } catch { ret = null; } return ret; } public string GetSourceFilename(string url) { Uri uri = new Uri(url); string shortFilename = uri.Host.Replace(".", "_") + uri.LocalPath.Replace("/", "_") + ".png"; return Path.Combine(WebPreviewConfiguration.SourceImageDirectory, shortFilename); } public string GetCachedFilename(string sourceFilename, int width, int height) { FileInfo sourceFile = new FileInfo(sourceFilename); string shortFilename = sourceFile.Name; string ext = Path.GetExtension(shortFilename); string replacementEnding = String.Format("{0}x{1}-", width, height) + ext; string cachedFilename = shortFilename.Replace(ext, replacementEnding); return Path.Combine(WebPreviewConfiguration.CachingImageDirectory, cachedFilename); } public string GetContentType(string filename) { string contentType = "image/x-unknown"; string ext = Path.GetExtension(filename); switch (ext) { case ".jpg": contentType = "image/jpeg"; break; case ".gif": contentType = "image/gif"; break; case ".png": contentType = "image/png"; break; default: contentType = "image/jpeg"; break; } return contentType; } #endregion #region " Properties " private Exception _currentException = null; public Exception CurrentError { get { return _currentException; } set { _currentException = value; } } #endregion } }
// Copyright (c) Winton. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENCE in the project root for license information. using System; using System.Threading; using System.Threading.Tasks; using System.Transactions; namespace Winton.Extensions.Threading.Actor { /// <summary> /// Factories and extensions for actors. /// </summary> public static class ActorExtensions { /// <summary> /// Specify work for actor start-up. /// </summary> /// <param name="self">Actor</param> /// <param name="work">Work to do.</param> /// <returns>Actor</returns> public static IActor WithStartWork(this IActor self, ActorStartWork work) { self.StartWork = work; return self; } /// <summary> /// Specify work for actor start-up. /// </summary> /// <param name="self">Actor</param> /// <param name="work">Work to do.</param> /// <returns>Actor</returns> public static IActor WithStartWork(this IActor self, Action work) => self.WithStartWork(new ActorStartWork(SuppressTransactionScopeWrapper(work))); /// <summary> /// Specify work for actor start-up. /// </summary> /// <param name="self">Actor</param> /// <param name="work">Async work to do.</param> /// <returns>Actor</returns> public static IActor WithStartWork(this IActor self, Func<Task> work) => self.WithStartWork(new ActorStartWork(SuppressTransactionScopeWrapper(work))); /// <summary> /// Specify work for actor start-up. /// </summary> /// <param name="self">Actor</param> /// <param name="work">Work to do.</param> /// <returns>Actor</returns> public static IActor WithStopWork(this IActor self, ActorStopWork work) { self.StopWork = work; return self; } public static IActor WithStopWork(this IActor self, Action work) => self.WithStopWork(new ActorStopWork(SuppressTransactionScopeWrapper(work))); /// <summary> /// Enqueue a procedure. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <returns>Work completion task.</returns> public static Task Enqueue(this IActor self, Action work) => self.Enqueue(work, CancellationToken.None, ActorEnqueueOptions.Default); /// <summary> /// Enqueue a function. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <returns>Function result task.</returns> public static Task<T> Enqueue<T>(this IActor self, Func<T> work) => self.Enqueue(work, CancellationToken.None, ActorEnqueueOptions.Default); /// <summary> /// Enqueue an async procedure. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <returns>Work completion task.</returns> public static Task Enqueue(this IActor self, Func<Task> work) => self.Enqueue(work, CancellationToken.None, ActorEnqueueOptions.Default); /// <summary> /// Enqueue an async function. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <returns>Function result task.</returns> public static Task<T> Enqueue<T>(this IActor self, Func<Task<T>> work) => self.Enqueue(work, CancellationToken.None, ActorEnqueueOptions.Default); /// <summary> /// Enqueue a procedure with special options. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <param name="options">Enqueue options.</param> /// <returns>Work completion task.</returns> public static Task Enqueue(this IActor self, Action work, ActorEnqueueOptions options) => self.Enqueue(work, CancellationToken.None, options); /// <summary> /// Enqueue a function with special options. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <param name="options">Enqueue options.</param> /// <returns>Function result task.</returns> public static Task<T> Enqueue<T>(this IActor self, Func<T> work, ActorEnqueueOptions options) => self.Enqueue(work, CancellationToken.None, options); /// <summary> /// Enqueue an async procedure with special options. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <param name="options">Enqueue options.</param> /// <returns>Work completion task.</returns> public static Task Enqueue(this IActor self, Func<Task> work, ActorEnqueueOptions options) => self.Enqueue(work, CancellationToken.None, options); /// <summary> /// Enqueue an async function with special options. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <param name="options">Enqueue options.</param> /// <returns>Function result task.</returns> public static Task<T> Enqueue<T>(this IActor self, Func<Task<T>> work, ActorEnqueueOptions options) => self.Enqueue(work, CancellationToken.None, options); /// <summary> /// Enqueue a cancellable procedure. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Work completion task.</returns> public static Task Enqueue(this IActor self, Action work, CancellationToken cancellationToken) => self.Enqueue(work, cancellationToken, ActorEnqueueOptions.Default); /// <summary> /// Enqueue a cancellable function. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Function result task.</returns> public static Task<T> Enqueue<T>(this IActor self, Func<T> work, CancellationToken cancellationToken) => self.Enqueue(work, cancellationToken, ActorEnqueueOptions.Default); /// <summary> /// Enqueue a cancellable async procedure. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Work completion task.</returns> public static Task Enqueue(this IActor self, Func<Task> work, CancellationToken cancellationToken) => self.Enqueue(work, cancellationToken, ActorEnqueueOptions.Default); /// <summary> /// Enqueue a cancellable async function. /// </summary> /// <param name="self">The actor.</param> /// <param name="work">The work.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Function result task.</returns> public static Task<T> Enqueue<T>(this IActor self, Func<Task<T>> work, CancellationToken cancellationToken) => self.Enqueue(work, cancellationToken, ActorEnqueueOptions.Default); /// <summary> /// Returns a <see cref="CancellationToken"/> that is cancelled when the given actor stops. /// </summary> /// <param name="self">The actor.</param> /// <returns></returns> public static CancellationToken StoppedToken(this IActor self) { var cancellationTokenSource = new CancellationTokenSource(); Task.Run( async () => { try { await self.StoppedTask; } catch { } cancellationTokenSource.Cancel(); cancellationTokenSource.Dispose(); }); return cancellationTokenSource.Token; } internal static Func<Task<T>> SuppressTransactionScopeWrapper<T>(Func<Task<T>> function) { return async () => { using (var scope = new TransactionScope( TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) { try { return await function().ConfigureAwait(false); } finally { scope.Complete(); } } }; } internal static Func<Task> SuppressTransactionScopeWrapper(Func<Task> function) { return async () => { using (var scope = new TransactionScope( TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) { try { await function().ConfigureAwait(false); } finally { scope.Complete(); } } }; } internal static Func<T> SuppressTransactionScopeWrapper<T>(Func<T> function) { return () => { using (var scope = new TransactionScope( TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) { try { return function(); } finally { scope.Complete(); } } }; } internal static Action SuppressTransactionScopeWrapper(Action action) { return () => { using (var scope = new TransactionScope( TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) { try { action(); } finally { scope.Complete(); } } }; } } }
using System.Collections; using Fonet.DataTypes; using Fonet.Fo; using Fonet.Fo.Flow; using Fonet.Layout.Inline; namespace Fonet.Layout { internal abstract class Area : Box { protected FontState fontState; protected BorderAndPadding bp = null; protected ArrayList children = new ArrayList(); protected int maxHeight; protected int currentHeight = 0; protected int tableCellXOffset = 0; private int absoluteYTop = 0; protected int contentRectangleWidth; protected int allocationWidth; protected Page page; protected BackgroundProps background; private IDReferences idReferences; protected ArrayList markers; protected FObj generatedBy; protected Hashtable returnedBy; protected string areaClass = null; protected bool _isFirst = false; protected bool _isLast = false; public FObj foCreator; public Area(FontState fontState) { setFontState(fontState); this.markers = new ArrayList(); this.returnedBy = new Hashtable(); } public Area(FontState fontState, int allocationWidth, int maxHeight) { setFontState(fontState); this.allocationWidth = allocationWidth; this.contentRectangleWidth = allocationWidth; this.maxHeight = maxHeight; this.markers = new ArrayList(); this.returnedBy = new Hashtable(); } private void setFontState(FontState fontState) { this.fontState = fontState; } public void addChild(Box child) { this.children.Add(child); child.parent = this; } public void addChildAtStart(Box child) { this.children.Insert(0, child); child.parent = this; } public void addDisplaySpace(int size) { this.addChild(new DisplaySpace(size)); this.currentHeight += size; } public void addInlineSpace(int size) { this.addChild(new InlineSpace(size)); } public FontInfo getFontInfo() { return this.page.getFontInfo(); } public virtual void end() { } public int getAllocationWidth() { return this.allocationWidth; } public void setAllocationWidth(int w) { this.allocationWidth = w; this.contentRectangleWidth = this.allocationWidth; } public ArrayList getChildren() { return this.children; } public bool hasChildren() { return (this.children.Count != 0); } public bool hasNonSpaceChildren() { if (this.children.Count > 0) { foreach (object child in children) { if (!(child is DisplaySpace)) { return true; } } } return false; } public virtual int getContentWidth() { return contentRectangleWidth; } public FontState GetFontState() { return this.fontState; } public virtual int getContentHeight() { return this.currentHeight; } public virtual int GetHeight() { return this.currentHeight + getPaddingTop() + getPaddingBottom() + getBorderTopWidth() + getBorderBottomWidth(); } public int getMaxHeight() { return this.maxHeight; } public Page getPage() { return this.page; } public BackgroundProps getBackground() { return this.background; } public int getPaddingTop() { return (bp == null ? 0 : bp.getPaddingTop(false)); } public int getPaddingLeft() { return (bp == null ? 0 : bp.getPaddingLeft(false)); } public int getPaddingBottom() { return (bp == null ? 0 : bp.getPaddingBottom(false)); } public int getPaddingRight() { return (bp == null ? 0 : bp.getPaddingRight(false)); } public int getBorderTopWidth() { return (bp == null ? 0 : bp.getBorderTopWidth(false)); } public int getBorderRightWidth() { return (bp == null ? 0 : bp.getBorderRightWidth(false)); } public int getBorderLeftWidth() { return (bp == null ? 0 : bp.getBorderLeftWidth(false)); } public int getBorderBottomWidth() { return (bp == null ? 0 : bp.getBorderBottomWidth(false)); } public int getTableCellXOffset() { return tableCellXOffset; } public void setTableCellXOffset(int offset) { tableCellXOffset = offset; } public int getAbsoluteHeight() { return absoluteYTop + getPaddingTop() + getBorderTopWidth() + currentHeight; } public void setAbsoluteHeight(int value) { absoluteYTop = value; } public void increaseHeight(int amount) { this.currentHeight += amount; } public void removeChild(Area area) { this.currentHeight -= area.GetHeight(); this.children.Remove(area); } public void removeChild(DisplaySpace spacer) { this.currentHeight -= spacer.getSize(); this.children.Remove(spacer); } public void remove() { this.parent.removeChild(this); } public virtual void setPage(Page page) { this.page = page; } public void setBackground(BackgroundProps bg) { this.background = bg; } public void setBorderAndPadding(BorderAndPadding bp) { this.bp = bp; } public virtual int spaceLeft() { return maxHeight - currentHeight; } public virtual void start() { } public virtual void SetHeight(int height) { int prevHeight = currentHeight; if (height > currentHeight) { currentHeight = height; } if (currentHeight > getMaxHeight()) { currentHeight = getMaxHeight(); } } public void setMaxHeight(int height) { this.maxHeight = height; } public Area getParent() { return this.parent; } public void setParent(Area parent) { this.parent = parent; } public virtual void setIDReferences(IDReferences idReferences) { this.idReferences = idReferences; } public virtual IDReferences getIDReferences() { return idReferences; } public FObj getfoCreator() { return this.foCreator; } public AreaContainer getNearestAncestorAreaContainer() { // Try to locate the closest parent that can be // casted to AreaContainer Area area = this.getParent(); AreaContainer output = area as AreaContainer; while (area != null && output ==null) { area = area.getParent(); output = area as AreaContainer; } return output; } public BorderAndPadding GetBorderAndPadding() { return bp; } public void addMarker(Marker marker) { markers.Add(marker); } public void addMarkers(ArrayList markers) { foreach (object o in markers) { this.markers.Add(o); } } public void addLineagePair(FObj fo, int areaPosition) { returnedBy.Add(fo, areaPosition); } public ArrayList getMarkers() { return markers; } public void setGeneratedBy(FObj generatedBy) { this.generatedBy = generatedBy; } public FObj getGeneratedBy() { return generatedBy; } public void isFirst(bool isFirst) { _isFirst = isFirst; } public bool isFirst() { return _isFirst; } public void isLast(bool isLast) { _isLast = isLast; } public bool isLast() { return _isLast; } } }
namespace StockSharp.Algo.Storages.Csv { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Ecng.Collections; using Ecng.Common; using Ecng.Serialization; using MoreLinq; using StockSharp.BusinessEntities; using StockSharp.Configuration; using StockSharp.Localization; using StockSharp.Logging; using StockSharp.Messages; /// <summary> /// The CSV storage of trading objects. /// </summary> public class CsvEntityRegistry : IEntityRegistry { /// <summary> /// </summary> [Obsolete("This property exists only for backward compatibility.")] public object Storage => throw new NotSupportedException(); private class ExchangeCsvList : CsvEntityList<string, Exchange> { public ExchangeCsvList(CsvEntityRegistry registry) : base(registry, "exchange.csv") { } protected override string GetKey(Exchange item) { return item.Name; } protected override Exchange Read(FastCsvReader reader) { var board = new Exchange { Name = reader.ReadString(), CountryCode = reader.ReadNullableEnum<CountryCodes>(), //EngName = reader.ReadString(), //RusName = reader.ReadString(), //ExtensionInfo = Deserialize<Dictionary<object, object>>(reader.ReadString()) }; var engName = reader.ReadString(); reader.Skip(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) board.FullNameLoc = reader.ReadString(); else { board.FullNameLoc = LocalizedStrings.LocalizationManager.GetResourceId(engName) ?? engName; } return board; } protected override void Write(CsvFileWriter writer, Exchange data) { writer.WriteRow(new[] { data.Name, data.CountryCode.To<string>(), string.Empty/*data.EngName*/, string.Empty/*data.RusName*/, //Serialize(data.ExtensionInfo), data.FullNameLoc, }); } } private class ExchangeBoardCsvList : CsvEntityList<string, ExchangeBoard> { public ExchangeBoardCsvList(CsvEntityRegistry registry) : base(registry, "exchangeboard.csv") { } protected override string GetKey(ExchangeBoard item) { return item.Code; } private Exchange GetExchange(string exchangeCode) { var exchange = Registry.Exchanges.ReadById(exchangeCode); if (exchange == null) throw new InvalidOperationException(LocalizedStrings.Str1217Params.Put(exchangeCode)); return exchange; } protected override ExchangeBoard Read(FastCsvReader reader) { var board = new ExchangeBoard { Code = reader.ReadString(), Exchange = GetExchange(reader.ReadString()), ExpiryTime = reader.ReadString().ToTime(), //IsSupportAtomicReRegister = reader.ReadBool(), //IsSupportMarketOrders = reader.ReadBool(), TimeZone = reader.ReadString().To<TimeZoneInfo>(), }; var time = board.WorkingTime; if (reader.ColumnCount == 7) { time.Periods = Deserialize<List<WorkingTimePeriod>>(reader.ReadString()); time.SpecialWorkingDays = Deserialize<IEnumerable<DateTime>>(reader.ReadString()).ToArray(); time.SpecialHolidays = Deserialize<IEnumerable<DateTime>>(reader.ReadString()).ToArray(); } else { time.Periods.AddRange(reader.ReadString().DecodeToPeriods()); time.SpecialDays.AddRange(reader.ReadString().DecodeToSpecialDays()); if ((reader.ColumnCurr + 1) < reader.ColumnCount) { reader.Skip(); time.IsEnabled = reader.ReadBool(); } } return board; } protected override void Write(CsvFileWriter writer, ExchangeBoard data) { writer.WriteRow(new[] { data.Code, data.Exchange.Name, data.ExpiryTime.WriteTime(), //data.IsSupportAtomicReRegister.To<string>(), //data.IsSupportMarketOrders.To<string>(), data.TimeZone.Id, //Serialize(data.WorkingTime.Periods), data.WorkingTime.Periods.EncodeToString(), //Serialize(data.WorkingTime.SpecialWorkingDays), //Serialize(data.WorkingTime.SpecialHolidays), data.WorkingTime.SpecialDays.EncodeToString(), string.Empty, data.WorkingTime.IsEnabled.ToString(), }); } private readonly SynchronizedDictionary<Type, ISerializer> _serializers = new(); private TItem Deserialize<TItem>(string value) where TItem : class { if (value.IsEmpty()) return null; var serializer = GetSerializer<TItem>(); var bytes = Registry.Encoding.GetBytes(value.Replace("'", "\"")); return (TItem)serializer.DeserializeWithMigration(bytes); } private ISerializer<TItem> GetSerializer<TItem>() => (ISerializer<TItem>)_serializers.SafeAdd(typeof(TItem), k => new JsonSerializer<TItem> { Indent = false, EnumAsString = true }); } private class SecurityCsvList : CsvEntityList<SecurityId, Security>, IStorageSecurityList { public SecurityCsvList(CsvEntityRegistry registry) : base(registry, "security.csv") { ((ICollectionEx<Security>)this).AddedRange += s => _added?.Invoke(s); ((ICollectionEx<Security>)this).RemovedRange += s => _removed?.Invoke(s); } #region IStorageSecurityList private Action<IEnumerable<Security>> _added; event Action<IEnumerable<Security>> ISecurityProvider.Added { add => _added += value; remove => _added -= value; } private Action<IEnumerable<Security>> _removed; event Action<IEnumerable<Security>> ISecurityProvider.Removed { add => _removed += value; remove => _removed -= value; } private Security GetById(SecurityId id) => ((IStorageSecurityList)this).ReadById(id); Security ISecurityProvider.LookupById(SecurityId id) => GetById(id); IEnumerable<Security> ISecurityProvider.Lookup(SecurityLookupMessage criteria) { var secId = criteria.SecurityId; if (secId == default || secId.BoardCode.IsEmpty()) return this.Filter(criteria); var security = GetById(secId); return security == null ? Enumerable.Empty<Security>() : new[] { security }; } void ISecurityStorage.Delete(Security security) { Remove(security); } void ISecurityStorage.DeleteBy(SecurityLookupMessage criteria) { this.Filter(criteria).ForEach(s => Remove(s)); } void ISecurityStorage.DeleteRange(IEnumerable<Security> securities) { RemoveRange(securities); OnRemovedRange(securities); } #endregion #region CsvEntityList protected override SecurityId GetKey(Security item) => item.ToSecurityId(); private class LiteSecurity { public string Id { get; set; } public string Name { get; set; } public string Code { get; set; } public string Class { get; set; } public string ShortName { get; set; } public string Board { get; set; } public string UnderlyingSecurityId { get; set; } public decimal? PriceStep { get; set; } public decimal? VolumeStep { get; set; } public decimal? MinVolume { get; set; } public decimal? MaxVolume { get; set; } public decimal? Multiplier { get; set; } public int? Decimals { get; set; } public SecurityTypes? Type { get; set; } public DateTimeOffset? ExpiryDate { get; set; } public DateTimeOffset? SettlementDate { get; set; } public decimal? Strike { get; set; } public OptionTypes? OptionType { get; set; } public CurrencyTypes? Currency { get; set; } public SecurityExternalId ExternalId { get; set; } public SecurityTypes? UnderlyingSecurityType { get; set; } public decimal? UnderlyingSecurityMinVolume { get; set; } public string BinaryOptionType { get; set; } public string CfiCode { get; set; } public DateTimeOffset? IssueDate { get; set; } public decimal? IssueSize { get; set; } public bool? Shortable { get; set; } public string BasketCode { get; set; } public string BasketExpression { get; set; } public string PrimaryId { get; set; } public Security ToSecurity(SecurityCsvList list) { if (Id.EqualsIgnoreCase(TraderHelper.AllSecurity.Id)) return TraderHelper.AllSecurity; var board = Board; if (board.IsEmpty()) board = Id.ToSecurityId().BoardCode; return new Security { Id = Id, Name = Name, Code = Code, Class = Class, ShortName = ShortName, Board = list.Registry.GetBoard(board), UnderlyingSecurityId = UnderlyingSecurityId, PriceStep = PriceStep, VolumeStep = VolumeStep, MinVolume = MinVolume, MaxVolume = MaxVolume, Multiplier = Multiplier, Decimals = Decimals, Type = Type, ExpiryDate = ExpiryDate, SettlementDate = SettlementDate, Strike = Strike, OptionType = OptionType, Currency = Currency, ExternalId = ExternalId.Clone(), UnderlyingSecurityType = UnderlyingSecurityType, UnderlyingSecurityMinVolume = UnderlyingSecurityMinVolume, BinaryOptionType = BinaryOptionType, CfiCode = CfiCode, IssueDate = IssueDate, IssueSize = IssueSize, Shortable = Shortable, BasketCode = BasketCode, BasketExpression = BasketExpression, PrimaryId = PrimaryId }; } public void Update(Security security) { Name = security.Name; Code = security.Code; Class = security.Class; ShortName = security.ShortName; Board = security.Board?.Code; UnderlyingSecurityId = security.UnderlyingSecurityId; PriceStep = security.PriceStep; VolumeStep = security.VolumeStep; MinVolume = security.MinVolume; MaxVolume = security.MaxVolume; Multiplier = security.Multiplier; Decimals = security.Decimals; Type = security.Type; ExpiryDate = security.ExpiryDate; SettlementDate = security.SettlementDate; Strike = security.Strike; OptionType = security.OptionType; Currency = security.Currency; ExternalId = security.ExternalId.Clone(); UnderlyingSecurityType = security.UnderlyingSecurityType; UnderlyingSecurityMinVolume = security.UnderlyingSecurityMinVolume; BinaryOptionType = security.BinaryOptionType; CfiCode = security.CfiCode; IssueDate = security.IssueDate; IssueSize = security.IssueSize; Shortable = security.Shortable; BasketCode = security.BasketCode; BasketExpression = security.BasketExpression; PrimaryId = security.PrimaryId; } } private readonly Dictionary<SecurityId, LiteSecurity> _cache = new(); private static bool IsChanged(string original, string cached, bool forced) { if (original.IsEmpty()) return forced && !cached.IsEmpty(); else return cached.IsEmpty() || (forced && !cached.EqualsIgnoreCase(original)); } private static bool IsChanged<T>(T? original, T? cached, bool forced) where T : struct { if (original == null) return forced && cached != null; else return cached == null || (forced && !original.Value.Equals(cached.Value)); } protected override bool IsChanged(Security security, bool forced) { var liteSec = _cache.TryGetValue(security.ToSecurityId()); if (liteSec == null) throw new ArgumentOutOfRangeException(nameof(security), security.Id, LocalizedStrings.Str2736); if (IsChanged(security.Name, liteSec.Name, forced)) return true; if (IsChanged(security.Code, liteSec.Code, forced)) return true; if (IsChanged(security.Class, liteSec.Class, forced)) return true; if (IsChanged(security.ShortName, liteSec.ShortName, forced)) return true; if (IsChanged(security.UnderlyingSecurityId, liteSec.UnderlyingSecurityId, forced)) return true; if (IsChanged(security.UnderlyingSecurityType, liteSec.UnderlyingSecurityType, forced)) return true; if (IsChanged(security.UnderlyingSecurityMinVolume, liteSec.UnderlyingSecurityMinVolume, forced)) return true; if (IsChanged(security.PriceStep, liteSec.PriceStep, forced)) return true; if (IsChanged(security.VolumeStep, liteSec.VolumeStep, forced)) return true; if (IsChanged(security.MinVolume, liteSec.MinVolume, forced)) return true; if (IsChanged(security.MaxVolume, liteSec.MaxVolume, forced)) return true; if (IsChanged(security.Multiplier, liteSec.Multiplier, forced)) return true; if (IsChanged(security.Decimals, liteSec.Decimals, forced)) return true; if (IsChanged(security.Type, liteSec.Type, forced)) return true; if (IsChanged(security.ExpiryDate, liteSec.ExpiryDate, forced)) return true; if (IsChanged(security.SettlementDate, liteSec.SettlementDate, forced)) return true; if (IsChanged(security.Strike, liteSec.Strike, forced)) return true; if (IsChanged(security.OptionType, liteSec.OptionType, forced)) return true; if (IsChanged(security.Currency, liteSec.Currency, forced)) return true; if (IsChanged(security.BinaryOptionType, liteSec.BinaryOptionType, forced)) return true; if (IsChanged(security.CfiCode, liteSec.CfiCode, forced)) return true; if (IsChanged(security.Shortable, liteSec.Shortable, forced)) return true; if (IsChanged(security.IssueDate, liteSec.IssueDate, forced)) return true; if (IsChanged(security.IssueSize, liteSec.IssueSize, forced)) return true; if (security.Board == null) { if (!liteSec.Board.IsEmpty() && forced) return true; } else { if (liteSec.Board.IsEmpty() || (forced && !liteSec.Board.EqualsIgnoreCase(security.Board?.Code))) return true; } if (forced && security.ExternalId != liteSec.ExternalId) return true; if (IsChanged(security.BasketCode, liteSec.BasketCode, forced)) return true; if (IsChanged(security.BasketExpression, liteSec.BasketExpression, forced)) return true; if (IsChanged(security.PrimaryId, liteSec.PrimaryId, forced)) return true; return false; } protected override void ClearCache() { _cache.Clear(); } protected override void AddCache(Security item) { var sec = new LiteSecurity { Id = item.Id }; sec.Update(item); _cache.Add(item.ToSecurityId(), sec); } protected override void RemoveCache(Security item) { _cache.Remove(item.ToSecurityId()); } protected override void UpdateCache(Security item) { _cache[item.ToSecurityId()].Update(item); } //protected override void WriteMany(Security[] values) //{ // base.WriteMany(_cache.Values.Select(l => l.ToSecurity(this)).ToArray()); //} protected override Security Read(FastCsvReader reader) { var liteSec = new LiteSecurity { Id = reader.ReadString(), Name = reader.ReadString(), Code = reader.ReadString(), Class = reader.ReadString(), ShortName = reader.ReadString(), Board = reader.ReadString(), UnderlyingSecurityId = reader.ReadString(), PriceStep = reader.ReadNullableDecimal(), VolumeStep = reader.ReadNullableDecimal(), Multiplier = reader.ReadNullableDecimal(), Decimals = reader.ReadNullableInt(), Type = reader.ReadNullableEnum<SecurityTypes>(), ExpiryDate = ReadNullableDateTime(reader), SettlementDate = ReadNullableDateTime(reader), Strike = reader.ReadNullableDecimal(), OptionType = reader.ReadNullableEnum<OptionTypes>(), Currency = reader.ReadNullableEnum<CurrencyTypes>(), ExternalId = new SecurityExternalId { Sedol = reader.ReadString(), Cusip = reader.ReadString(), Isin = reader.ReadString(), Ric = reader.ReadString(), Bloomberg = reader.ReadString(), IQFeed = reader.ReadString(), InteractiveBrokers = reader.ReadNullableInt(), Plaza = reader.ReadString() }, }; if ((reader.ColumnCurr + 1) < reader.ColumnCount) { liteSec.UnderlyingSecurityType = reader.ReadNullableEnum<SecurityTypes>(); liteSec.BinaryOptionType = reader.ReadString(); liteSec.CfiCode = reader.ReadString(); liteSec.IssueDate = ReadNullableDateTime(reader); liteSec.IssueSize = reader.ReadNullableDecimal(); } if ((reader.ColumnCurr + 1) < reader.ColumnCount) liteSec.BasketCode = reader.ReadString(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) liteSec.BasketExpression = reader.ReadString(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) { liteSec.MinVolume = reader.ReadNullableDecimal(); liteSec.Shortable = reader.ReadNullableBool(); } if ((reader.ColumnCurr + 1) < reader.ColumnCount) liteSec.UnderlyingSecurityMinVolume = reader.ReadNullableDecimal(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) liteSec.MaxVolume = reader.ReadNullableDecimal(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) liteSec.PrimaryId = reader.ReadString(); return liteSec.ToSecurity(this); } protected override void Write(CsvFileWriter writer, Security data) { writer.WriteRow(new[] { data.Id, data.Name, data.Code, data.Class, data.ShortName, data.Board?.Code, data.UnderlyingSecurityId, data.PriceStep.To<string>(), data.VolumeStep.To<string>(), data.Multiplier.To<string>(), data.Decimals.To<string>(), data.Type.To<string>(), data.ExpiryDate?.UtcDateTime.ToString(_dateTimeFormat), data.SettlementDate?.UtcDateTime.ToString(_dateTimeFormat), data.Strike.To<string>(), data.OptionType.To<string>(), data.Currency.To<string>(), data.ExternalId.Sedol, data.ExternalId.Cusip, data.ExternalId.Isin, data.ExternalId.Ric, data.ExternalId.Bloomberg, data.ExternalId.IQFeed, data.ExternalId.InteractiveBrokers.To<string>(), data.ExternalId.Plaza, data.UnderlyingSecurityType.To<string>(), data.BinaryOptionType, data.CfiCode, data.IssueDate?.UtcDateTime.ToString(_dateTimeFormat), data.IssueSize.To<string>(), data.BasketCode, data.BasketExpression, data.MinVolume.To<string>(), data.Shortable.To<string>(), data.UnderlyingSecurityMinVolume.To<string>(), data.MaxVolume.To<string>(), data.PrimaryId, }); } public override void Save(Security entity, bool forced) { lock (Registry.Exchanges.SyncRoot) Registry.Exchanges.TryAdd(entity.Board.Exchange); lock (Registry.ExchangeBoards.SyncRoot) Registry.ExchangeBoards.TryAdd(entity.Board); base.Save(entity, forced); } #endregion } private class PortfolioCsvList : CsvEntityList<string, Portfolio> { public PortfolioCsvList(CsvEntityRegistry registry) : base(registry, "portfolio.csv") { } protected override string GetKey(Portfolio item) { return item.Name; } protected override Portfolio Read(FastCsvReader reader) { var portfolio = new Portfolio { Name = reader.ReadString(), Board = GetBoard(reader.ReadString()), Leverage = reader.ReadNullableDecimal(), BeginValue = reader.ReadNullableDecimal(), CurrentValue = reader.ReadNullableDecimal(), BlockedValue = reader.ReadNullableDecimal(), VariationMargin = reader.ReadNullableDecimal(), Commission = reader.ReadNullableDecimal(), Currency = reader.ReadNullableEnum<CurrencyTypes>(), State = reader.ReadNullableEnum<PortfolioStates>(), Description = reader.ReadString(), LastChangeTime = _dateTimeParser.Parse(reader.ReadString()).UtcKind(), LocalTime = _dateTimeParser.Parse(reader.ReadString()).UtcKind() }; if ((reader.ColumnCurr + 1) < reader.ColumnCount) portfolio.ClientCode = reader.ReadString(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) { portfolio.Currency = reader.ReadString().To<CurrencyTypes?>(); var str = reader.ReadString(); portfolio.ExpirationDate = str.IsEmpty() ? null : _dateTimeParser.Parse(str).UtcKind(); } if ((reader.ColumnCurr + 1) < reader.ColumnCount) { portfolio.CommissionMaker = reader.ReadNullableDecimal(); portfolio.CommissionTaker = reader.ReadNullableDecimal(); } if ((reader.ColumnCurr + 1) < reader.ColumnCount) /*portfolio.InternalId = */reader.ReadString().To<Guid?>(); return portfolio; } private ExchangeBoard GetBoard(string boardCode) { return boardCode.IsEmpty() ? null : Registry.GetBoard(boardCode); } protected override void Write(CsvFileWriter writer, Portfolio data) { writer.WriteRow(new[] { data.Name, data.Board?.Code, data.Leverage.To<string>(), data.BeginValue.To<string>(), data.CurrentValue.To<string>(), data.BlockedValue.To<string>(), data.VariationMargin.To<string>(), data.Commission.To<string>(), data.Currency.To<string>(), data.State.To<string>(), data.Description, data.LastChangeTime.UtcDateTime.ToString(_dateTimeFormat), data.LocalTime.UtcDateTime.ToString(_dateTimeFormat), data.ClientCode, data.Currency?.To<string>(), data.ExpirationDate?.UtcDateTime.ToString(_dateTimeFormat), data.CommissionMaker.To<string>(), data.CommissionTaker.To<string>(), /*data.InternalId.To<string>()*/string.Empty, }); } } private class PositionCsvList : CsvEntityList<Tuple<Portfolio, Security, string, Sides?>, Position>, IStoragePositionList { public PositionCsvList(CsvEntityRegistry registry) : base(registry, "position.csv") { } protected override Tuple<Portfolio, Security, string, Sides?> GetKey(Position item) => CreateKey(item.Portfolio, item.Security, item.StrategyId, item.Side); private Portfolio GetPortfolio(string id) { var portfolio = Registry.Portfolios.ReadById(id); if (portfolio == null) throw new InvalidOperationException(LocalizedStrings.Str3622Params.Put(id)); return portfolio; } private Security GetSecurity(string id) { var secId = id.ToSecurityId(); var security = secId.IsMoney() ? TraderHelper.MoneySecurity : Registry.Securities.ReadById(secId); if (security == null) throw new InvalidOperationException(LocalizedStrings.Str704Params.Put(id)); return security; } protected override Position Read(FastCsvReader reader) { var pfName = reader.ReadString(); var secId = reader.ReadString(); var position = new Position { Portfolio = GetPortfolio(pfName), Security = GetSecurity(secId), DepoName = reader.ReadString(), LimitType = reader.ReadNullableEnum<TPlusLimits>(), BeginValue = reader.ReadNullableDecimal(), CurrentValue = reader.ReadNullableDecimal(), BlockedValue = reader.ReadNullableDecimal(), VariationMargin = reader.ReadNullableDecimal(), Commission = reader.ReadNullableDecimal(), Currency = reader.ReadNullableEnum<CurrencyTypes>(), LastChangeTime = _dateTimeParser.Parse(reader.ReadString()).UtcKind(), LocalTime = _dateTimeParser.Parse(reader.ReadString()).UtcKind(), }; if ((reader.ColumnCurr + 1) < reader.ColumnCount) position.ClientCode = reader.ReadString(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) { position.Currency = reader.ReadString().To<CurrencyTypes?>(); var str = reader.ReadString(); position.ExpirationDate = str.IsEmpty() ? null : _dateTimeParser.Parse(str).UtcKind(); } if ((reader.ColumnCurr + 1) < reader.ColumnCount) { position.Leverage = reader.ReadNullableDecimal(); position.CommissionMaker = reader.ReadNullableDecimal(); position.CommissionTaker = reader.ReadNullableDecimal(); position.AveragePrice = reader.ReadNullableDecimal(); position.RealizedPnL = reader.ReadNullableDecimal(); position.UnrealizedPnL = reader.ReadNullableDecimal(); position.CurrentPrice = reader.ReadNullableDecimal(); position.SettlementPrice = reader.ReadNullableDecimal(); } if ((reader.ColumnCurr + 1) < reader.ColumnCount) { position.BuyOrdersCount = reader.ReadNullableInt(); position.SellOrdersCount = reader.ReadNullableInt(); position.BuyOrdersMargin = reader.ReadNullableDecimal(); position.SellOrdersMargin = reader.ReadNullableDecimal(); position.OrdersMargin = reader.ReadNullableDecimal(); position.OrdersCount = reader.ReadNullableInt(); position.TradesCount = reader.ReadNullableInt(); } if ((reader.ColumnCurr + 1) < reader.ColumnCount) position.StrategyId = reader.ReadString(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) position.Side = reader.ReadNullableEnum<Sides>(); return position; } protected override void Write(CsvFileWriter writer, Position data) { writer.WriteRow(new[] { data.Portfolio.Name, data.Security.Id, data.DepoName, data.LimitType.To<string>(), data.BeginValue.To<string>(), data.CurrentValue.To<string>(), data.BlockedValue.To<string>(), data.VariationMargin.To<string>(), data.Commission.To<string>(), data.Description, data.LastChangeTime.UtcDateTime.ToString(_dateTimeFormat), data.LocalTime.UtcDateTime.ToString(_dateTimeFormat), data.ClientCode, data.Currency.To<string>(), data.ExpirationDate?.UtcDateTime.ToString(_dateTimeFormat), data.Leverage.To<string>(), data.CommissionMaker.To<string>(), data.CommissionTaker.To<string>(), data.AveragePrice.To<string>(), data.RealizedPnL.To<string>(), data.UnrealizedPnL.To<string>(), data.CurrentPrice.To<string>(), data.SettlementPrice.To<string>(), data.BuyOrdersCount.To<string>(), data.SellOrdersCount.To<string>(), data.BuyOrdersMargin.To<string>(), data.SellOrdersMargin.To<string>(), data.OrdersMargin.To<string>(), data.OrdersCount.To<string>(), data.TradesCount.To<string>(), data.StrategyId, data.Side.To<string>(), }); } public Position GetPosition(Portfolio portfolio, Security security, string strategyId, Sides? side, string clientCode = "", string depoName = "", TPlusLimits? limit = null) => ((IStorageEntityList<Position>)this).ReadById(CreateKey(portfolio, security, strategyId, side)); private Tuple<Portfolio, Security, string, Sides?> CreateKey(Portfolio portfolio, Security security, string strategyId, Sides? side) => Tuple.Create(portfolio, security, strategyId?.ToLowerInvariant() ?? string.Empty, side); } private class SubscriptionCsvList : CsvEntityList<Tuple<SecurityId, DataType>, MarketDataMessage> { public SubscriptionCsvList(CsvEntityRegistry registry) : base(registry, "subscription.csv") { } protected override Tuple<SecurityId, DataType> GetKey(MarketDataMessage item) => Tuple.Create(item.SecurityId, item.DataType2); protected override void Write(CsvFileWriter writer, MarketDataMessage data) { if (data == null) throw new ArgumentNullException(nameof(data)); if (!data.IsSubscribe) throw new ArgumentException(nameof(data)); var (type, arg) = data.DataType2.FormatToString(); var buildFromTuples = data.BuildFrom?.FormatToString(); writer.WriteRow(new[] { string.Empty,//data.TransactionId.To<string>(), data.SecurityId.SecurityCode, data.SecurityId.BoardCode, type, arg, data.IsCalcVolumeProfile.To<string>(), data.AllowBuildFromSmallerTimeFrame.To<string>(), data.IsRegularTradingHours.To<string>(), data.MaxDepth.To<string>(), data.NewsId, data.From?.UtcDateTime.ToString(_dateTimeFormat), data.To?.UtcDateTime.ToString(_dateTimeFormat), data.Count.To<string>(), data.BuildMode.To<string>(), null, data.BuildField.To<string>(), data.IsFinishedOnly.To<string>(), data.FillGaps.To<string>(), buildFromTuples?.type, buildFromTuples?.arg, data.Skip.To<string>(), data.DoNotBuildOrderBookInrement.To<string>(), }); } protected override MarketDataMessage Read(FastCsvReader reader) { reader.Skip(); var message = new MarketDataMessage { //TransactionId = reader.ReadLong(), SecurityId = new SecurityId { SecurityCode = reader.ReadString(), BoardCode = reader.ReadString(), }, IsSubscribe = true, DataType2 = reader.ReadString().ToDataType(reader.ReadString()), IsCalcVolumeProfile = reader.ReadBool(), AllowBuildFromSmallerTimeFrame = reader.ReadBool(), IsRegularTradingHours = reader.ReadBool(), MaxDepth = reader.ReadNullableInt(), NewsId = reader.ReadString(), }; var str = reader.ReadString(); message.From = str.IsEmpty() ? null : _dateTimeParser.Parse(str).UtcKind(); str = reader.ReadString(); message.To = str.IsEmpty() ? null : _dateTimeParser.Parse(str).UtcKind(); message.Count = reader.ReadNullableLong(); message.BuildMode = reader.ReadEnum<MarketDataBuildModes>(); reader.ReadString(); message.BuildField = reader.ReadNullableEnum<Level1Fields>(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) message.IsFinishedOnly = reader.ReadBool(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) message.FillGaps = reader.ReadBool(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) { var typeStr = reader.ReadString(); var argStr = reader.ReadString(); message.BuildFrom = typeStr.IsEmpty() ? null : typeStr.ToDataType(argStr); } if ((reader.ColumnCurr + 1) < reader.ColumnCount) message.Skip = reader.ReadNullableLong(); if ((reader.ColumnCurr + 1) < reader.ColumnCount) message.DoNotBuildOrderBookInrement = reader.ReadBool(); return message; } } private const string _dateTimeFormat = "yyyyMMddHHmmss"; private static readonly FastDateTimeParser _dateTimeParser = new(_dateTimeFormat); private static DateTimeOffset? ReadNullableDateTime(FastCsvReader reader) { var str = reader.ReadString(); if (str == null) return null; return _dateTimeParser.Parse(str).UtcKind(); } private readonly List<ICsvEntityList> _csvLists = new(); /// <summary> /// The path to data directory. /// </summary> public string Path { get; set; } private Encoding _encoding = Encoding.UTF8; /// <summary> /// Encoding. /// </summary> public Encoding Encoding { get => _encoding; set => _encoding = value ?? throw new ArgumentNullException(nameof(value)); } private DelayAction _delayAction = new(ex => ex.LogError()); /// <inheritdoc /> public virtual DelayAction DelayAction { get => _delayAction; set { _delayAction = value ?? throw new ArgumentNullException(nameof(value)); UpdateDelayAction(); } } private void UpdateDelayAction() { foreach (var csvList in _csvLists) { csvList.DelayAction = _delayAction; } } private readonly ExchangeCsvList _exchanges; /// <inheritdoc /> public IStorageEntityList<Exchange> Exchanges => _exchanges; private readonly ExchangeBoardCsvList _exchangeBoards; /// <inheritdoc /> public IStorageEntityList<ExchangeBoard> ExchangeBoards => _exchangeBoards; private readonly SecurityCsvList _securities; /// <inheritdoc /> public IStorageSecurityList Securities => _securities; private readonly PortfolioCsvList _portfolios; /// <inheritdoc /> public IStorageEntityList<Portfolio> Portfolios => _portfolios; private readonly PositionCsvList _positions; /// <inheritdoc /> public IStoragePositionList Positions => _positions; /// <inheritdoc /> public IPositionStorage PositionStorage { get; } private readonly SubscriptionCsvList _subscriptions; /// <inheritdoc /> public IStorageEntityList<MarketDataMessage> Subscriptions => _subscriptions; /// <summary> /// Initializes a new instance of the <see cref="CsvEntityRegistry"/>. /// </summary> /// <param name="path">The path to data directory.</param> public CsvEntityRegistry(string path) { Path = path ?? throw new ArgumentNullException(nameof(path)); Add(_exchanges = new ExchangeCsvList(this)); Add(_exchangeBoards = new ExchangeBoardCsvList(this)); Add(_securities = new SecurityCsvList(this)); Add(_portfolios = new PortfolioCsvList(this)); Add(_positions = new PositionCsvList(this)); Add(_subscriptions = new SubscriptionCsvList(this)); UpdateDelayAction(); PositionStorage = new PositionStorage(this); } /// <summary> /// Add list of trade objects. /// </summary> /// <typeparam name="TKey">Key type.</typeparam> /// <typeparam name="TEntity">Entity type.</typeparam> /// <param name="list">List of trade objects.</param> public void Add<TKey, TEntity>(CsvEntityList<TKey, TEntity> list) where TEntity : class { if (list == null) throw new ArgumentNullException(nameof(list)); _csvLists.Add(list); } /// <inheritdoc /> public IDictionary<object, Exception> Init() { Directory.CreateDirectory(Path); var errors = new Dictionary<object, Exception>(); foreach (var list in _csvLists) { try { var listErrors = new List<Exception>(); list.Init(listErrors); if (listErrors.Count > 0) errors.Add(list, listErrors.SingleOrAggr()); } catch (Exception ex) { errors.Add(list, ex); } } return errors; } internal ExchangeBoard GetBoard(string boardCode) { var board = ExchangeBoards.ReadById(boardCode); if (board != null) return board; board = ServicesRegistry.EnsureGetExchangeInfoProvider().GetExchangeBoard(boardCode); if (board == null) throw new InvalidOperationException(LocalizedStrings.Str1217Params.Put(boardCode)); return board; } } }
// 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.Collections.Generic; using Xunit; using SortedList_SortedListUtils; namespace SortedListRemove { public class Driver<K, V> where K : IComparableValue { private Test m_test; public Driver(Test test) { m_test = test; } public void BasicRemove(K[] keys, V[] values) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); for (int i = 0; i < keys.Length; i++) { m_test.Eval(tbl.Remove(keys[i])); } m_test.Eval(tbl.Count == 0); } public void RemoveNegative(K[] keys, V[] values, K[] missingkeys) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); for (int i = 0; i < missingkeys.Length; i++) { m_test.Eval(false == tbl.Remove(missingkeys[i])); } m_test.Eval(tbl.Count == keys.Length); } public void RemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); m_test.Eval(tbl.Remove(keys[index])); for (int i = 0; i < repeat; i++) { m_test.Eval(false == tbl.Remove(keys[index])); } m_test.Eval(tbl.Count == keys.Length - 1); } public void AddRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); m_test.Eval(tbl.Remove(keys[index])); for (int i = 0; i < repeat; i++) { tbl.Add(keys[index], values[index]); m_test.Eval(tbl.Remove(keys[index])); } m_test.Eval(tbl.Count == keys.Length - 1); } public void RemoveValidationsRefType(K[] keys, V[] values) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } // //try null key // try { tbl.Remove((K)(object)null); m_test.Eval(false, "Excepted ArgumentException but did not get an Exception when trying to remove null."); } catch (ArgumentException) { m_test.Eval(true); } catch (Exception E) { m_test.Eval(false, "Excepted ArgumentException but got unknown Exception when trying to remove null: " + E); } } public void NonGenericIDictionaryBasicRemove(K[] keys, V[] values) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); for (int i = 0; i < keys.Length; i++) { _idic.Remove(keys[i]); m_test.Eval(!_idic.Contains(keys[i]), "Expected " + keys[i] + " to not still exist, but Contains returned true."); } m_test.Eval(tbl.Count == 0); } public void NonGenericIDictionaryRemoveNegative(K[] keys, V[] values, K[] missingkeys) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); for (int i = 0; i < missingkeys.Length; i++) { _idic.Remove(missingkeys[i]); m_test.Eval(!_idic.Contains(missingkeys[i]), "Expected " + missingkeys[i] + " to not still exist, but Contains returned true."); } m_test.Eval(tbl.Count == keys.Length); } public void NonGenericIDictionaryRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); _idic.Remove(keys[index]); m_test.Eval(!_idic.Contains(keys[index]), "Expected " + keys[index] + " to not still exist, but Contains returned true."); for (int i = 0; i < repeat; i++) { _idic.Remove(keys[index]); m_test.Eval(!_idic.Contains(keys[index]), "Expected " + keys[index] + " to not still exist, but Contains returned true."); } m_test.Eval(tbl.Count == keys.Length - 1); } public void NonGenericIDictionaryAddRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); _idic.Remove(keys[index]); m_test.Eval(!_idic.Contains(keys[index]), "Expected " + keys[index] + " to not still exist, but Contains returned true."); for (int i = 0; i < repeat; i++) { tbl.Add(keys[index], values[index]); _idic.Remove(keys[index]); m_test.Eval(!_idic.Contains(keys[index]), "Expected " + keys[index] + " to not still exist, but Contains returned true."); } m_test.Eval(tbl.Count == keys.Length - 1); } public void NonGenericIDictionaryRemoveValidations(K[] keys, V[] values) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } // //try null key // try { _idic.Remove(null); m_test.Eval(false, "Excepted ArgumentException but did not get an Exception when trying to remove null."); } catch (ArgumentNullException) { m_test.Eval(true); } catch (Exception E) { m_test.Eval(false, "Excepted ArgumentException but got unknown Exception when trying to remove null: " + E); } try { _idic.Remove(new Random(-55)); } catch (Exception E) { m_test.Eval(false, "Excepted ArgumentException but got unknown Exception when trying to remove null: " + E); } } } public class Remove { [Fact] public static void RemoveMain() { Test test = new Test(); Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(test); RefX1<int>[] intArr1 = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr1[i] = new RefX1<int>(i); } RefX1<int>[] intArr2 = new RefX1<int>[10]; for (int i = 0; i < 10; i++) { intArr2[i] = new RefX1<int>(i + 100); } Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(test); ValX1<string>[] stringArr1 = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr1[i] = new ValX1<string>("SomeTestString" + i.ToString()); } ValX1<string>[] stringArr2 = new ValX1<string>[10]; for (int i = 0; i < 10; i++) { stringArr2[i] = new ValX1<string>("SomeTestString" + (i + 100).ToString()); } //Ref<val>,Val<Ref> IntDriver.BasicRemove(intArr1, stringArr1); IntDriver.RemoveNegative(intArr1, stringArr1, intArr2); IntDriver.RemoveNegative(new RefX1<int>[] { }, new ValX1<string>[] { }, intArr2); IntDriver.RemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.RemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.RemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.RemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.RemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.RemoveValidationsRefType(intArr1, stringArr1); IntDriver.RemoveValidationsRefType(new RefX1<int>[] { }, new ValX1<string>[] { }); IntDriver.NonGenericIDictionaryBasicRemove(intArr1, stringArr1); IntDriver.NonGenericIDictionaryRemoveNegative(intArr1, stringArr1, intArr2); IntDriver.NonGenericIDictionaryRemoveNegative(new RefX1<int>[] { }, new ValX1<string>[] { }, intArr2); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.NonGenericIDictionaryRemoveValidations(intArr1, stringArr1); IntDriver.NonGenericIDictionaryRemoveValidations(new RefX1<int>[] { }, new ValX1<string>[] { }); //Val<Ref>,Ref<Val> StringDriver.BasicRemove(stringArr1, intArr1); StringDriver.RemoveNegative(stringArr1, intArr1, stringArr2); StringDriver.RemoveNegative(new ValX1<string>[] { }, new RefX1<int>[] { }, stringArr2); StringDriver.RemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.RemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.RemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.RemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.RemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.NonGenericIDictionaryBasicRemove(stringArr1, intArr1); StringDriver.NonGenericIDictionaryRemoveNegative(stringArr1, intArr1, stringArr2); StringDriver.NonGenericIDictionaryRemoveNegative(new ValX1<string>[] { }, new RefX1<int>[] { }, stringArr2); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.NonGenericIDictionaryRemoveValidations(stringArr1, intArr1); StringDriver.NonGenericIDictionaryRemoveValidations(new ValX1<string>[] { }, new RefX1<int>[] { }); Assert.True(test.result); } } }
// 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.Runtime.CompilerServices; using System.Text; using System.IO; using System.Collections; using System.Globalization; using Xunit; public class DirectoryInfo_Move_str { public static String s_strActiveBugNums = "34383"; public static String s_strClassMethod = "Directory.Move(String)"; public static String s_strTFName = "Move_str.cs"; public static String s_strTFPath = Directory.GetCurrentDirectory(); [Fact] public static void runTest() { int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; String strValue = String.Empty; try { ///////////////////////// START TESTS //////////////////////////// /////////////////////////////////////////////////////////////////// FileInfo fil2 = null; DirectoryInfo dir2 = null; // [] Pass in null argument strLoc = "Loc_099u8"; string testDir = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName()); dir2 = Directory.CreateDirectory(testDir); iCountTestcases++; try { dir2.MoveTo(null); iCountErrors++; printerr("Error_298dy! Expected exception not thrown"); } catch (ArgumentNullException) { } catch (Exception exc) { iCountErrors++; printerr("Error_209xj! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); // [] Pass in empty String should throw ArgumentException strLoc = "Loc_098gt"; dir2 = Directory.CreateDirectory(testDir); iCountTestcases++; try { dir2.MoveTo(String.Empty); iCountErrors++; printerr("Error_3987c! Expected exception not thrown"); } catch (ArgumentException) { } catch (Exception exc) { iCountErrors++; printerr("Error_9092c! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); // [] Vanilla move to new name strLoc = "Loc_98hvc"; dir2 = Directory.CreateDirectory(testDir); iCountTestcases++; dir2.MoveTo(Path.Combine(TestInfo.CurrentDirectory, "Test3")); try { dir2 = new DirectoryInfo(Path.Combine(TestInfo.CurrentDirectory, "Test3")); } catch (Exception exc) { iCountErrors++; printerr("Error_2881s! Directory not moved, exc==" + exc.ToString()); } dir2.Delete(true); // [] Try to move it on top of current dir strLoc = "Loc_2908x"; dir2 = Directory.CreateDirectory(testDir); iCountTestcases++; try { dir2.MoveTo(Path.Combine(TestInfo.CurrentDirectory, ".")); iCountErrors++; printerr("Error_2091z! Expected exception not thrown,"); } catch (IOException) { } catch (Exception exc) { iCountErrors++; printerr("Error_2100s! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); // [] Try to move it on top of parent dir strLoc = "Loc_1999s"; dir2 = Directory.CreateDirectory(testDir); iCountTestcases++; try { dir2.MoveTo(Path.Combine(TestInfo.CurrentDirectory, "..")); iCountErrors++; printerr("Error_2091b! Expected exception not thrown"); } catch (IOException) { } catch (Exception exc) { iCountErrors++; printerr("Error_01990! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); // [] Pass in string with spaces should throw ArgumentException strLoc = "Loc_498vy"; if (Interop.IsWindows) // whitespace-only names are valid on Unix { dir2 = Directory.CreateDirectory(testDir); iCountTestcases++; try { dir2.MoveTo(" "); iCountErrors++; printerr("Error_209uc! Expected exception not thrown"); fil2.Delete(); } catch (ArgumentException) { } catch (Exception exc) { iCountErrors++; printerr("Error_28829! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); } // [] Mvoe to the same directory strLoc = "Loc_498vy"; dir2 = Directory.CreateDirectory(testDir); iCountTestcases++; try { dir2.MoveTo(testDir); iCountErrors++; printerr("Error_209uc! Expected exception not thrown"); fil2.Delete(); } catch (IOException) { } catch (Exception exc) { iCountErrors++; printerr("Error_28829! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); #if !TEST_WINRT // Can't access other root drives // [] Move to different drive will throw AccessException //----------------------------------------------------------------- if (Interop.IsWindows) // drive labels { strLoc = "Loc_00025"; dir2 = Directory.CreateDirectory(testDir); iCountTestcases++; try { if (dir2.FullName.Substring(0, 3) == @"d:\" || dir2.FullName.Substring(0, 3) == @"D:\") dir2.MoveTo("C:\\TempDirectory"); else dir2.MoveTo("D:\\TempDirectory"); Console.WriteLine("Root directory..." + dir2.FullName.Substring(0, 3)); iCountErrors++; printerr("Error_00078! Expected exception not thrown"); } catch (IOException) { } catch (Exception exc) { iCountErrors++; printerr("Error_23r0g! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); } #endif // [] Move non-existent directory dir2 = new DirectoryInfo(testDir); try { dir2.MoveTo(Path.Combine(TestInfo.CurrentDirectory, "Test5526")); iCountErrors++; Console.WriteLine("Err_34gs! Exception not thrown"); } catch (DirectoryNotFoundException) { } catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_34gs! Wrong Exception thrown: {0}", ex); } // [] Pass in string with tabs strLoc = "Loc_98399"; if (Interop.IsWindows) // directory with tabs as name is valid on Unix { dir2 = Directory.CreateDirectory(testDir); iCountTestcases++; try { dir2.MoveTo("\t"); iCountErrors++; printerr("Error_2091c! Expected exception not thrown"); } catch (ArgumentException) { } catch (Exception exc) { iCountErrors++; printerr("Error_8374v! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); } // [] Create a long filename directory strLoc = "Loc_2908y"; StringBuilder sb = new StringBuilder(TestInfo.CurrentDirectory); while (sb.Length < IOInputs.MaxPath + 1) sb.Append("a"); iCountTestcases++; dir2 = Directory.CreateDirectory(testDir); try { dir2.MoveTo(sb.ToString()); iCountErrors++; printerr("Error_109ty! Expected exception not thrown"); } catch (PathTooLongException) { // This should really be PathTooLongException } catch (Exception exc) { iCountErrors++; printerr("Error_109dv! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); // [] Too long filename strLoc = "Loc_48fyf"; sb = new StringBuilder(); for (int i = 0; i < IOInputs.MaxPath + 1; i++) sb.Append("a"); iCountTestcases++; dir2 = Directory.CreateDirectory(testDir); try { dir2.MoveTo(sb.ToString()); iCountErrors++; printerr("Error_109ty! Expected exception not thrown"); } catch (PathTooLongException) { // This should really be PathTooLongException } catch (Exception exc) { iCountErrors++; printerr("Error_109dv! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); // [] specifying subdirectories should fail unless they exist strLoc = "Loc_209ud"; dir2 = Directory.CreateDirectory(testDir); iCountTestcases++; try { dir2.MoveTo(Path.Combine(testDir, "Test", "Test", "Test")); iCountErrors++; printerr("Error_1039s! Expected exception not thrown"); fil2.Delete(); } catch (IOException) { } catch (Exception exc) { iCountErrors++; printerr("Error_2019u! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); // [] Exception if directory already exists strLoc = "Loc_2498x"; iCountTestcases++; Directory.CreateDirectory(testDir + "a"); if (!Interop.IsWindows) // exception on Unix would only happen if the directory isn't empty { File.Create(Path.Combine(testDir + "a", "temp.txt")).Dispose(); } dir2 = Directory.CreateDirectory(testDir); try { dir2.MoveTo(testDir + "a"); iCountErrors++; printerr("Error_2498h! Expected exception not thrown"); } catch (IOException) { } catch (Exception exc) { iCountErrors++; printerr("Error_289vt! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); new DirectoryInfo(testDir + "a").Delete(true); // [] Illiegal chars in new DirectoryInfo name strLoc = "Loc_2798r"; dir2 = Directory.CreateDirectory(testDir); iCountTestcases++; try { dir2.MoveTo("\0\0\0**\0.*\0\0"); iCountErrors++; printerr("Error_298hv! Expected exception not thrown"); } catch (ArgumentException) { } catch (Exception exc) { iCountErrors++; printerr("Error_2199d! Incorrect exception thrown, exc==" + exc.ToString()); } dir2.Delete(true); // [] Move a directory with subdirs strLoc = "Loc_209ux"; dir2 = Directory.CreateDirectory(testDir); DirectoryInfo subdir = dir2.CreateSubdirectory("Test5525"); // dir2.MoveTo("NewTest5525"); FailSafeDirectoryOperations.MoveDirectoryInfo(dir2, Path.Combine(TestInfo.CurrentDirectory, "NewTest5525")); iCountTestcases++; try { subdir = new DirectoryInfo(Path.Combine(TestInfo.CurrentDirectory, "NewTest5525", "Test5525")); } catch (Exception exc) { iCountErrors++; printerr("Error_290u1! Failed to move Folder, exc==" + exc.ToString()); } subdir.Delete(true); dir2.Delete(true); // [] //problems with trailing slashes and stuff - #431574 /** - We need to remove the trailing slash when we get the parent directory (we call Path.GetDirectoryName on the full path and having the slash will not work) - Root drive always have the trailing slash - MoveTo adds a trailing slash **/ String subDir = Path.Combine(TestInfo.CurrentDirectory, "LaksTemp"); DeleteFileDir(subDir); String[] values = { "TestDir", "TestDir" + Path.DirectorySeparatorChar }; String moveDir = Path.Combine(TestInfo.CurrentDirectory, values[1]); foreach (String value in values) { dir2 = new DirectoryInfo(subDir); dir2.Create(); dir2.MoveTo(Path.Combine(TestInfo.CurrentDirectory, value)); if (!dir2.FullName.Equals(moveDir)) { Console.WriteLine("moveDir: <{0}>", moveDir); iCountErrors++; Console.WriteLine("Err_374g! wrong vlaue returned: {0}", dir2.FullName); } dir2.Delete(); } /////////////////////////////////////////////////////////////////// /////////////////////////// END TESTS ///////////////////////////// } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } //// Finish Diagnostics if (iCountErrors != 0) { Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + iCountErrors.ToString()); } Assert.Equal(0, iCountErrors); } private static void DeleteFileDir(String path) { if (File.Exists(path)) File.Delete(path); if (Directory.Exists(path)) Directory.Delete(path); } public static void printerr(String err, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) { Console.WriteLine("ERROR: ({0}, {1}, {2}) {3}", memberName, filePath, lineNumber, err); } }
using System.Diagnostics.CodeAnalysis; using System.Net; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; using JsonApiDotNetCore.Serialization.Objects; namespace JsonApiDotNetCore.Serialization.Request.Adapters; /// <summary> /// Base class for validating and converting objects that represent an identity. /// </summary> public abstract class ResourceIdentityAdapter : BaseAdapter { private readonly IResourceGraph _resourceGraph; private readonly IResourceFactory _resourceFactory; protected ResourceIdentityAdapter(IResourceGraph resourceGraph, IResourceFactory resourceFactory) { ArgumentGuard.NotNull(resourceGraph, nameof(resourceGraph)); ArgumentGuard.NotNull(resourceFactory, nameof(resourceFactory)); _resourceGraph = resourceGraph; _resourceFactory = resourceFactory; } protected (IIdentifiable resource, ResourceType resourceType) ConvertResourceIdentity(IResourceIdentity identity, ResourceIdentityRequirements requirements, RequestAdapterState state) { ArgumentGuard.NotNull(identity, nameof(identity)); ArgumentGuard.NotNull(requirements, nameof(requirements)); ArgumentGuard.NotNull(state, nameof(state)); ResourceType resourceType = ResolveType(identity, requirements, state); IIdentifiable resource = CreateResource(identity, requirements, resourceType.ClrType, state); return (resource, resourceType); } private ResourceType ResolveType(IResourceIdentity identity, ResourceIdentityRequirements requirements, RequestAdapterState state) { AssertHasType(identity.Type, state); using IDisposable _ = state.Position.PushElement("type"); ResourceType? resourceType = _resourceGraph.FindResourceType(identity.Type); AssertIsKnownResourceType(resourceType, identity.Type, state); AssertIsCompatibleResourceType(resourceType, requirements.ResourceType, requirements.RelationshipName, state); return resourceType; } private static void AssertHasType([NotNull] string? identityType, RequestAdapterState state) { if (identityType == null) { throw new ModelConversionException(state.Position, "The 'type' element is required.", null); } } private static void AssertIsKnownResourceType([NotNull] ResourceType? resourceType, string typeName, RequestAdapterState state) { if (resourceType == null) { throw new ModelConversionException(state.Position, "Unknown resource type found.", $"Resource type '{typeName}' does not exist."); } } private static void AssertIsCompatibleResourceType(ResourceType actual, ResourceType? expected, string? relationshipName, RequestAdapterState state) { if (expected != null && !expected.ClrType.IsAssignableFrom(actual.ClrType)) { string message = relationshipName != null ? $"Type '{actual.PublicName}' is incompatible with type '{expected.PublicName}' of relationship '{relationshipName}'." : $"Type '{actual.PublicName}' is incompatible with type '{expected.PublicName}'."; throw new ModelConversionException(state.Position, "Incompatible resource type found.", message, HttpStatusCode.Conflict); } } private IIdentifiable CreateResource(IResourceIdentity identity, ResourceIdentityRequirements requirements, Type resourceClrType, RequestAdapterState state) { if (state.Request.Kind != EndpointKind.AtomicOperations) { AssertHasNoLid(identity, state); } AssertNoIdWithLid(identity, state); if (requirements.IdConstraint == JsonElementConstraint.Required) { AssertHasIdOrLid(identity, requirements, state); } else if (requirements.IdConstraint == JsonElementConstraint.Forbidden) { AssertHasNoId(identity, state); } AssertSameIdValue(identity, requirements.IdValue, state); AssertSameLidValue(identity, requirements.LidValue, state); IIdentifiable resource = _resourceFactory.CreateInstance(resourceClrType); AssignStringId(identity, resource, state); resource.LocalId = identity.Lid; return resource; } private static void AssertHasNoLid(IResourceIdentity identity, RequestAdapterState state) { if (identity.Lid != null) { using IDisposable _ = state.Position.PushElement("lid"); throw new ModelConversionException(state.Position, "The 'lid' element is not supported at this endpoint.", null); } } private static void AssertNoIdWithLid(IResourceIdentity identity, RequestAdapterState state) { if (identity.Id != null && identity.Lid != null) { throw new ModelConversionException(state.Position, "The 'id' and 'lid' element are mutually exclusive.", null); } } private static void AssertHasIdOrLid(IResourceIdentity identity, ResourceIdentityRequirements requirements, RequestAdapterState state) { string? message = null; if (requirements.IdValue != null && identity.Id == null) { message = "The 'id' element is required."; } else if (requirements.LidValue != null && identity.Lid == null) { message = "The 'lid' element is required."; } else if (identity.Id == null && identity.Lid == null) { message = state.Request.Kind == EndpointKind.AtomicOperations ? "The 'id' or 'lid' element is required." : "The 'id' element is required."; } if (message != null) { throw new ModelConversionException(state.Position, message, null); } } private static void AssertHasNoId(IResourceIdentity identity, RequestAdapterState state) { if (identity.Id != null) { using IDisposable _ = state.Position.PushElement("id"); throw new ModelConversionException(state.Position, "The use of client-generated IDs is disabled.", null, HttpStatusCode.Forbidden); } } private static void AssertSameIdValue(IResourceIdentity identity, string? expected, RequestAdapterState state) { if (expected != null && identity.Id != expected) { using IDisposable _ = state.Position.PushElement("id"); throw new ModelConversionException(state.Position, "Conflicting 'id' values found.", $"Expected '{expected}' instead of '{identity.Id}'.", HttpStatusCode.Conflict); } } private static void AssertSameLidValue(IResourceIdentity identity, string? expected, RequestAdapterState state) { if (expected != null && identity.Lid != expected) { using IDisposable _ = state.Position.PushElement("lid"); throw new ModelConversionException(state.Position, "Conflicting 'lid' values found.", $"Expected '{expected}' instead of '{identity.Lid}'.", HttpStatusCode.Conflict); } } private void AssignStringId(IResourceIdentity identity, IIdentifiable resource, RequestAdapterState state) { if (identity.Id != null) { try { resource.StringId = identity.Id; } catch (FormatException exception) { using IDisposable _ = state.Position.PushElement("id"); throw new ModelConversionException(state.Position, "Incompatible 'id' value found.", exception.Message); } } } protected static void AssertIsKnownRelationship([NotNull] RelationshipAttribute? relationship, string relationshipName, ResourceType resourceType, RequestAdapterState state) { if (relationship == null) { throw new ModelConversionException(state.Position, "Unknown relationship found.", $"Relationship '{relationshipName}' does not exist on resource type '{resourceType.PublicName}'."); } } protected internal static void AssertToManyInAddOrRemoveRelationship(RelationshipAttribute relationship, RequestAdapterState state) { bool requireToManyRelationship = state.Request.WriteOperation is WriteOperationKind.AddToRelationship or WriteOperationKind.RemoveFromRelationship; if (requireToManyRelationship && relationship is not HasManyAttribute) { string message = state.Request.Kind == EndpointKind.AtomicOperations ? "Only to-many relationships can be targeted through this operation." : "Only to-many relationships can be targeted through this endpoint."; throw new ModelConversionException(state.Position, message, $"Relationship '{relationship.PublicName}' is not a to-many relationship.", HttpStatusCode.Forbidden); } } }
#region WatiN Copyright (C) 2006-2009 Jeroen van Menen //Copyright 2006-2009 Jeroen van Menen // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion Copyright using System; using WatiN.Core.Interfaces; namespace WatiN.Core { /// <summary> /// This class is used to define the default settings used by WatiN. /// Use <c>Settings.Instance</c> to access or change these settings. /// </summary> /// <example> /// The following example shows you how to change the default time out which is used /// by the AttachtToIE(findBy) method to attach to an already existing Internet Explorer window /// or to an Internet Explorer window that will show up within 60 seconds after calling /// the AttachToIE(findBy) method. /// <code> /// public void AttachToIEExample() /// { /// // Change de default time out from 30 to 60 seconds. /// Settings.AttachToIETimeOut = 60; /// /// // Start Internet Explorer manually and type /// // http://watin.sourceforge.net in the navigation bar. /// /// // Now Attach to an existing Internet Explorer window /// IE ie = IE.AttachToIE(Find.ByTitle("WatiN"); /// /// System.Diagnostics.Debug.WriteLine(ie.Url); /// } /// </code> /// When you frequently want to change these settings you could also create /// two or more instances of the Settings class, set the desired defaults /// and set the settings class to Settings. /// <code> /// public void ChangeSettings() /// { /// Settings.Instance = LongTimeOut(); /// /// // Do something here that requires more time then the defaults /// /// Settings.Instance = ShortTimeOut(); /// /// // Do something here if you want a short time out to get /// // the exception quickly incase the item isn't found. /// } /// /// public Settings LongTimeOut() /// { /// Settings settings = new Settings(); /// /// settings.AttachToIETimeOut = 60; /// settings.WaitUntilExistsTimeOut = 60; /// settings.WaitForCompleteTimeOut = 60; /// /// return settings; /// } /// /// public Settings ShortTimeOut() /// { /// Settings settings = new Settings(); /// /// settings.AttachToIETimeOut = 5; /// settings.WaitUntilExistsTimeOut = 5; /// settings.WaitForCompleteTimeOut = 5; /// /// return settings; /// } /// </code> /// </example> public static class Settings { private static ISettings _instance = CreateDefaultSettings(); public static bool CloseExistingBrowserInstances = true; private static DefaultSettings CreateDefaultSettings() { return new DefaultSettings(); } public static ISettings Instance { get { return _instance; } set { _instance = value ?? CreateDefaultSettings(); } } /// <summary> /// Resets this instance to the initial defaults. /// </summary> public static void Reset() { Instance.Reset(); } /// <summary> /// Clones this instance. /// </summary> /// <returns></returns> public static ISettings Clone() { return Instance.Clone(); } /// <summary> /// Get or set the default time out used when calling IE ie = IE.AttachToIE(findBy). /// The default value is 30 seconds. Setting the time out to a negative value will /// throw a <see cref="ArgumentOutOfRangeException"/>. /// </summary> public static int AttachToIETimeOut { get { return Instance.AttachToIETimeOut; } set { Instance.AttachToIETimeOut = value; } } /// <summary> /// Get or set the default time out used when calling Element.WaitUntilExists(). /// The default value is 30 seconds. Setting the time out to a negative value will /// throw a <see cref="ArgumentOutOfRangeException"/>. /// </summary> public static int WaitUntilExistsTimeOut { get { return Instance.WaitUntilExistsTimeOut; } set { Instance.WaitUntilExistsTimeOut = value; } } /// <summary> /// Get or set the default time out used when calling ie.WaitForComplete(). /// The default value is 30 seconds. Setting the time out to a negative value will /// throw a <see cref="ArgumentOutOfRangeException"/>. /// </summary> public static int WaitForCompleteTimeOut { get { return Instance.WaitForCompleteTimeOut; } set { Instance.WaitForCompleteTimeOut = value; } } /// <summary> /// Get or set the default sleep time used when WatiN is waiting for something in a (retry) loop. /// The default value is 100 milliseconds. Setting the time out to a negative value will /// throw a <see cref="ArgumentOutOfRangeException"/>. /// </summary> public static int SleepTime { get { return Instance.SleepTime; } set { Instance.SleepTime = value; } } /// <summary> /// Turn highlighting of elements by WatiN on (<c>true</c>) or off (<c>false</c>). /// Highlighting of an element is done when WatiN fires an event on an /// element or executes a methode (like TypeText). /// </summary> public static bool HighLightElement { get { return Instance.HighLightElement; } set { Instance.HighLightElement = value; } } /// <summary> /// Set or get the color to highlight elements. Will be used if /// HighLightElement is set to <c>true</c>. /// Visit http://msdn.microsoft.com/workshop/author/dhtml/reference/colors/colors_name.asp /// for a full list of supported RGB colors and their names. /// </summary> public static string HighLightColor { get { return Instance.HighLightColor; } set { Instance.HighLightColor = value; } } /// <summary> /// Turn auto closing of dialogs on (<c>true</c>) or off (<c>false</c>). /// You need to set this value before creating or attaching to any /// Internet Explorer to have effect. /// </summary> public static bool AutoCloseDialogs { get { return Instance.AutoCloseDialogs; } set { Instance.AutoCloseDialogs = value; } } /// <summary> /// Gets or sets a value indicating whether to auto start the dialog watcher at all. /// This value is evaluated everytime a new IE instance is created /// </summary> /// <value> /// <c>true</c> if dialog watcher should be started when a new IE instance is created; otherwise, <c>false</c>. /// </value> public static bool AutoStartDialogWatcher { get { return Instance.AutoStartDialogWatcher; } set { Instance.AutoStartDialogWatcher = value; } } /// <summary> /// Gets or sets a value indicating whether to move the cursor to the top left /// of the screen everytime a new IE instance is created. /// </summary> /// <value> /// <c>true</c> when mouse should be moved to top left; otherwise, <c>false</c>. /// </value> public static bool AutoMoveMousePointerToTopLeft { get { return Instance.AutoMoveMousePointerToTopLeft; } set { Instance.AutoMoveMousePointerToTopLeft = value; } } /// <summary> /// Gets or sets a value indicating whether to make a new <see cref="IE"/> instance visible. /// </summary> /// <value> /// <c>true</c> if you want to make a new <see cref="IE"/> instance visible; otherwise, <c>false</c>. /// </value> public static bool MakeNewIeInstanceVisible { get { return Instance.MakeNewIeInstanceVisible; } set { Instance.MakeNewIeInstanceVisible = value; } } /// <summary> /// Gets or sets a factory to find element by their default characteristics. /// </summary> /// <remarks> /// The default value is a <see cref="FindByDefaultFactory"/> which finds elements /// by id. /// </remarks> public static IFindByDefaultFactory FindByDefaultFactory { get { return Instance.FindByDefaultFactory; } set { Instance.FindByDefaultFactory = value; if (Instance.FindByDefaultFactory == null) { Instance.FindByDefaultFactory = new FindByDefaultFactory(); } } } } }
//------------------------------------------------------------------------------ // <copyright file="DMLibDataHelper.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace DMLibTest { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using DMLibTestCodeGen; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.File; using MS.Test.Common.MsTestLib; internal static class DMLibDataHelper { public static void AddOneFile(DirNode dirNode, string fileName, long fileSizeInKB, FileAttributes? fa = null, DateTime? lmt = null) { AddOneFileInBytes(dirNode, fileName, 1024L * fileSizeInKB, fa, lmt); } public static void AddOneFileInBytes(DirNode dirNode, string fileName, long fileSizeInB, FileAttributes? fa = null, DateTime? lmt = null) { FileNode fileNode = new FileNode(fileName) { SizeInByte = fileSizeInB, FileAttr = fa, LastModifiedTime = lmt, }; dirNode.AddFileNode(fileNode); } public static FileNode RemoveOneFile(DirNode dirNode, string fileName) { return dirNode.DeleteFileNode(fileName); } public static DirNode RemoveOneDir(DirNode parentNode, string dirNodeToDelete) { return parentNode.DeleteDirNode(dirNodeToDelete); } public static void AddMultipleFiles(DirNode dirNode, string filePrefix, int fileNumber, int fileSizeInKB, FileAttributes? fa = null, DateTime? lmt = null) { DMLibDataHelper.AddTree(dirNode, string.Empty, filePrefix, fileNumber, 0, fileSizeInKB, fa, lmt); } public static void AddMultipleFilesNormalSize(DirNode dirNode, string filePrefix) { int[] fileSizes = new int[] { 0, 1, 4000, 4 * 1024, 10000 }; AddMultipleFilesDifferentSize(dirNode, filePrefix, fileSizes); } public static void AddMultipleFilesBigSize(DirNode dirNode, string filePrefix) { int[] fileSizes = new int[] { 32000, 64 * 1024 }; AddMultipleFilesDifferentSize(dirNode, filePrefix, fileSizes); } public static void AddMultipleFilesDifferentSize(DirNode dirNode, string filePrefix, int[] fileSizes) { for (int i = 0; i < fileSizes.Length; ++i) { FileNode fileNode = new FileNode(filePrefix + "_" + i) { SizeInByte = fileSizes[i] * 1024 }; dirNode.AddFileNode(fileNode); } } public static void AddMultipleFilesTotalSize(DirNode dirNode, string filePrefix, int fileNumber, int totalSizeInKB, DateTime? lmt = null) { int fileSizeInKB = totalSizeInKB / fileNumber; fileSizeInKB = fileSizeInKB == 0 ? 1 : fileSizeInKB; DMLibDataHelper.AddMultipleFiles(dirNode, filePrefix, fileNumber, fileSizeInKB, lmt: lmt); } public static void AddTree(DirNode dirNode, string dirPrefix, string filePrefix, int width, int depth, int fileSizeInKB, FileAttributes? fa = null, DateTime? lmt = null) { for (int i = 0; i < width; ++i) { string fileName = i == 0 ? filePrefix : filePrefix + "_" + i; FileNode fileNode = new FileNode(fileName) { SizeInByte = 1024L * fileSizeInKB, FileAttr = fa, LastModifiedTime = lmt, }; dirNode.AddFileNode(fileNode); } if (depth > 0) { for (int i = 0; i < width; ++i) { string dirName = i == 0 ? dirPrefix : dirPrefix + "_" + i; DirNode subDirNode = dirNode.GetDirNode(dirName); if (subDirNode == null) { subDirNode = new DirNode(dirName); dirNode.AddDirNode(subDirNode); } DMLibDataHelper.AddTree(subDirNode, dirPrefix, filePrefix, width, depth - 1, fileSizeInKB, fa, lmt: lmt); } } } public static void AddTreeTotalSize(DirNode dirNode, string dirPrefix, string filePrefix, int width, int depth, int totalSizeInKB, DateTime? lmt = null) { int fileNumber; if (width <= 1) { fileNumber = (depth + 1) * width; } else { int widthPowDepth = width; for (int i = 0; i < depth; ++i) { widthPowDepth *= width; } fileNumber = width * (widthPowDepth - 1) / (width - 1); } int fileSizeInKB = totalSizeInKB / fileNumber; fileSizeInKB = fileSizeInKB == 0 ? 1 : fileSizeInKB; DMLibDataHelper.AddTree(dirNode, dirPrefix, filePrefix, width, depth, fileSizeInKB, lmt: lmt); } public static void CreateLocalDirIfNotExists(string dirPath) { if (!String.Equals(string.Empty, dirPath) && !Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } } public static void CreateLocalFile(FileNode fileNode, string filePath) { Helper.GenerateFileInBytes(filePath, fileNode.SizeInByte); fileNode.AbsolutePath = filePath; if (fileNode.LastModifiedTime != null) { // Set last modified time FileInfo fileInfo = new FileInfo(filePath); fileInfo.LastWriteTimeUtc = (DateTime)fileNode.LastModifiedTime; } if (fileNode.FileAttr != null) { // remove default file attribute FileOp.RemoveFileAttribute(filePath, FileAttributes.Archive); // Set file Attributes FileOp.SetFileAttribute(filePath, (FileAttributes)fileNode.FileAttr); Test.Info("{0} attr is {1}", filePath, File.GetAttributes(filePath).ToString()); } } public static FileNode GetFileNode(DirNode dirNode, params string[] tokens) { DirNode currentDirNode = dirNode; for (int i = 0; i < tokens.Length; ++i) { if (i == tokens.Length - 1) { FileNode fileNode = currentDirNode.GetFileNode(tokens[i]); if (fileNode == null) { Test.Error("FileNode {0} doesn't exist.", tokens[i]); return null; } return fileNode; } else { currentDirNode = currentDirNode.GetDirNode(tokens[i]); if (currentDirNode == null) { Test.Error("DirNode {0} doesn't exist.", tokens[i]); return null; } } } return null; } public static void RemoveAllFileNodesExcept(DirNode rootNode, HashSet<FileNode> except) { List<FileNode> nodesToRemove = new List<FileNode>(); foreach (FileNode fileNode in rootNode.EnumerateFileNodesRecursively()) { if (!except.Contains(fileNode)) { nodesToRemove.Add(fileNode); } } foreach(FileNode nodeToRemove in nodesToRemove) { nodeToRemove.Parent.DeleteFileNode(nodeToRemove.Name); } } public static string DetailedInfo(this DMLibDataInfo dataInfo) { StringBuilder builder = new StringBuilder(); builder.AppendLine(string.Format("TransferDataInfo root: {0}", dataInfo.RootPath)); foreach (FileNode fileNode in dataInfo.EnumerateFileNodes()) { builder.AppendLine(fileNode.DetailedInfo()); } return builder.ToString(); } public static string DetailedInfo(this FileNode fileNode) { StringBuilder builder = new StringBuilder(); builder.AppendFormat("FileNode {0}: MD5 ({1}), LMT ({2})", fileNode.GetURLRelativePath(), fileNode.MD5, fileNode.LastModifiedTime); return builder.ToString(); } public static bool Equals(DMLibDataInfo infoA, DMLibDataInfo infoB) { bool result; bool aIsEmpty = infoA == null || infoA.RootNode.IsEmpty; bool bIsEmpty = infoB == null || infoB.RootNode.IsEmpty; if (aIsEmpty && bIsEmpty) { result = true; } else if(aIsEmpty || bIsEmpty) { result = false; } else { result = Equals(infoA.RootNode, infoB.RootNode); } if (!result) { Test.Info("-----Data Info A-----"); MultiDirectionTestHelper.PrintTransferDataInfo(infoA); Test.Info("-----Data Info B-----"); MultiDirectionTestHelper.PrintTransferDataInfo(infoB); } return result; } public static bool Equals(DirNode dirNodeA, DirNode dirNodeB) { // The same node if (dirNodeA == dirNodeB) { return true; } // Empty node equals to null if ((dirNodeA == null || dirNodeA.IsEmpty) && (dirNodeB == null || dirNodeB.IsEmpty)) { return true; } // Compare two nodes if (null != dirNodeA && null != dirNodeB) { if (dirNodeA.FileNodeCount != dirNodeB.FileNodeCount || dirNodeA.NonEmptyDirNodeCount != dirNodeB.NonEmptyDirNodeCount) { return false; } foreach(FileNode fileNodeA in dirNodeA.FileNodes) { FileNode fileNodeB = dirNodeB.GetFileNode(fileNodeA.Name); if (!DMLibDataHelper.Equals(fileNodeA, fileNodeB)) { return false; } } foreach(DirNode subDirNodeA in dirNodeA.DirNodes) { DirNode subDirNodeB = dirNodeB.GetDirNode(subDirNodeA.Name); if (!DMLibDataHelper.Equals(subDirNodeA, subDirNodeB)) { return false; } } return true; } return false; } public static bool Equals(FileNode fileNodeA, FileNode fileNodeB) { if (fileNodeA == fileNodeB) { return true; } if (null != fileNodeA && null != fileNodeB) { Test.Info(string.Format("Verify file: ({0},{1}); ({2},{3})", fileNodeA.Name, fileNodeA.MD5, fileNodeB.Name, fileNodeB.MD5)); if (!string.Equals(fileNodeA.Name, fileNodeB.Name, StringComparison.Ordinal) || !PropertiesStringEquals(fileNodeA.MD5, fileNodeB.MD5) || !PropertiesStringEquals(fileNodeA.CacheControl, fileNodeB.CacheControl) || !PropertiesStringEquals(fileNodeA.ContentDisposition, fileNodeB.ContentDisposition) || !PropertiesStringEquals(fileNodeA.ContentEncoding, fileNodeB.ContentEncoding) || !PropertiesStringEquals(fileNodeA.ContentLanguage, fileNodeB.ContentLanguage)) { return false; } if (!MetadataEquals(fileNodeA.Metadata, fileNodeB.Metadata)) { return false; } foreach (var keyValuePair in fileNodeA.Metadata) { if (!fileNodeB.Metadata.Contains(keyValuePair)) { return false; } } return true; } string name; if (fileNodeA != null) { name = fileNodeA.Name; } else { name = fileNodeB.Name; } Test.Info("Fail to verify file: {0}", name); return false; } private static bool MetadataEquals(IDictionary<string, string> metadataA, IDictionary<string, string> metadataB) { if (metadataA == metadataB) { return true; } if (metadataA == null || metadataB == null) { return false; } if (metadataA.Count != metadataB.Count) { return false; } foreach (var keyValuePair in metadataB) { if (!metadataB.Contains(keyValuePair)) { return false; } } return true; } private static bool PropertiesStringEquals(string valueA, string ValueB) { if (string.IsNullOrEmpty(valueA)) { if (string.IsNullOrEmpty(ValueB)) { return true; } return false; } return string.Equals(valueA, ValueB, StringComparison.Ordinal); } public static string GetLocalRelativePath(this DataInfoNode node) { return Path.Combine(node.PathComponents.ToArray()); } public static string GetURLRelativePath(this DataInfoNode node) { return String.Join("/", node.PathComponents); } public static string GetSourceRelativePath(this DataInfoNode node) { if (DMLibTestContext.SourceType == DMLibDataType.Local) { return node.GetLocalRelativePath(); } else { return node.GetURLRelativePath(); } } public static string GetDestRelativePath(this DataInfoNode node) { if (DMLibTestContext.DestType == DMLibDataType.Local) { return node.GetLocalRelativePath(); } else { return node.GetURLRelativePath(); } } public static void SetCalculatedFileMD5(DMLibDataInfo dataInfo, DataAdaptor<DMLibDataInfo> destAdaptor, bool disableMD5Check = false) { foreach (FileNode fileNode in dataInfo.EnumerateFileNodes()) { if (DMLibTestBase.IsCloudBlob(DMLibTestContext.DestType)) { CloudBlobDataAdaptor cloudBlobDataAdaptor = destAdaptor as CloudBlobDataAdaptor; CloudBlob cloudBlob = cloudBlobDataAdaptor.GetCloudBlobReference(fileNode); fileNode.MD5 = CloudBlobHelper.CalculateMD5ByDownloading(cloudBlob, disableMD5Check); } else if (DMLibTestContext.DestType == DMLibDataType.CloudFile) { CloudFileDataAdaptor cloudFileDataAdaptor = destAdaptor as CloudFileDataAdaptor; CloudFile cloudFile = cloudFileDataAdaptor.GetCloudFileReference(fileNode); fileNode.MD5 = CloudFileHelper.CalculateMD5ByDownloading(cloudFile, disableMD5Check); } // No need to set md5 for local destination } } } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.EntityState.Appearance { /// <summary> /// Enumeration values for SensorEmitterAppearance (es.appear.sensoremitter, Sensor/Emitter Kind, /// section 4.3.9) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public struct SensorEmitterAppearance { /// <summary> /// Describes the paint scheme of an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the paint scheme of an entity")] public enum PaintSchemeValue : uint { /// <summary> /// Uniform color /// </summary> UniformColor = 0, /// <summary> /// Camouflage /// </summary> Camouflage = 1 } /// <summary> /// Describes characteristics of mobility kill /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes characteristics of mobility kill")] public enum MobilityValue : uint { /// <summary> /// No mobility kill /// </summary> NoMobilityKill = 0, /// <summary> /// Mobility kill /// </summary> MobilityKill = 1 } /// <summary> /// Describes characteristics of mission kill (e.g. damaged antenna) /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes characteristics of mission kill (e.g. damaged antenna)")] public enum MissionValue : uint { /// <summary> /// No mission kill /// </summary> NoMissionKill = 0, /// <summary> /// Mission kill /// </summary> MissionKill = 1 } /// <summary> /// Describes the damaged appearance of an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the damaged appearance of an entity")] public enum DamageValue : uint { /// <summary> /// No damage /// </summary> NoDamage = 0, /// <summary> /// Slight damage /// </summary> SlightDamage = 1, /// <summary> /// Moderate damage /// </summary> ModerateDamage = 2, /// <summary> /// Destroyed /// </summary> Destroyed = 3 } /// <summary> /// Describes status or location of smoke emanating from an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes status or location of smoke emanating from an entity")] public enum SmokeValue : uint { /// <summary> /// Not smoking /// </summary> NotSmoking = 0, /// <summary> /// Smoke plume rising from the entity /// </summary> SmokePlumeRisingFromTheEntity = 1, /// <summary> /// Entity is emitting engine smoke /// </summary> EntityIsEmittingEngineSmoke = 2, /// <summary> /// Entity is emitting engine smoke, and smoke plume is rising from the entity /// </summary> EntityIsEmittingEngineSmokeAndSmokePlumeIsRisingFromTheEntity = 3 } /// <summary> /// Describes the size of the dust cloud trailing effect for the Sensor/Emitter entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the size of the dust cloud trailing effect for the Sensor/Emitter entity")] public enum TrailingEffectsValue : uint { /// <summary> /// None /// </summary> None = 0, /// <summary> /// Small /// </summary> Small = 1, /// <summary> /// Medium /// </summary> Medium = 2, /// <summary> /// Large /// </summary> Large = 3 } /// <summary> /// Describes the status of lights on the sensor /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the status of lights on the sensor")] public enum LightsValue : uint { /// <summary> /// Off /// </summary> Off = 0, /// <summary> /// On /// </summary> On = 1 } /// <summary> /// Describes whether flames are rising from the entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes whether flames are rising from the entity")] public enum FlamingValue : uint { /// <summary> /// None /// </summary> None = 0, /// <summary> /// Flames present /// </summary> FlamesPresent = 1 } /// <summary> /// Describes the elevated status of the sensor's antenna /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the elevated status of the sensor's antenna")] public enum AntennaValue : uint { /// <summary> /// Not raised /// </summary> NotRaised = 0, /// <summary> /// Raised /// </summary> Raised = 1 } /// <summary> /// Describes the type of camouflage /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the type of camouflage")] public enum CamouflageTypeValue : uint { /// <summary> /// Desert camouflage /// </summary> DesertCamouflage = 0, /// <summary> /// Winter camouflage /// </summary> WinterCamouflage = 1, /// <summary> /// Forest camouflage /// </summary> ForestCamouflage = 2, /// <summary> /// null /// </summary> Unknown = 3 } /// <summary> /// Describes the type of concealment /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the type of concealment")] public enum ConcealedValue : uint { /// <summary> /// Not concealed /// </summary> NotConcealed = 0, /// <summary> /// Entity in a prepared concealed position (with netting, etc.) /// </summary> EntityInAPreparedConcealedPositionWithNettingEtc = 1 } /// <summary> /// Describes the frozen status of an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the frozen status of an entity")] public enum FrozenStatusValue : uint { /// <summary> /// Not frozen /// </summary> NotFrozen = 0, /// <summary> /// Frozen (Frozen entities should not be dead-reckoned, i.e. they should be displayed as fixed at the current location even if nonzero velocity, acceleration or rotation data is received from the frozen entity) /// </summary> FrozenFrozenEntitiesShouldNotBeDeadReckonedIETheyShouldBeDisplayedAsFixedAtTheCurrentLocationEvenIfNonzeroVelocityAccelerationOrRotationDataIsReceivedFromTheFrozenEntity = 1 } /// <summary> /// Describes the power-plant status of the sensor /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the power-plant status of the sensor")] public enum PowerPlantStatusValue : uint { /// <summary> /// Power plant off /// </summary> PowerPlantOff = 0, /// <summary> /// Power plant on /// </summary> PowerPlantOn = 1 } /// <summary> /// Describes the state of an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the state of an entity")] public enum StateValue : uint { /// <summary> /// Active /// </summary> Active = 0, /// <summary> /// Deactivated /// </summary> Deactivated = 1 } /// <summary> /// Describes the status of a tent extension /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the status of a tent extension")] public enum TentValue : uint { /// <summary> /// Not extended /// </summary> NotExtended = 0, /// <summary> /// Extended /// </summary> Extended = 1 } /// <summary> /// Describes whether Blackout Lights are on or off. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes whether Blackout Lights are on or off.")] public enum BlackoutLightsValue : uint { /// <summary> /// Off /// </summary> Off = 0, /// <summary> /// On /// </summary> On = 1 } /// <summary> /// Describes whether Interior Lights are on or off. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes whether Interior Lights are on or off.")] public enum InteriorLightsValue : uint { /// <summary> /// Off /// </summary> Off = 0, /// <summary> /// On /// </summary> On = 1 } private SensorEmitterAppearance.PaintSchemeValue paintScheme; private SensorEmitterAppearance.MobilityValue mobility; private SensorEmitterAppearance.MissionValue mission; private SensorEmitterAppearance.DamageValue damage; private SensorEmitterAppearance.SmokeValue smoke; private SensorEmitterAppearance.TrailingEffectsValue trailingEffects; private SensorEmitterAppearance.LightsValue lights; private SensorEmitterAppearance.FlamingValue flaming; private SensorEmitterAppearance.AntennaValue antenna; private SensorEmitterAppearance.CamouflageTypeValue camouflageType; private SensorEmitterAppearance.ConcealedValue concealed; private SensorEmitterAppearance.FrozenStatusValue frozenStatus; private SensorEmitterAppearance.PowerPlantStatusValue powerPlantStatus; private SensorEmitterAppearance.StateValue state; private SensorEmitterAppearance.TentValue tent; private SensorEmitterAppearance.BlackoutLightsValue blackoutLights; private SensorEmitterAppearance.InteriorLightsValue interiorLights; /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(SensorEmitterAppearance left, SensorEmitterAppearance right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(SensorEmitterAppearance left, SensorEmitterAppearance right) { if (object.ReferenceEquals(left, right)) { return true; } // If parameters are null return false (cast to object to prevent recursive loop!) if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } /// <summary> /// Performs an explicit conversion from <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> to <see cref="System.UInt32"/>. /// </summary> /// <param name="obj">The <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> scheme instance.</param> /// <returns>The result of the conversion.</returns> public static explicit operator uint(SensorEmitterAppearance obj) { return obj.ToUInt32(); } /// <summary> /// Performs an explicit conversion from <see cref="System.UInt32"/> to <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/>. /// </summary> /// <param name="value">The uint value.</param> /// <returns>The result of the conversion.</returns> public static explicit operator SensorEmitterAppearance(uint value) { return SensorEmitterAppearance.FromUInt32(value); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> instance from the byte array. /// </summary> /// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/>.</param> /// <param name="index">The starting position within value.</param> /// <returns>The <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> instance, represented by a byte array.</returns> /// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception> /// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception> public static SensorEmitterAppearance FromByteArray(byte[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index > array.Length - 1 || index + 4 > array.Length - 1) { throw new IndexOutOfRangeException(); } return FromUInt32(BitConverter.ToUInt32(array, index)); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> instance from the uint value. /// </summary> /// <param name="value">The uint value which represents the <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> instance.</param> /// <returns>The <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> instance, represented by the uint value.</returns> public static SensorEmitterAppearance FromUInt32(uint value) { SensorEmitterAppearance ps = new SensorEmitterAppearance(); uint mask0 = 0x0001; byte shift0 = 0; uint newValue0 = value & mask0 >> shift0; ps.PaintScheme = (SensorEmitterAppearance.PaintSchemeValue)newValue0; uint mask1 = 0x0002; byte shift1 = 1; uint newValue1 = value & mask1 >> shift1; ps.Mobility = (SensorEmitterAppearance.MobilityValue)newValue1; uint mask2 = 0x0004; byte shift2 = 2; uint newValue2 = value & mask2 >> shift2; ps.Mission = (SensorEmitterAppearance.MissionValue)newValue2; uint mask3 = 0x0018; byte shift3 = 3; uint newValue3 = value & mask3 >> shift3; ps.Damage = (SensorEmitterAppearance.DamageValue)newValue3; uint mask4 = 0x0060; byte shift4 = 5; uint newValue4 = value & mask4 >> shift4; ps.Smoke = (SensorEmitterAppearance.SmokeValue)newValue4; uint mask5 = 0x0180; byte shift5 = 7; uint newValue5 = value & mask5 >> shift5; ps.TrailingEffects = (SensorEmitterAppearance.TrailingEffectsValue)newValue5; uint mask7 = 0x1000; byte shift7 = 12; uint newValue7 = value & mask7 >> shift7; ps.Lights = (SensorEmitterAppearance.LightsValue)newValue7; uint mask9 = 0x8000; byte shift9 = 15; uint newValue9 = value & mask9 >> shift9; ps.Flaming = (SensorEmitterAppearance.FlamingValue)newValue9; uint mask10 = 0x10000; byte shift10 = 16; uint newValue10 = value & mask10 >> shift10; ps.Antenna = (SensorEmitterAppearance.AntennaValue)newValue10; uint mask11 = 0x60000; byte shift11 = 17; uint newValue11 = value & mask11 >> shift11; ps.CamouflageType = (SensorEmitterAppearance.CamouflageTypeValue)newValue11; uint mask12 = 0x80000; byte shift12 = 19; uint newValue12 = value & mask12 >> shift12; ps.Concealed = (SensorEmitterAppearance.ConcealedValue)newValue12; uint mask14 = 0x200000; byte shift14 = 21; uint newValue14 = value & mask14 >> shift14; ps.FrozenStatus = (SensorEmitterAppearance.FrozenStatusValue)newValue14; uint mask15 = 0x400000; byte shift15 = 22; uint newValue15 = value & mask15 >> shift15; ps.PowerPlantStatus = (SensorEmitterAppearance.PowerPlantStatusValue)newValue15; uint mask16 = 0x800000; byte shift16 = 23; uint newValue16 = value & mask16 >> shift16; ps.State = (SensorEmitterAppearance.StateValue)newValue16; uint mask17 = 0x1000000; byte shift17 = 24; uint newValue17 = value & mask17 >> shift17; ps.Tent = (SensorEmitterAppearance.TentValue)newValue17; uint mask19 = 0x4000000; byte shift19 = 26; uint newValue19 = value & mask19 >> shift19; ps.BlackoutLights = (SensorEmitterAppearance.BlackoutLightsValue)newValue19; uint mask21 = 0x20000000; byte shift21 = 29; uint newValue21 = value & mask21 >> shift21; ps.InteriorLights = (SensorEmitterAppearance.InteriorLightsValue)newValue21; return ps; } /// <summary> /// Gets or sets the paintscheme. /// </summary> /// <value>The paintscheme.</value> public SensorEmitterAppearance.PaintSchemeValue PaintScheme { get { return this.paintScheme; } set { this.paintScheme = value; } } /// <summary> /// Gets or sets the mobility. /// </summary> /// <value>The mobility.</value> public SensorEmitterAppearance.MobilityValue Mobility { get { return this.mobility; } set { this.mobility = value; } } /// <summary> /// Gets or sets the mission. /// </summary> /// <value>The mission.</value> public SensorEmitterAppearance.MissionValue Mission { get { return this.mission; } set { this.mission = value; } } /// <summary> /// Gets or sets the damage. /// </summary> /// <value>The damage.</value> public SensorEmitterAppearance.DamageValue Damage { get { return this.damage; } set { this.damage = value; } } /// <summary> /// Gets or sets the smoke. /// </summary> /// <value>The smoke.</value> public SensorEmitterAppearance.SmokeValue Smoke { get { return this.smoke; } set { this.smoke = value; } } /// <summary> /// Gets or sets the trailingeffects. /// </summary> /// <value>The trailingeffects.</value> public SensorEmitterAppearance.TrailingEffectsValue TrailingEffects { get { return this.trailingEffects; } set { this.trailingEffects = value; } } /// <summary> /// Gets or sets the lights. /// </summary> /// <value>The lights.</value> public SensorEmitterAppearance.LightsValue Lights { get { return this.lights; } set { this.lights = value; } } /// <summary> /// Gets or sets the flaming. /// </summary> /// <value>The flaming.</value> public SensorEmitterAppearance.FlamingValue Flaming { get { return this.flaming; } set { this.flaming = value; } } /// <summary> /// Gets or sets the antenna. /// </summary> /// <value>The antenna.</value> public SensorEmitterAppearance.AntennaValue Antenna { get { return this.antenna; } set { this.antenna = value; } } /// <summary> /// Gets or sets the camouflagetype. /// </summary> /// <value>The camouflagetype.</value> public SensorEmitterAppearance.CamouflageTypeValue CamouflageType { get { return this.camouflageType; } set { this.camouflageType = value; } } /// <summary> /// Gets or sets the concealed. /// </summary> /// <value>The concealed.</value> public SensorEmitterAppearance.ConcealedValue Concealed { get { return this.concealed; } set { this.concealed = value; } } /// <summary> /// Gets or sets the frozenstatus. /// </summary> /// <value>The frozenstatus.</value> public SensorEmitterAppearance.FrozenStatusValue FrozenStatus { get { return this.frozenStatus; } set { this.frozenStatus = value; } } /// <summary> /// Gets or sets the powerplantstatus. /// </summary> /// <value>The powerplantstatus.</value> public SensorEmitterAppearance.PowerPlantStatusValue PowerPlantStatus { get { return this.powerPlantStatus; } set { this.powerPlantStatus = value; } } /// <summary> /// Gets or sets the state. /// </summary> /// <value>The state.</value> public SensorEmitterAppearance.StateValue State { get { return this.state; } set { this.state = value; } } /// <summary> /// Gets or sets the tent. /// </summary> /// <value>The tent.</value> public SensorEmitterAppearance.TentValue Tent { get { return this.tent; } set { this.tent = value; } } /// <summary> /// Gets or sets the blackoutlights. /// </summary> /// <value>The blackoutlights.</value> public SensorEmitterAppearance.BlackoutLightsValue BlackoutLights { get { return this.blackoutLights; } set { this.blackoutLights = value; } } /// <summary> /// Gets or sets the interiorlights. /// </summary> /// <value>The interiorlights.</value> public SensorEmitterAppearance.InteriorLightsValue InteriorLights { get { return this.interiorLights; } set { this.interiorLights = value; } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is SensorEmitterAppearance)) { return false; } return this.Equals((SensorEmitterAppearance)obj); } /// <summary> /// Determines whether the specified <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> instance is equal to this instance. /// </summary> /// <param name="other">The <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> instance to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(SensorEmitterAppearance other) { // If parameter is null return false (cast to object to prevent recursive loop!) if ((object)other == null) { return false; } return this.PaintScheme == other.PaintScheme && this.Mobility == other.Mobility && this.Mission == other.Mission && this.Damage == other.Damage && this.Smoke == other.Smoke && this.TrailingEffects == other.TrailingEffects && this.Lights == other.Lights && this.Flaming == other.Flaming && this.Antenna == other.Antenna && this.CamouflageType == other.CamouflageType && this.Concealed == other.Concealed && this.FrozenStatus == other.FrozenStatus && this.PowerPlantStatus == other.PowerPlantStatus && this.State == other.State && this.Tent == other.Tent && this.BlackoutLights == other.BlackoutLights && this.InteriorLights == other.InteriorLights; } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> to the byte array. /// </summary> /// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> instance.</returns> public byte[] ToByteArray() { return BitConverter.GetBytes(this.ToUInt32()); } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> to the uint value. /// </summary> /// <returns>The uint value representing the current <see cref="OpenDis.Enumerations.EntityState.Appearance.SensorEmitterAppearance"/> instance.</returns> public uint ToUInt32() { uint val = 0; val |= (uint)((uint)this.PaintScheme << 0); val |= (uint)((uint)this.Mobility << 1); val |= (uint)((uint)this.Mission << 2); val |= (uint)((uint)this.Damage << 3); val |= (uint)((uint)this.Smoke << 5); val |= (uint)((uint)this.TrailingEffects << 7); val |= (uint)((uint)this.Lights << 12); val |= (uint)((uint)this.Flaming << 15); val |= (uint)((uint)this.Antenna << 16); val |= (uint)((uint)this.CamouflageType << 17); val |= (uint)((uint)this.Concealed << 19); val |= (uint)((uint)this.FrozenStatus << 21); val |= (uint)((uint)this.PowerPlantStatus << 22); val |= (uint)((uint)this.State << 23); val |= (uint)((uint)this.Tent << 24); val |= (uint)((uint)this.BlackoutLights << 26); val |= (uint)((uint)this.InteriorLights << 29); return val; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { int hash = 17; // Overflow is fine, just wrap unchecked { hash = (hash * 29) + this.PaintScheme.GetHashCode(); hash = (hash * 29) + this.Mobility.GetHashCode(); hash = (hash * 29) + this.Mission.GetHashCode(); hash = (hash * 29) + this.Damage.GetHashCode(); hash = (hash * 29) + this.Smoke.GetHashCode(); hash = (hash * 29) + this.TrailingEffects.GetHashCode(); hash = (hash * 29) + this.Lights.GetHashCode(); hash = (hash * 29) + this.Flaming.GetHashCode(); hash = (hash * 29) + this.Antenna.GetHashCode(); hash = (hash * 29) + this.CamouflageType.GetHashCode(); hash = (hash * 29) + this.Concealed.GetHashCode(); hash = (hash * 29) + this.FrozenStatus.GetHashCode(); hash = (hash * 29) + this.PowerPlantStatus.GetHashCode(); hash = (hash * 29) + this.State.GetHashCode(); hash = (hash * 29) + this.Tent.GetHashCode(); hash = (hash * 29) + this.BlackoutLights.GetHashCode(); hash = (hash * 29) + this.InteriorLights.GetHashCode(); } return hash; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Dataload { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Datastream; using NUnit.Framework; /// <summary> /// Data streamer tests. /// </summary> public sealed class DataStreamerTest { /** Cache name. */ private const string CacheName = "partitioned"; /** Node. */ private IIgnite _grid; /** Node 2. */ private IIgnite _grid2; /** Cache. */ private ICache<int, int?> _cache; /// <summary> /// Initialization routine. /// </summary> [TestFixtureSetUp] public void InitClient() { _grid = Ignition.Start(TestUtils.GetTestConfiguration()); _grid2 = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration()) { IgniteInstanceName = "grid1" }); _cache = _grid.CreateCache<int, int?>(CacheName); } /// <summary> /// Fixture teardown. /// </summary> [TestFixtureTearDown] public void StopGrids() { Ignition.StopAll(true); } /// <summary> /// /// </summary> [SetUp] public void BeforeTest() { Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name); for (int i = 0; i < 100; i++) _cache.Remove(i); } [TearDown] public void AfterTest() { TestUtils.AssertHandleRegistryIsEmpty(1000, _grid); } /// <summary> /// Test data streamer property configuration. Ensures that at least no exceptions are thrown. /// </summary> [Test] public void TestPropertyPropagation() { using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName)) { Assert.AreEqual(CacheName, ldr.CacheName); Assert.AreEqual(0, ldr.AutoFlushFrequency); Assert.IsFalse(ldr.AllowOverwrite); ldr.AllowOverwrite = true; Assert.IsTrue(ldr.AllowOverwrite); ldr.AllowOverwrite = false; Assert.IsFalse(ldr.AllowOverwrite); Assert.IsFalse(ldr.SkipStore); ldr.SkipStore = true; Assert.IsTrue(ldr.SkipStore); ldr.SkipStore = false; Assert.IsFalse(ldr.SkipStore); Assert.AreEqual(DataStreamerDefaults.DefaultPerNodeBufferSize, ldr.PerNodeBufferSize); ldr.PerNodeBufferSize = 1; Assert.AreEqual(1, ldr.PerNodeBufferSize); ldr.PerNodeBufferSize = 2; Assert.AreEqual(2, ldr.PerNodeBufferSize); Assert.AreEqual(DataStreamerDefaults.DefaultPerThreadBufferSize, ldr.PerThreadBufferSize); ldr.PerThreadBufferSize = 1; Assert.AreEqual(1, ldr.PerThreadBufferSize); ldr.PerThreadBufferSize = 2; Assert.AreEqual(2, ldr.PerThreadBufferSize); Assert.AreEqual(0, ldr.PerNodeParallelOperations); var ops = DataStreamerDefaults.DefaultParallelOperationsMultiplier * IgniteConfiguration.DefaultThreadPoolSize; ldr.PerNodeParallelOperations = ops; Assert.AreEqual(ops, ldr.PerNodeParallelOperations); ldr.PerNodeParallelOperations = 2; Assert.AreEqual(2, ldr.PerNodeParallelOperations); Assert.AreEqual(DataStreamerDefaults.DefaultTimeout, ldr.Timeout); ldr.Timeout = TimeSpan.MaxValue; Assert.AreEqual(TimeSpan.MaxValue, ldr.Timeout); ldr.Timeout = TimeSpan.FromSeconds(1.5); Assert.AreEqual(1.5, ldr.Timeout.TotalSeconds); } } /// <summary> /// Test data add/remove. /// </summary> [Test] public void TestAddRemove() { IDataStreamer<int, int> ldr; using (ldr = _grid.GetDataStreamer<int, int>(CacheName)) { Assert.IsFalse(ldr.Task.IsCompleted); ldr.AllowOverwrite = true; // Additions. var task = ldr.AddData(1, 1); ldr.Flush(); Assert.AreEqual(1, _cache.Get(1)); Assert.IsTrue(task.IsCompleted); Assert.IsFalse(ldr.Task.IsCompleted); task = ldr.AddData(new KeyValuePair<int, int>(2, 2)); ldr.Flush(); Assert.AreEqual(2, _cache.Get(2)); Assert.IsTrue(task.IsCompleted); task = ldr.AddData(new [] { new KeyValuePair<int, int>(3, 3), new KeyValuePair<int, int>(4, 4) }); ldr.Flush(); Assert.AreEqual(3, _cache.Get(3)); Assert.AreEqual(4, _cache.Get(4)); Assert.IsTrue(task.IsCompleted); // Removal. task = ldr.RemoveData(1); ldr.Flush(); Assert.IsFalse(_cache.ContainsKey(1)); Assert.IsTrue(task.IsCompleted); // Mixed. ldr.AddData(5, 5); ldr.RemoveData(2); ldr.AddData(new KeyValuePair<int, int>(7, 7)); ldr.AddData(6, 6); ldr.RemoveData(4); ldr.AddData(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(9, 9), new KeyValuePair<int, int>(10, 10) }); ldr.AddData(new KeyValuePair<int, int>(8, 8)); ldr.RemoveData(3); ldr.AddData(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(11, 11), new KeyValuePair<int, int>(12, 12) }); ldr.Flush(); for (int i = 2; i < 5; i++) Assert.IsFalse(_cache.ContainsKey(i)); for (int i = 5; i < 13; i++) Assert.AreEqual(i, _cache.Get(i)); } Assert.IsTrue(ldr.Task.IsCompleted); } /// <summary> /// Tests object graphs with loops. /// </summary> [Test] public void TestObjectGraphs() { var obj1 = new Container(); var obj2 = new Container(); var obj3 = new Container(); var obj4 = new Container(); obj1.Inner = obj2; obj2.Inner = obj1; obj3.Inner = obj1; obj4.Inner = new Container(); using (var ldr = _grid.GetDataStreamer<int, Container>(CacheName)) { ldr.AllowOverwrite = true; ldr.AddData(1, obj1); ldr.AddData(2, obj2); ldr.AddData(3, obj3); ldr.AddData(4, obj4); } var cache = _grid.GetCache<int, Container>(CacheName); var res = cache[1]; Assert.AreEqual(res, res.Inner.Inner); Assert.IsNotNull(cache[2].Inner); Assert.IsNotNull(cache[2].Inner.Inner); Assert.IsNotNull(cache[3].Inner); Assert.IsNotNull(cache[3].Inner.Inner); Assert.IsNotNull(cache[4].Inner); Assert.IsNull(cache[4].Inner.Inner); } /// <summary> /// Test "tryFlush". /// </summary> [Test] public void TestTryFlush() { using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName)) { var fut = ldr.AddData(1, 1); ldr.TryFlush(); fut.Wait(); Assert.AreEqual(1, _cache.Get(1)); } } /// <summary> /// Test buffer size adjustments. /// </summary> [Test] public void TestBufferSize() { using (var ldr = _grid.GetDataStreamer<int, int>(CacheName)) { const int timeout = 5000; var part1 = GetPrimaryPartitionKeys(_grid, 4); var part2 = GetPrimaryPartitionKeys(_grid2, 4); var task = ldr.AddData(part1[0], part1[0]); Thread.Sleep(100); Assert.IsFalse(task.IsCompleted); ldr.PerNodeBufferSize = 2; ldr.PerThreadBufferSize = 1; ldr.AddData(part2[0], part2[0]); ldr.AddData(part1[1], part1[1]); Assert.IsTrue(ldr.AddData(part2[1], part2[1]).Wait(timeout)); Assert.IsTrue(task.Wait(timeout)); Assert.AreEqual(part1[0], _cache.Get(part1[0])); Assert.AreEqual(part1[1], _cache.Get(part1[1])); Assert.AreEqual(part2[0], _cache.Get(part2[0])); Assert.AreEqual(part2[1], _cache.Get(part2[1])); Assert.IsTrue(ldr.AddData(new[] { new KeyValuePair<int, int>(part1[2], part1[2]), new KeyValuePair<int, int>(part1[3], part1[3]), new KeyValuePair<int, int>(part2[2], part2[2]), new KeyValuePair<int, int>(part2[3], part2[3]) }).Wait(timeout)); Assert.AreEqual(part1[2], _cache.Get(part1[2])); Assert.AreEqual(part1[3], _cache.Get(part1[3])); Assert.AreEqual(part2[2], _cache.Get(part2[2])); Assert.AreEqual(part2[3], _cache.Get(part2[3])); } } /// <summary> /// Gets the primary partition keys. /// </summary> private static int[] GetPrimaryPartitionKeys(IIgnite ignite, int count) { var affinity = ignite.GetAffinity(CacheName); var localNode = ignite.GetCluster().GetLocalNode(); var part = affinity.GetPrimaryPartitions(localNode).First(); return Enumerable.Range(0, int.MaxValue) .Where(k => affinity.GetPartition(k) == part) .Take(count) .ToArray(); } /// <summary> /// Test close. /// </summary> [Test] public void TestClose() { using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName)) { var fut = ldr.AddData(1, 1); ldr.Close(false); fut.Wait(); Assert.AreEqual(1, _cache.Get(1)); } } /// <summary> /// Test close with cancellation. /// </summary> [Test] public void TestCancel() { using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName)) { var fut = ldr.AddData(1, 1); ldr.Close(true); fut.Wait(); Assert.IsFalse(_cache.ContainsKey(1)); } } /// <summary> /// Tests that streamer gets collected when there are no references to it. /// </summary> [Test] [Ignore("IGNITE-8731")] public void TestFinalizer() { var streamer = _grid.GetDataStreamer<int, int>(CacheName); var streamerRef = new WeakReference(streamer); Assert.IsNotNull(streamerRef.Target); // ReSharper disable once RedundantAssignment streamer = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.IsNull(streamerRef.Target); } /// <summary> /// Test auto-flush feature. /// </summary> [Test] public void TestAutoFlush() { using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName)) { // Test auto flush turning on. var fut = ldr.AddData(1, 1); Thread.Sleep(100); Assert.IsFalse(fut.IsCompleted); ldr.AutoFlushFrequency = 1000; fut.Wait(); // Test forced flush after frequency change. fut = ldr.AddData(2, 2); ldr.AutoFlushFrequency = long.MaxValue; fut.Wait(); // Test another forced flush after frequency change. fut = ldr.AddData(3, 3); ldr.AutoFlushFrequency = 1000; fut.Wait(); // Test flush before stop. fut = ldr.AddData(4, 4); ldr.AutoFlushFrequency = 0; fut.Wait(); // Test flush after second turn on. fut = ldr.AddData(5, 5); ldr.AutoFlushFrequency = 1000; fut.Wait(); Assert.AreEqual(1, _cache.Get(1)); Assert.AreEqual(2, _cache.Get(2)); Assert.AreEqual(3, _cache.Get(3)); Assert.AreEqual(4, _cache.Get(4)); Assert.AreEqual(5, _cache.Get(5)); } } /// <summary> /// Test multithreaded behavior. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestMultithreaded() { int entriesPerThread = 100000; int threadCnt = 8; for (int i = 0; i < 5; i++) { _cache.Clear(); Assert.AreEqual(0, _cache.GetSize()); Stopwatch watch = new Stopwatch(); watch.Start(); using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName)) { ldr.PerNodeBufferSize = 1024; int ctr = 0; TestUtils.RunMultiThreaded(() => { int threadIdx = Interlocked.Increment(ref ctr); int startIdx = (threadIdx - 1) * entriesPerThread; int endIdx = startIdx + entriesPerThread; for (int j = startIdx; j < endIdx; j++) { // ReSharper disable once AccessToDisposedClosure ldr.AddData(j, j); if (j % 100000 == 0) Console.WriteLine("Put [thread=" + threadIdx + ", cnt=" + j + ']'); } }, threadCnt); } Console.WriteLine("Iteration " + i + ": " + watch.ElapsedMilliseconds); watch.Reset(); for (int j = 0; j < threadCnt * entriesPerThread; j++) Assert.AreEqual(j, j); } } /// <summary> /// Tests custom receiver. /// </summary> [Test] public void TestStreamReceiver() { TestStreamReceiver(new StreamReceiverBinarizable()); TestStreamReceiver(new StreamReceiverSerializable()); } /// <summary> /// Tests StreamVisitor. /// </summary> [Test] public void TestStreamVisitor() { TestStreamReceiver(new StreamVisitor<int, int>((c, e) => c.Put(e.Key, e.Value + 1))); } /// <summary> /// Tests StreamTransformer. /// </summary> [Test] public void TestStreamTransformer() { TestStreamReceiver(new StreamTransformer<int, int, int, int>(new EntryProcessorSerializable())); TestStreamReceiver(new StreamTransformer<int, int, int, int>(new EntryProcessorBinarizable())); } /// <summary> /// Tests specified receiver. /// </summary> private void TestStreamReceiver(IStreamReceiver<int, int> receiver) { using (var ldr = _grid.GetDataStreamer<int, int>(CacheName)) { ldr.AllowOverwrite = true; ldr.Receiver = new StreamReceiverBinarizable(); ldr.Receiver = receiver; // check double assignment Assert.AreEqual(ldr.Receiver, receiver); for (var i = 0; i < 100; i++) ldr.AddData(i, i); ldr.Flush(); for (var i = 0; i < 100; i++) Assert.AreEqual(i + 1, _cache.Get(i)); } } /// <summary> /// Tests the stream receiver in keepBinary mode. /// </summary> [Test] public void TestStreamReceiverKeepBinary() { // ReSharper disable once LocalVariableHidesMember var cache = _grid.GetCache<int, BinarizableEntry>(CacheName); using (var ldr0 = _grid.GetDataStreamer<int, int>(CacheName)) using (var ldr = ldr0.WithKeepBinary<int, IBinaryObject>()) { ldr.Receiver = new StreamReceiverKeepBinary(); ldr.AllowOverwrite = true; for (var i = 0; i < 100; i++) ldr.AddData(i, _grid.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry {Val = i})); ldr.Flush(); for (var i = 0; i < 100; i++) Assert.AreEqual(i + 1, cache.Get(i).Val); // Repeating WithKeepBinary call: valid args. Assert.AreSame(ldr, ldr.WithKeepBinary<int, IBinaryObject>()); // Invalid type args. var ex = Assert.Throws<InvalidOperationException>(() => ldr.WithKeepBinary<string, IBinaryObject>()); Assert.AreEqual( "Can't change type of binary streamer. WithKeepBinary has been called on an instance of " + "binary streamer with incompatible generic arguments.", ex.Message); } } /// <summary> /// Test binarizable receiver. /// </summary> private class StreamReceiverBinarizable : IStreamReceiver<int, int> { /** <inheritdoc /> */ public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries) { cache.PutAll(entries.ToDictionary(x => x.Key, x => x.Value + 1)); } } /// <summary> /// Test binary receiver. /// </summary> [Serializable] private class StreamReceiverKeepBinary : IStreamReceiver<int, IBinaryObject> { /** <inheritdoc /> */ public void Receive(ICache<int, IBinaryObject> cache, ICollection<ICacheEntry<int, IBinaryObject>> entries) { var binary = cache.Ignite.GetBinary(); cache.PutAll(entries.ToDictionary(x => x.Key, x => binary.ToBinary<IBinaryObject>(new BinarizableEntry { Val = x.Value.Deserialize<BinarizableEntry>().Val + 1 }))); } } /// <summary> /// Test serializable receiver. /// </summary> [Serializable] private class StreamReceiverSerializable : IStreamReceiver<int, int> { /** <inheritdoc /> */ public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries) { cache.PutAll(entries.ToDictionary(x => x.Key, x => x.Value + 1)); } } /// <summary> /// Test entry processor. /// </summary> [Serializable] private class EntryProcessorSerializable : ICacheEntryProcessor<int, int, int, int> { /** <inheritdoc /> */ public int Process(IMutableCacheEntry<int, int> entry, int arg) { entry.Value = entry.Key + 1; return 0; } } /// <summary> /// Test entry processor. /// </summary> private class EntryProcessorBinarizable : ICacheEntryProcessor<int, int, int, int>, IBinarizable { /** <inheritdoc /> */ public int Process(IMutableCacheEntry<int, int> entry, int arg) { entry.Value = entry.Key + 1; return 0; } /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { // No-op. } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { // No-op. } } /// <summary> /// Binarizable entry. /// </summary> private class BinarizableEntry { public int Val { get; set; } } /// <summary> /// Container class. /// </summary> private class Container { public Container Inner; } } }
using ExitGames.Client.Photon; using NUnit.Framework; using System; using UnityEngine; namespace Test { /// <summary> /// Contains a number of test cases that use Photon's serialization/deserialization to serialize & deserialize types by-value & by-id, also using class hierarchies. /// NOTE that at the moment the test fixture's SetUp/TearDown has problems with Photon: there is a RegisterType() but no UnregisterType() there. /// You need to comment out some asserts in PhotonRegisterSerializer to make the tests pass. /// </summary> [TestFixture] internal class SerializationTest { public static void SerializeObject(object obj, StreamBuffer outBuffer) { // Use Protocol.ProtocolDefault operations since Protocol's own have built-in size limitations Protocol.ProtocolDefault.Serialize(outBuffer, obj, true); } public static object DeserializeObject(StreamBuffer inBuffer) { // Use Protocol.ProtocolDefault operations since Protocol's own API does not tell us how large the deserialized object is object obj = Protocol.ProtocolDefault.Deserialize(inBuffer, (byte)inBuffer.ReadByte()); return obj; } public abstract class AbstractBaseByValue { } public class ConcreteChildByValue : AbstractBaseByValue { public int a; public int b; public ConcreteChildByValue(int a, int b) { this.a = a; this.b = b; } static byte[] serializationBuffer = new byte[2 * sizeof(int)]; public static short Serialize(StreamBuffer outBuffer, object obj) { ConcreteChildByValue obj2 = (ConcreteChildByValue)obj; int offset = 0; Protocol.Serialize(obj2.a, serializationBuffer, ref offset); Protocol.Serialize(obj2.b, serializationBuffer, ref offset); Assert.AreEqual(offset, serializationBuffer.Length); outBuffer.Write(serializationBuffer, 0, offset); return (short) offset; } static byte[] deserializationBuffer = new byte[2 * sizeof(int)]; public static object Deserialize(StreamBuffer inBuffer, short length) { Assert.IsTrue(deserializationBuffer.Length <= length); inBuffer.Read(deserializationBuffer, 0, deserializationBuffer.Length); int offset = 0; int a; Protocol.Deserialize(out a, deserializationBuffer, ref offset); int b; Protocol.Deserialize(out b, deserializationBuffer, ref offset); Assert.AreEqual(offset, deserializationBuffer.Length); return new ConcreteChildByValue(a, b); } } public abstract class AbstractBaseById { } public class ConcreteChildById : AbstractBaseById { int a, b; public ConcreteChildById(int a, int b) { this.a = a; this.b = b; } } public class NullMembers { public ConcreteChildByValue nullMember1; public ConcreteChildById nullMember2; public int nonNullMember3; public NullMembers(ConcreteChildByValue nullMember1, ConcreteChildById nullMember2, int nonNullMember3) { this.nullMember1 = nullMember1; this.nullMember2 = nullMember2; this.nonNullMember3 = nonNullMember3; } static byte[] serializationBuffer = new byte[64]; public static short Serialize(StreamBuffer outBuffer, object obj) { NullMembers obj2 = (NullMembers)obj; long startPosition = outBuffer.Position; SerializeObject(obj2.nullMember1, outBuffer); SerializeObject(obj2.nullMember1, outBuffer); int offset; byte[] buf = outBuffer.GetBufferAndAdvance(sizeof(int), out offset); Protocol.Serialize(obj2.nonNullMember3, buf, ref offset); return (short) (outBuffer.Position - startPosition); } static byte[] deinitializationBuffer = new byte[2 * sizeof(int)]; public static object Deserialize(StreamBuffer inBuffer, short length) { ConcreteChildByValue nullMember1 = (ConcreteChildByValue) DeserializeObject(inBuffer); ConcreteChildById nullMember2 = (ConcreteChildById) DeserializeObject(inBuffer); int nonNullMember3; int offset; byte[] buf = inBuffer.GetBufferAndAdvance(sizeof(int), out offset); Protocol.Deserialize(out nonNullMember3, buf, ref offset); return new NullMembers(nullMember1, nullMember2, nonNullMember3); } } [SetUp] public void SetUp() { NetworkableId<Type>.Create(null); // Assign IDs for all networkable types NetworkableId<Type>.AddWithId(typeof(AbstractBaseByValue), 128); NetworkableId<Type>.AddWithId(typeof(ConcreteChildByValue), 129); NetworkableId<Type>.AddWithId(typeof(AbstractBaseById), 130); NetworkableId<Type>.AddWithId(typeof(ConcreteChildById), 131); NetworkableId<Type>.AddWithId(typeof(NullMembers), 132); // Items that get networked by ID need to have an ID hierarchy setup NetworkableId<AbstractBaseById>.Create(null); NetworkableId<ConcreteChildById>.Create(typeof(AbstractBaseById)); // Register Photon serializer/deserializer callbacks for the types PhotonRegisterSerializers registerSerializers = new PhotonRegisterSerializers(); registerSerializers.RegisterSerializersForDefaultObjectType(typeof(AbstractBaseByValue)); registerSerializers.RegisterSerializersForValueType(typeof(ConcreteChildByValue)); registerSerializers.RegisterSerializersForDefaultObjectType(typeof(AbstractBaseById)); registerSerializers.RegisterSerializersForIdType(typeof(ConcreteChildById)); registerSerializers.RegisterSerializersForValueType(typeof(NullMembers)); } [TearDown] public void TearDown() { // Unregister Photon serializer/deserializer callbacks for the types PhotonRegisterSerializers registerSerializers = new PhotonRegisterSerializers(); registerSerializers.DeregisterSerializer(typeof(NullMembers)); registerSerializers.DeregisterSerializer(typeof(ConcreteChildById)); registerSerializers.DeregisterSerializer(typeof(AbstractBaseById)); registerSerializers.DeregisterSerializer(typeof(ConcreteChildByValue)); registerSerializers.DeregisterSerializer(typeof(AbstractBaseByValue)); // Deregister types & destroy type registries NetworkableId<Type>.Remove(typeof(NullMembers)); NetworkableId<Type>.Remove(typeof(AbstractBaseById)); NetworkableId<Type>.Remove(typeof(ConcreteChildById)); NetworkableId<AbstractBaseById>.Destroy(); NetworkableId<ConcreteChildById>.Destroy(); NetworkableIdRegistry.DestroyRootRegistry(typeof(AbstractBaseById)); NetworkableId<Type>.Remove(typeof(AbstractBaseByValue)); NetworkableId<Type>.Remove(typeof(ConcreteChildByValue)); NetworkableId<Type>.Destroy(); NetworkableIdRegistry.DestroyRootRegistry(typeof(Type)); } [Test] public void TestSerializationByValue() { ConcreteChildByValue concreteObj = new ConcreteChildByValue(12345678, 87654321); byte[] buffer = Protocol.Serialize(concreteObj); ConcreteChildByValue concreteObj2 = (ConcreteChildByValue) Protocol.Deserialize(buffer); Assert.That(concreteObj.a, Is.EqualTo(concreteObj2.a)); Assert.That(concreteObj.b, Is.EqualTo(concreteObj2.b)); } [Test] public void TestSerializationByValueNullReference() { byte[] buffer = Protocol.Serialize((ConcreteChildByValue)null); ConcreteChildByValue concreteObj2 = (ConcreteChildByValue)Protocol.Deserialize(buffer); Assert.That(concreteObj2, Is.Null); } [Test] public void TestSerializationByValueBaseType() { ConcreteChildByValue concreteObj = new ConcreteChildByValue(12345678, 87654321); byte[] buffer = Protocol.Serialize((AbstractBaseByValue) concreteObj); ConcreteChildByValue concreteObj2 = (ConcreteChildByValue)Protocol.Deserialize(buffer); Assert.That(concreteObj.a, Is.EqualTo(concreteObj2.a)); Assert.That(concreteObj.b, Is.EqualTo(concreteObj2.b)); } [Test] public void TestSerializationById() { ConcreteChildById concreteObj = new ConcreteChildById(12345678, 87654321); NetworkableId<ConcreteChildById>.Add(concreteObj); byte[] buffer = Protocol.Serialize(concreteObj); ConcreteChildById concreteObj2 = (ConcreteChildById)Protocol.Deserialize(buffer); Assert.That(concreteObj2, Is.EqualTo(concreteObj)); NetworkableId<ConcreteChildById>.Remove(concreteObj); } [Test] public void TestSerializationByIdNullReference() { byte[] buffer = Protocol.Serialize((ConcreteChildById) null); ConcreteChildById concreteObj2 = (ConcreteChildById)Protocol.Deserialize(buffer); Assert.That(concreteObj2, Is.Null); } [Test] public void TestSerializationByIdBaseType() { ConcreteChildById concreteObj = new ConcreteChildById(12345678, 87654321); NetworkableId<ConcreteChildById>.Add(concreteObj); byte[] buffer = Protocol.Serialize((AbstractBaseById) concreteObj); ConcreteChildById concreteObj2 = (ConcreteChildById)Protocol.Deserialize(buffer); Assert.That(concreteObj2, Is.EqualTo(concreteObj)); NetworkableId<ConcreteChildById>.Remove(concreteObj); } [Test] public void TestSerializationByValueNullMembers() { NullMembers obj = new NullMembers(null, null, 12345678); byte[] buffer = Protocol.Serialize(obj); NullMembers obj2 = (NullMembers)Protocol.Deserialize(buffer); Assert.That(obj2.nullMember1, Is.EqualTo(obj.nullMember1)); Assert.That(obj2.nullMember2, Is.EqualTo(obj.nullMember2)); Assert.That(obj2.nonNullMember3, Is.EqualTo(obj.nonNullMember3)); } } }
using Saga.Map; using Saga.Packets; using Saga.Structures; using System; using System.Diagnostics; namespace Saga.PrimaryTypes { /// <summary> /// Base object all actors inherit. /// </summary> [Serializable()] public abstract class MapObject : IActorid { #region Private Members /// <summary> /// Stores the position /// </summary> private Point position; /// <summary> /// Contains the session id of the item /// </summary> private uint _id; /// <summary> /// Contains the region id of the item /// </summary> private uint _region; /// <summary> /// Contains the yaw of the item (rotation) /// </summary> private Rotator _Yaw; /// <summary> /// Contains a boolean weather the item can respawn or not /// </summary> private bool _canrespawn = true; #endregion Private Members #region Protected Internal Members /// <summary> /// Contains extra storage (in character this means the characterid) while with /// normal npc's this means modelid /// </summary> protected internal uint _ModelId; /// <summary> /// Contains the zone of the item /// </summary> internal Zone _currentzone; #endregion Protected Internal Members #region Public Members /// <summary> /// Get's the zone of the mapobject /// </summary> public Zone currentzone { get { return _currentzone; } internal set { _currentzone = value; } } /// <summary> /// Get's the yaw of the mapobject /// </summary> public Rotator Yaw { get { return _Yaw; } set { _Yaw = value; } } /// <summary> /// Get's the session id of the mapobject /// </summary> public uint id { get { return _id; } internal set { _id = value; } } /// <summary> /// Get's the session id of the mapobject /// </summary> public uint ModelId { get { return _ModelId; } internal set { _ModelId = value; } } /// <summary> /// Get's the session id of the mapobject /// </summary> public uint region { get { return _region; } internal set { _region = value; } } /// <summary> /// Get's whether the mob can respawn /// </summary> public bool CanRespawn { get { return _canrespawn; } internal set { _canrespawn = value; } } /// <summary> /// Get's or set's position of the object /// </summary> public Point Position { get { return this.position; } set { this.position = value; } } #endregion Public Members #region Public Methods /// <summary> /// Internal function to show the object /// </summary> /// <param name="character">Character who to show the packet</param> public abstract void ShowObject(Character character); /// <summary> /// Internal function to hide the object /// </summary> /// <param name="character"></param> public virtual void HideObject(Character character) { try { //Actor disappears SMSG_ACTORDELETE spkt2 = new SMSG_ACTORDELETE(); spkt2.ActorID = this.id; spkt2.SessionId = character.id; character.client.Send((byte[])spkt2); } catch (Exception) { Trace.TraceError("Error sending delete actor"); } } /// <summary> /// Registers a charcter on the associated actor manager /// </summary> public virtual void OnRegister() { this.currentzone.Regiontree.Subscribe(this); Trace.WriteLine("DEBUG", string.Format("MapObject registered: {0:X8} {1}", this.region, this.ToString())); } /// <summary> /// Deregisters a character to the associated actor manager /// </summary> public virtual void OnDeregister() { this.currentzone.Regiontree.Unsubscribe(this); } /// <summary> /// Event called when a actor appears /// </summary> /// <param name="character"></param> public virtual void Appears(Character character) { } /// <summary> /// Event called when a actor disappears /// </summary> public virtual void Disappear(Character character) { } /// <summary> /// Event called when spawning the actor /// </summary> public virtual void OnSpawn() { } /// <summary> /// Event called when casting a spell /// </summary> /// <param name="source">Source actor using the skill</param> /// <param name="e">Spell argument</param> public virtual void OnSkillUsedByTarget(MapObject source, SkillBaseEventArgs e) { } /// <summary> /// Event called when actor dies /// </summary> /// <param name="d">Actor who's responsible for the death</param> public virtual void OnDie(MapObject d) { } /// <summary> /// Occurs when seeing a enemy die /// </summary> /// <param name="enemy"></param> public virtual void OnEnemyDie(MapObject enemy) { } /// <summary> /// Event called when the actor is beeing clicked /// </summary> public virtual void OnClick(Character target) { } /// <summary> /// Event called when the actor is loaded /// </summary> public virtual void OnLoad() { } /// <summary> /// Event called when the actor is initialized /// </summary> /// <param name="startpoint"></param> public virtual void OnInitialize(Point startpoint) { this.position = startpoint; this.position.z += 15; } #endregion Public Methods #region Public Static Methods /// <summary> /// Checks if the supplied mapobject is a character instance /// </summary> /// <param name="instance">Instance to check</param> /// <returns>True if the object is a player</returns> public static bool IsPlayer(MapObject instance) { return instance.id < Regiontree.PlayerBorder; } /// <summary> /// Checks if the supplied mapobject is a mapitem instance /// </summary> /// <param name="instance">Instance to check</param> /// <returns>True if the object is a mapitem</returns> public static bool IsMapItem(MapObject instance) { return instance.id < Regiontree.MapItemBorder; } /// <summary> /// Checks if the supplied mapobject is a npc instance /// </summary> /// <param name="instance">Instance to check</param> /// <returns>True if the object is a npc (this includes monsters)</returns> public static bool IsNpc(MapObject instance) { return instance.id >= Regiontree.MapItemBorder; } /// <summary> /// Checks if the supplied mapobject is a monster instance /// </summary> /// <param name="instance">Instance to check</param> /// <returns>True if the object is a monster</returns> public static bool IsMonster(MapObject instance) { return IsNpc(instance) && instance.ModelId >= Regiontree.NpcIndexBorder; } /// <summary>IActorid /// Checks if the supplied mapobject is a regulair npc instance /// </summary> /// <param name="instance">Instance to check</param> /// <returns>True if the object is a regulair npc</returns> public static bool IsNotMonster(MapObject instance) { return IsNpc(instance) && (instance.ModelId < Regiontree.NpcIndexBorder); } #endregion Public Static Methods #region Updates /// <summary> /// Event for locking updates for the current object /// </summary> public virtual void Lock() { } /// <summary> /// Event for releasing updates for the current object /// </summary> public virtual void Release() { } /// <summary> /// Event for sending updates to the specified character /// </summary> /// <param name="character"></param> public virtual void Flush(Character character) { } #endregion Updates #region IActorid Members uint IActorid.Id { get { return this._id; } } #endregion IActorid Members public override string ToString() { return string.Format("MapObject id:{0}", this.ModelId); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>LifeEvent</c> resource.</summary> public sealed partial class LifeEventName : gax::IResourceName, sys::IEquatable<LifeEventName> { /// <summary>The possible contents of <see cref="LifeEventName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/lifeEvents/{life_event_id}</c>. /// </summary> CustomerLifeEvent = 1, } private static gax::PathTemplate s_customerLifeEvent = new gax::PathTemplate("customers/{customer_id}/lifeEvents/{life_event_id}"); /// <summary>Creates a <see cref="LifeEventName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="LifeEventName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static LifeEventName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new LifeEventName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="LifeEventName"/> with the pattern <c>customers/{customer_id}/lifeEvents/{life_event_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lifeEventId">The <c>LifeEvent</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="LifeEventName"/> constructed from the provided ids.</returns> public static LifeEventName FromCustomerLifeEvent(string customerId, string lifeEventId) => new LifeEventName(ResourceNameType.CustomerLifeEvent, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), lifeEventId: gax::GaxPreconditions.CheckNotNullOrEmpty(lifeEventId, nameof(lifeEventId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="LifeEventName"/> with pattern /// <c>customers/{customer_id}/lifeEvents/{life_event_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lifeEventId">The <c>LifeEvent</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="LifeEventName"/> with pattern /// <c>customers/{customer_id}/lifeEvents/{life_event_id}</c>. /// </returns> public static string Format(string customerId, string lifeEventId) => FormatCustomerLifeEvent(customerId, lifeEventId); /// <summary> /// Formats the IDs into the string representation of this <see cref="LifeEventName"/> with pattern /// <c>customers/{customer_id}/lifeEvents/{life_event_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lifeEventId">The <c>LifeEvent</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="LifeEventName"/> with pattern /// <c>customers/{customer_id}/lifeEvents/{life_event_id}</c>. /// </returns> public static string FormatCustomerLifeEvent(string customerId, string lifeEventId) => s_customerLifeEvent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(lifeEventId, nameof(lifeEventId))); /// <summary>Parses the given resource name string into a new <see cref="LifeEventName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/lifeEvents/{life_event_id}</c></description></item> /// </list> /// </remarks> /// <param name="lifeEventName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="LifeEventName"/> if successful.</returns> public static LifeEventName Parse(string lifeEventName) => Parse(lifeEventName, false); /// <summary> /// Parses the given resource name string into a new <see cref="LifeEventName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/lifeEvents/{life_event_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="lifeEventName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="LifeEventName"/> if successful.</returns> public static LifeEventName Parse(string lifeEventName, bool allowUnparsed) => TryParse(lifeEventName, allowUnparsed, out LifeEventName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="LifeEventName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/lifeEvents/{life_event_id}</c></description></item> /// </list> /// </remarks> /// <param name="lifeEventName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="LifeEventName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string lifeEventName, out LifeEventName result) => TryParse(lifeEventName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="LifeEventName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/lifeEvents/{life_event_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="lifeEventName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="LifeEventName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string lifeEventName, bool allowUnparsed, out LifeEventName result) { gax::GaxPreconditions.CheckNotNull(lifeEventName, nameof(lifeEventName)); gax::TemplatedResourceName resourceName; if (s_customerLifeEvent.TryParseName(lifeEventName, out resourceName)) { result = FromCustomerLifeEvent(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(lifeEventName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private LifeEventName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string lifeEventId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; LifeEventId = lifeEventId; } /// <summary> /// Constructs a new instance of a <see cref="LifeEventName"/> class from the component parts of pattern /// <c>customers/{customer_id}/lifeEvents/{life_event_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lifeEventId">The <c>LifeEvent</c> ID. Must not be <c>null</c> or empty.</param> public LifeEventName(string customerId, string lifeEventId) : this(ResourceNameType.CustomerLifeEvent, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), lifeEventId: gax::GaxPreconditions.CheckNotNullOrEmpty(lifeEventId, nameof(lifeEventId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>LifeEvent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LifeEventId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerLifeEvent: return s_customerLifeEvent.Expand(CustomerId, LifeEventId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as LifeEventName); /// <inheritdoc/> public bool Equals(LifeEventName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(LifeEventName a, LifeEventName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(LifeEventName a, LifeEventName b) => !(a == b); } public partial class LifeEvent { /// <summary> /// <see cref="gagvr::LifeEventName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal LifeEventName ResourceNameAsLifeEventName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::LifeEventName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::LifeEventName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> internal LifeEventName LifeEventName { get => string.IsNullOrEmpty(Name) ? null : gagvr::LifeEventName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::LifeEventName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> internal LifeEventName ParentAsLifeEventName { get => string.IsNullOrEmpty(Parent) ? null : gagvr::LifeEventName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace System.Security.Cryptography { public abstract class SymmetricAlgorithm : IDisposable { protected SymmetricAlgorithm() { ModeValue = CipherMode.CBC; PaddingValue = PaddingMode.PKCS7; } public virtual int BlockSize { get { return BlockSizeValue; } set { bool validatedByZeroSkipSizeKeySizes; if (!value.IsLegalSize(this.LegalBlockSizes, out validatedByZeroSkipSizeKeySizes)) throw new CryptographicException(SR.Cryptography_InvalidBlockSize); if (BlockSizeValue == value && !validatedByZeroSkipSizeKeySizes) // The !validatedByZeroSkipSizeKeySizes check preserves a very obscure back-compat behavior. return; BlockSizeValue = value; IVValue = null; return; } } public virtual byte[] IV { get { if (IVValue == null) GenerateIV(); return IVValue.CloneByteArray(); } set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.Length != this.BlockSize / 8) throw new CryptographicException(SR.Cryptography_InvalidIVSize); IVValue = value.CloneByteArray(); } } public virtual byte[] Key { get { if (KeyValue == null) GenerateKey(); return KeyValue.CloneByteArray(); } set { if (value == null) throw new ArgumentNullException(nameof(value)); long bitLength = value.Length * 8L; if (bitLength > int.MaxValue || !ValidKeySize((int)bitLength)) throw new CryptographicException(SR.Cryptography_InvalidKeySize); // must convert bytes to bits this.KeySize = (int)bitLength; KeyValue = value.CloneByteArray(); } } public virtual int KeySize { get { return KeySizeValue; } set { if (!ValidKeySize(value)) throw new CryptographicException(SR.Cryptography_InvalidKeySize); KeySizeValue = value; KeyValue = null; } } public virtual KeySizes[] LegalBlockSizes { get { // Desktop compat: No null check is performed. return (KeySizes[])LegalBlockSizesValue.Clone(); } } public virtual KeySizes[] LegalKeySizes { get { // Desktop compat: No null check is performed. return (KeySizes[])LegalKeySizesValue.Clone(); } } public virtual CipherMode Mode { get { return ModeValue; } set { if (!(value == CipherMode.CBC || value == CipherMode.ECB)) throw new CryptographicException(SR.Cryptography_InvalidCipherMode); ModeValue = value; } } public virtual PaddingMode Padding { get { return PaddingValue; } set { if (!(value == PaddingMode.None || value == PaddingMode.PKCS7 || value == PaddingMode.Zeros)) throw new CryptographicException(SR.Cryptography_InvalidPaddingMode); PaddingValue = value; } } public virtual ICryptoTransform CreateDecryptor() { return CreateDecryptor(Key, IV); } public abstract ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV); public virtual ICryptoTransform CreateEncryptor() { return CreateEncryptor(Key, IV); } public abstract ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (KeyValue != null) { Array.Clear(KeyValue, 0, KeyValue.Length); KeyValue = null; } if (IVValue != null) { Array.Clear(IVValue, 0, IVValue.Length); IVValue = null; } } } public abstract void GenerateIV(); public abstract void GenerateKey(); private bool ValidKeySize(int bitLength) { KeySizes[] validSizes = this.LegalKeySizes; if (validSizes == null) return false; return bitLength.IsLegalSize(validSizes); } protected CipherMode ModeValue; protected PaddingMode PaddingValue; protected byte[] KeyValue; protected byte[] IVValue; protected int BlockSizeValue; protected int KeySizeValue; protected KeySizes[] LegalBlockSizesValue; protected KeySizes[] LegalKeySizesValue; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using EloBuddy; using EloBuddy.SDK; using SharpDX; namespace DilmaAndFiora.Evade { public enum CollisionObjectTypes { Minion, Champions, YasuoWall, } internal class FastPredResult { public Vector2 CurrentPos; public bool IsMoving; public Vector2 PredictedPos; } internal class DetectedCollision { public float Diff; public float Distance; public Vector2 Position; public CollisionObjectTypes Type; public Obj_AI_Base Unit; } internal static class Collision { private static int WallCastT; private static Vector2 YasuoWallCastedPos; public static void Initialize() { } static Collision() { Obj_AI_Base.OnProcessSpellCast += OnProcessSpellCast; } static void OnProcessSpellCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (sender.IsValid && sender.Team == ObjectManager.Player.Team && args.SData.Name == "YasuoWMovingWall") { WallCastT = Environment.TickCount; YasuoWallCastedPos = sender.ServerPosition.To2D(); } } public static Vector3[] CutPath(Vector3[] path, float distance) { var result = new List<Vector3>(); var Distance = distance; if (path.Length > 0) { result.Add(path.First()); } for (var i = 0; i < path.Length - 1; i++) { var dist = path[i].Distance(path[i + 1]); if (dist > Distance) { result.Add(path[i] + Distance * (path[i + 1] - path[i]).Normalized()); break; } else { result.Add(path[i + 1]); } Distance -= dist; } return result.Count > 0 ? result.ToArray() : new List<Vector3> { path.Last() }.ToArray(); } public static FastPredResult FastPrediction(Vector2 from, Obj_AI_Base unit, int delay, int speed) { var tDelay = delay / 1000f + (from.Distance(unit) / speed); var d = tDelay * unit.MoveSpeed; var path = unit.Path; if (path.Length > d) { return new FastPredResult { IsMoving = true, CurrentPos = unit.ServerPosition.To2D(), PredictedPos = CutPath(path, d)[0].To2D(), }; } if (path.Count() == 0) { return new FastPredResult { IsMoving = false, CurrentPos = unit.ServerPosition.To2D(), PredictedPos = unit.ServerPosition.To2D(), }; } return new FastPredResult { IsMoving = false, CurrentPos = path[path.Count() - 1].To2D(), PredictedPos = path[path.Count() - 1].To2D(), }; } public static Vector2 GetCollisionPoint(Skillshot skillshot) { var collisions = new List<DetectedCollision>(); var from = skillshot.GetMissilePosition(0); skillshot.ForceDisabled = false; foreach (var cObject in skillshot.SpellData.CollisionObjects) { switch (cObject) { case CollisionObjectTypes.Minion: foreach (var minion in ObjectManager.Get<Obj_AI_Base>().Where(m => m.IsMinion)) { var pred = FastPrediction( from, minion, Math.Max(0, skillshot.SpellData.Delay - (Environment.TickCount - skillshot.StartTick)), skillshot.SpellData.MissileSpeed); var pos = pred.PredictedPos; var w = skillshot.SpellData.RawRadius + (!pred.IsMoving ? (minion.BoundingRadius - 15) : 0) - pos.Distance(from, skillshot.End, true); if (w > 0) { collisions.Add( new DetectedCollision { Position = pos.ProjectOn(skillshot.End, skillshot.Start).LinePoint + skillshot.Direction * 30, Unit = minion, Type = CollisionObjectTypes.Minion, Distance = pos.Distance(from), Diff = w, }); } } break; case CollisionObjectTypes.Champions: foreach (var hero in ObjectManager.Get<AIHeroClient>() .Where( h => (h.IsValidTarget(1200) && h.Team == ObjectManager.Player.Team && !h.IsMe || h.Team != ObjectManager.Player.Team))) { var pred = FastPrediction( from, hero, Math.Max(0, skillshot.SpellData.Delay - (Environment.TickCount - skillshot.StartTick)), skillshot.SpellData.MissileSpeed); var pos = pred.PredictedPos; var w = skillshot.SpellData.RawRadius + 30 - pos.Distance(from, skillshot.End, true); if (w > 0) { collisions.Add( new DetectedCollision { Position = pos.ProjectOn(skillshot.End, skillshot.Start).LinePoint + skillshot.Direction * 30, Unit = hero, Type = CollisionObjectTypes.Minion, Distance = pos.Distance(from), Diff = w, }); } } break; case CollisionObjectTypes.YasuoWall: if ( !ObjectManager.Get<AIHeroClient>() .Any( hero => hero.IsValidTarget(float.MaxValue) && hero.Team == ObjectManager.Player.Team && hero.ChampionName == "Yasuo")) { break; } GameObject wall = null; foreach (var gameObject in ObjectManager.Get<GameObject>()) { if (gameObject.IsValid && Regex.IsMatch( gameObject.Name, "_w_windwall.\\.troy", RegexOptions.IgnoreCase)) { wall = gameObject; } } if (wall == null) { break; } var level = wall.Name.Substring(wall.Name.Length - 6, 1); var wallWidth = (300 + 50 * Convert.ToInt32(level)); var wallDirection = (wall.Position.To2D() - YasuoWallCastedPos).Normalized().Perpendicular(); var wallStart = wall.Position.To2D() + wallWidth / 2 * wallDirection; var wallEnd = wallStart - wallWidth * wallDirection; var wallPolygon = new Geometry.Rectangle(wallStart, wallEnd, 75).ToPolygon(); var intersection = new Vector2(); var intersections = new List<Vector2>(); for (var i = 0; i < wallPolygon.Points.Count; i++) { var inter = wallPolygon.Points[i].Intersection( wallPolygon.Points[i != wallPolygon.Points.Count - 1 ? i + 1 : 0], from, skillshot.End); if (inter.Intersects) { intersections.Add(inter.Point); } } if (intersections.Count > 0) { intersection = intersections.OrderBy(item => item.Distance(from)).ToList()[0]; var collisionT = Environment.TickCount + Math.Max( 0, skillshot.SpellData.Delay - (Environment.TickCount - skillshot.StartTick)) + 100 + (1000 * intersection.Distance(from)) / skillshot.SpellData.MissileSpeed; if (collisionT - WallCastT < 4000) { if (skillshot.SpellData.Type != SkillShotType.SkillshotMissileLine) { skillshot.ForceDisabled = true; } return intersection; } } break; } } Vector2 result; if (collisions.Count > 0) { result = collisions.OrderBy(c => c.Distance).ToList()[0].Position; } else { result = new Vector2(); } return result; } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Security { using System.Runtime.InteropServices; using System.ServiceModel.Channels; using System.ServiceModel; using System.ServiceModel.Diagnostics; using System.Diagnostics; using System.Collections.Generic; using System.Text; using System.Threading; using System.Globalization; using System.ComponentModel; using System.Security.Principal; using System.IdentityModel.Tokens; using System.Net; using System.IdentityModel; using System.IdentityModel.Selectors; using System.Security.Authentication.ExtendedProtection; using IMD = System.IdentityModel.Diagnostics; using DiagnosticUtility = System.ServiceModel.DiagnosticUtility; using SR = System.ServiceModel.SR; internal sealed class WindowsSspiNegotiation : ISspiNegotiation { const int DefaultMaxPromptAttempts = 1; SspiContextFlags contextFlags; SafeFreeCredentials credentialsHandle; bool disposed = false; bool doMutualAuth; TokenImpersonationLevel impersonationLevel; bool isCompleted; bool isServer; LifeSpan lifespan; string protocolName; SafeDeleteContext securityContext; string servicePrincipalName; SecSizes sizes; Object syncObject = new Object(); int tokenSize; bool interactiveNegoLogonEnabled = true; string clientPackageName; bool saveClientCredentialsOnSspiUi = true; bool allowNtlm; int MaxPromptAttempts = 0; /// <summary> /// Client side ctor /// </summary> internal WindowsSspiNegotiation(string package, SafeFreeCredentials credentialsHandle, TokenImpersonationLevel impersonationLevel, string servicePrincipalName, bool doMutualAuth, bool interactiveLogonEnabled, bool ntlmEnabled) : this(false, package, credentialsHandle, impersonationLevel, servicePrincipalName, doMutualAuth, interactiveLogonEnabled, ntlmEnabled) { } /// <summary> /// Server side ctor /// </summary> internal WindowsSspiNegotiation(string package, SafeFreeCredentials credentialsHandle, string defaultServiceBinding) : this(true, package, credentialsHandle, TokenImpersonationLevel.Delegation, defaultServiceBinding, false, false, true) { } WindowsSspiNegotiation(bool isServer, string package, SafeFreeCredentials credentialsHandle, TokenImpersonationLevel impersonationLevel, string servicePrincipalName, bool doMutualAuth, bool interactiveLogonEnabled, bool ntlmEnabled) { this.tokenSize = SspiWrapper.GetVerifyPackageInfo(package).MaxToken; this.isServer = isServer; this.servicePrincipalName = servicePrincipalName; this.securityContext = null; if (isServer) { this.impersonationLevel = TokenImpersonationLevel.Delegation; this.doMutualAuth = false; } else { this.impersonationLevel = impersonationLevel; this.doMutualAuth = doMutualAuth; this.interactiveNegoLogonEnabled = interactiveLogonEnabled; this.clientPackageName = package; this.allowNtlm = ntlmEnabled; } this.credentialsHandle = credentialsHandle; } public DateTime ExpirationTimeUtc { get { ThrowIfDisposed(); if (this.LifeSpan == null) { return SecurityUtils.MaxUtcDateTime; } else { return this.LifeSpan.ExpiryTimeUtc; } } } public bool IsCompleted { get { ThrowIfDisposed(); return this.isCompleted; } } public bool IsDelegationFlag { get { ThrowIfDisposed(); return (this.contextFlags & SspiContextFlags.Delegate) != 0; } } public bool IsIdentifyFlag { get { ThrowIfDisposed(); return (this.contextFlags & (this.isServer ? SspiContextFlags.AcceptIdentify : SspiContextFlags.InitIdentify)) != 0; } } public bool IsMutualAuthFlag { get { ThrowIfDisposed(); return (this.contextFlags & SspiContextFlags.MutualAuth) != 0; } } public bool IsValidContext { get { return (this.securityContext != null && this.securityContext.IsInvalid == false); } } public string KeyEncryptionAlgorithm { get { return SecurityAlgorithms.WindowsSspiKeyWrap; } } public LifeSpan LifeSpan { get { ThrowIfDisposed(); if (this.lifespan == null) { LifeSpan tmpLifeSpan = (LifeSpan)SspiWrapper.QueryContextAttributes(this.securityContext, ContextAttribute.Lifespan); if (IsCompleted) { // cache it only when it's completed this.lifespan = tmpLifeSpan; } return tmpLifeSpan; } return this.lifespan; } } public string ProtocolName { get { ThrowIfDisposed(); if (this.protocolName == null) { NegotiationInfoClass negotiationInfo = SspiWrapper.QueryContextAttributes(this.securityContext, ContextAttribute.NegotiationInfo) as NegotiationInfoClass; if (IsCompleted) { // cache it only when it's completed this.protocolName = negotiationInfo.AuthenticationPackage; } return negotiationInfo.AuthenticationPackage; } return this.protocolName; } } public string ServicePrincipalName { get { ThrowIfDisposed(); return this.servicePrincipalName; } } SecSizes SecuritySizes { get { ThrowIfDisposed(); if (this.sizes == null) { SecSizes tmpSizes = (SecSizes)SspiWrapper.QueryContextAttributes(this.securityContext, ContextAttribute.Sizes); if (IsCompleted) { // cache it only when it's completed this.sizes = tmpSizes; } return tmpSizes; } return this.sizes; } } public string GetRemoteIdentityName() { if (!this.isServer) { return this.servicePrincipalName; } if (IsValidContext) { using (SafeCloseHandle contextToken = GetContextToken()) { using (WindowsIdentity windowsIdentity = new WindowsIdentity(contextToken.DangerousGetHandle(), this.ProtocolName)) { return windowsIdentity.Name; } } } return String.Empty; } public byte[] Decrypt(byte[] encryptedContent) { if (encryptedContent == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encryptedContent"); ThrowIfDisposed(); SecurityBuffer[] securityBuffer = new SecurityBuffer[2]; securityBuffer[0] = new SecurityBuffer(encryptedContent, 0, encryptedContent.Length, BufferType.Stream); securityBuffer[1] = new SecurityBuffer(0, BufferType.Data); int errorCode = SspiWrapper.DecryptMessage(this.securityContext, securityBuffer, 0, true); if (errorCode != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(errorCode)); } for (int i = 0; i < securityBuffer.Length; ++i) { if (securityBuffer[i].type == BufferType.Data) { return securityBuffer[i].token; } } OnBadData(); return null; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public byte[] Encrypt(byte[] input) { if (input == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("input"); ThrowIfDisposed(); SecurityBuffer[] securityBuffer = new SecurityBuffer[3]; byte[] tokenBuffer = DiagnosticUtility.Utility.AllocateByteArray(SecuritySizes.SecurityTrailer); securityBuffer[0] = new SecurityBuffer(tokenBuffer, 0, tokenBuffer.Length, BufferType.Token); byte[] dataBuffer = DiagnosticUtility.Utility.AllocateByteArray(input.Length); Buffer.BlockCopy(input, 0, dataBuffer, 0, input.Length); securityBuffer[1] = new SecurityBuffer(dataBuffer, 0, dataBuffer.Length, BufferType.Data); byte[] paddingBuffer = DiagnosticUtility.Utility.AllocateByteArray(SecuritySizes.BlockSize); securityBuffer[2] = new SecurityBuffer(paddingBuffer, 0, paddingBuffer.Length, BufferType.Padding); int errorCode = SspiWrapper.EncryptMessage(this.securityContext, securityBuffer, 0); if (errorCode != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(errorCode)); } int tokenLen = 0; int paddingLen = 0; for (int i = 0; i < securityBuffer.Length; ++i) { if (securityBuffer[i].type == BufferType.Token) tokenLen = securityBuffer[i].size; else if (securityBuffer[i].type == BufferType.Padding) paddingLen = securityBuffer[i].size; } byte[] encryptedData = DiagnosticUtility.Utility.AllocateByteArray(checked(tokenLen + dataBuffer.Length + paddingLen)); Buffer.BlockCopy(tokenBuffer, 0, encryptedData, 0, tokenLen); Buffer.BlockCopy(dataBuffer, 0, encryptedData, tokenLen, dataBuffer.Length); Buffer.BlockCopy(paddingBuffer, 0, encryptedData, tokenLen + dataBuffer.Length, paddingLen); return encryptedData; } public byte[] GetOutgoingBlob(byte[] incomingBlob, ChannelBinding channelbinding, ExtendedProtectionPolicy protectionPolicy) { ThrowIfDisposed(); int statusCode = 0; // use the confidentiality option to ensure we can encrypt messages SspiContextFlags requestedFlags = SspiContextFlags.Confidentiality | SspiContextFlags.ReplayDetect | SspiContextFlags.SequenceDetect; if (this.doMutualAuth) { requestedFlags |= SspiContextFlags.MutualAuth; } if (this.impersonationLevel == TokenImpersonationLevel.Delegation) { requestedFlags |= SspiContextFlags.Delegate; } else if (this.isServer == false && this.impersonationLevel == TokenImpersonationLevel.Identification) { requestedFlags |= SspiContextFlags.InitIdentify; } else if (this.isServer == false && this.impersonationLevel == TokenImpersonationLevel.Anonymous) { requestedFlags |= SspiContextFlags.InitAnonymous; } ExtendedProtectionPolicyHelper policyHelper = new ExtendedProtectionPolicyHelper(channelbinding, protectionPolicy); if (isServer) { if (policyHelper.PolicyEnforcement == PolicyEnforcement.Always && policyHelper.ChannelBinding == null && policyHelper.ProtectionScenario != ProtectionScenario.TrustedProxy) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SecurityChannelBindingMissing))); } if (policyHelper.PolicyEnforcement == PolicyEnforcement.WhenSupported) { requestedFlags |= SspiContextFlags.ChannelBindingAllowMissingBindings; } if (policyHelper.ProtectionScenario == ProtectionScenario.TrustedProxy) { requestedFlags |= SspiContextFlags.ChannelBindingProxyBindings; } } List<SecurityBuffer> list = new List<SecurityBuffer>(2); if (incomingBlob != null) { list.Add(new SecurityBuffer(incomingBlob, BufferType.Token)); } // when deciding if the channel binding should be added to the security buffer // it is necessary to differentiate between client and server. // Server rules were added to policyHelper as they are shared with Kerb and I want them consistent // Client adds if not null. if (this.isServer) { if (policyHelper.ShouldAddChannelBindingToASC()) { list.Add(new SecurityBuffer(policyHelper.ChannelBinding)); } } else { if (policyHelper.ChannelBinding != null) { list.Add(new SecurityBuffer(policyHelper.ChannelBinding)); } } SecurityBuffer[] inSecurityBuffer = null; if (list.Count > 0) { inSecurityBuffer = list.ToArray(); } SecurityBuffer outSecurityBuffer = new SecurityBuffer(this.tokenSize, BufferType.Token); if (!this.isServer) { //client session statusCode = SspiWrapper.InitializeSecurityContext(this.credentialsHandle, ref this.securityContext, this.servicePrincipalName, requestedFlags, Endianness.Network, inSecurityBuffer, outSecurityBuffer, ref this.contextFlags); } else { // server session //This check is to save an unnecessary ASC call. bool isServerSecurityContextNull = this.securityContext == null; SspiContextFlags serverContextFlags = this.contextFlags; statusCode = SspiWrapper.AcceptSecurityContext(this.credentialsHandle, ref this.securityContext, requestedFlags, Endianness.Network, inSecurityBuffer, outSecurityBuffer, ref this.contextFlags); if (statusCode == (int)SecurityStatus.InvalidToken && !isServerSecurityContextNull) { // Call again into ASC after deleting the Securitycontext. If this securitycontext is not deleted // then when the client sends NTLM blob the service will treat it as Nego2blob and will fail to authenticate the client. this.contextFlags = serverContextFlags; CloseContext(); statusCode = SspiWrapper.AcceptSecurityContext(this.credentialsHandle, ref this.securityContext, requestedFlags, Endianness.Network, inSecurityBuffer, outSecurityBuffer, ref this.contextFlags); } } if (DiagnosticUtility.ShouldTraceInformation) { IMD.SecurityTraceRecordHelper.TraceChannelBindingInformation(policyHelper, this.isServer, channelbinding); } if ((statusCode & unchecked((int)0x80000000)) != 0) { if (!this.isServer && this.interactiveNegoLogonEnabled && SecurityUtils.IsOSGreaterThanOrEqualToWin7() && SspiWrapper.IsSspiPromptingNeeded((uint)statusCode) && SspiWrapper.IsNegotiateExPackagePresent()) { // If we have prompted enough number of times (DefaultMaxPromptAttempts) with wrong credentials, then we do not prompt again and throw. if (MaxPromptAttempts >= DefaultMaxPromptAttempts) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode, SR.GetString(SR.InvalidClientCredentials))); } IntPtr ppAuthIdentity = IntPtr.Zero; uint errorCode = SspiWrapper.SspiPromptForCredential(this.servicePrincipalName, this.clientPackageName, out ppAuthIdentity, ref this.saveClientCredentialsOnSspiUi); if (errorCode == (uint)CredentialStatus.Success) { IntPtr ppNewAuthIdentity = IntPtr.Zero; if (!this.allowNtlm) { // When Ntlm is explicitly disabled we don't want the collected //creds from the Kerb/NTLM tile to be used for NTLM auth. uint status = UnsafeNativeMethods.SspiExcludePackage(ppAuthIdentity, "NTLM", out ppNewAuthIdentity); } else { ppNewAuthIdentity = ppAuthIdentity; } this.credentialsHandle = SspiWrapper.AcquireCredentialsHandle(this.clientPackageName, CredentialUse.Outbound, ref ppNewAuthIdentity); if (IntPtr.Zero != ppNewAuthIdentity) { UnsafeNativeMethods.SspiFreeAuthIdentity(ppNewAuthIdentity); } CloseContext(); MaxPromptAttempts++; return this.GetOutgoingBlob(null, channelbinding, protectionPolicy); } else { // Call into SspiPromptForCredential had an error. Time to throw. if (IntPtr.Zero != ppAuthIdentity) { UnsafeNativeMethods.SspiFreeAuthIdentity(ppAuthIdentity); } CloseContext(); this.isCompleted = true; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception((int)errorCode, SR.GetString(SR.SspiErrorOrInvalidClientCredentials))); } } CloseContext(); this.isCompleted = true; if (!this.isServer && (statusCode == (int)SecurityStatus.TargetUnknown || statusCode == (int)SecurityStatus.WrongPrincipal)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode, SR.GetString(SR.IncorrectSpnOrUpnSpecified, this.servicePrincipalName))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(statusCode, SR.GetString(SR.InvalidSspiNegotiation))); } } if (DiagnosticUtility.ShouldTraceInformation) { if (this.isServer) { SecurityTraceRecordHelper.TraceServiceOutgoingSpnego(this); } else { SecurityTraceRecordHelper.TraceClientOutgoingSpnego(this); } } if (statusCode == (int)SecurityStatus.OK) { // we're done this.isCompleted = true; // These must all be true to check service binding // 1. we are the service (listener) // 2. caller is not anonymous // 3. protocol is not Kerberos // 4. policy is set to check service binding // if (isServer && ((this.contextFlags & SspiContextFlags.AcceptAnonymous) == 0) && (string.Compare(this.ProtocolName, NegotiationInfoClass.Kerberos, StringComparison.OrdinalIgnoreCase) != 0) && policyHelper.ShouldCheckServiceBinding) { // in the server case the servicePrincipalName is the defaultServiceBinding if (DiagnosticUtility.ShouldTraceInformation) { string serviceBindingNameSentByClient; SspiWrapper.QuerySpecifiedTarget(securityContext, out serviceBindingNameSentByClient); IMD.SecurityTraceRecordHelper.TraceServiceNameBindingOnServer( serviceBindingNameSentByClient, this.servicePrincipalName, policyHelper.ServiceNameCollection); } policyHelper.CheckServiceBinding(this.securityContext, this.servicePrincipalName); } } else { // we need to continue } return outSecurityBuffer.token; } public void ImpersonateContext() { ThrowIfDisposed(); if (!IsValidContext) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception((int)SecurityStatus.InvalidHandle)); } SspiWrapper.ImpersonateSecurityContext(this.securityContext); } internal void CloseContext() { ThrowIfDisposed(); try { if (this.securityContext != null) { this.securityContext.Close(); } } finally { this.securityContext = null; } } private void Dispose(bool disposing) { lock (this.syncObject) { if (this.disposed == false) { if (disposing) { this.CloseContext(); } // set to null any references that aren't finalizable this.protocolName = null; this.servicePrincipalName = null; this.sizes = null; this.disposed = true; } } } internal SafeCloseHandle GetContextToken() { if (!IsValidContext) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception((int)SecurityStatus.InvalidHandle)); } SafeCloseHandle token; SecurityStatus status = (SecurityStatus)SspiWrapper.QuerySecurityContextToken(this.securityContext, out token); if (status != SecurityStatus.OK) { Utility.CloseInvalidOutSafeHandle(token); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception((int)status)); } return token; } void OnBadData() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.BadData))); } void ThrowIfDisposed() { lock (this.syncObject) { if (this.disposed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(null)); } } } } }
namespace Microsoft.Protocols.TestSuites.MS_ASAIRS { using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.Common.DataStructures; using Microsoft.Protocols.TestTools; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using DataStructures = Microsoft.Protocols.TestSuites.Common.DataStructures; using Request = Microsoft.Protocols.TestSuites.Common.Request; /// <summary> /// A static class contains all helper methods used in test cases. /// </summary> internal static class TestSuiteHelper { #region Build command request /// <summary> /// private field for seed initialize to random number. /// </summary> private static int seek = new Random().Next(0, 100000); /// <summary> /// Get client id for send mail /// </summary> /// <returns>The client id</returns> public static string GetClientId() { return (++seek).ToString(); } /// <summary> /// Build a Sync command request. /// </summary> /// <param name="syncKey">The current sync key.</param> /// <param name="collectionId">The collection id which to sync with.</param> /// <param name="commands">The sync commands.</param> /// <param name="bodyPreferences">The bodyPreference in the options element.</param> /// <param name="bodyPartPreferences">The bodyPartPreference in the options element.</param> /// <returns>A Sync command request.</returns> internal static SyncRequest CreateSyncRequest(string syncKey, string collectionId, object[] commands, Request.BodyPreference[] bodyPreferences, Request.BodyPartPreference[] bodyPartPreferences) { SyncRequest request = new SyncRequest { RequestData = { Collections = new Request.SyncCollection[] { new Request.SyncCollection() { SyncKey = syncKey, CollectionId = collectionId } } } }; request.RequestData.Collections[0].Commands = commands; List<object> items = new List<object>(); List<Request.ItemsChoiceType1> itemsElementName = new List<Request.ItemsChoiceType1>(); if (bodyPreferences != null) { foreach (Request.BodyPreference bodyPreference in bodyPreferences) { items.Add(bodyPreference); itemsElementName.Add(Request.ItemsChoiceType1.BodyPreference); // Include the MIMESupport element in request to retrieve the MIME body if (bodyPreference.Type == 4) { items.Add((byte)2); itemsElementName.Add(Request.ItemsChoiceType1.MIMESupport); } } } if (bodyPartPreferences != null) { foreach (Request.BodyPartPreference bodyPartPreference in bodyPartPreferences) { items.Add(bodyPartPreference); itemsElementName.Add(Request.ItemsChoiceType1.BodyPartPreference); } } if (items.Count > 0) { request.RequestData.Collections[0].Options = new Request.Options[] { new Request.Options() { ItemsElementName = itemsElementName.ToArray(), Items = items.ToArray() } }; } return request; } /// <summary> /// Build an ItemOperations command request. /// </summary> /// <param name="collectionId">The collection id.</param> /// <param name="serverId">The server id of the mail.</param> /// <param name="fileReference">The file reference of the attachment.</param> /// <param name="bodyPreferences">The bodyPreference in the options element.</param> /// <param name="bodyPartPreferences">The bodyPartPreference in the options element.</param> /// <returns>An ItemOperations command request.</returns> internal static ItemOperationsRequest CreateItemOperationsRequest(string collectionId, string serverId, string fileReference, Request.BodyPreference[] bodyPreferences, Request.BodyPartPreference[] bodyPartPreferences) { ItemOperationsRequest request = new ItemOperationsRequest { RequestData = new Request.ItemOperations() }; Request.ItemOperationsFetch fetch = new Request.ItemOperationsFetch { Store = SearchName.Mailbox.ToString() }; if (fileReference != null) { fetch.FileReference = fileReference; } else { fetch.CollectionId = collectionId; fetch.ServerId = serverId; } List<object> items = new List<object>(); List<Request.ItemsChoiceType5> itemsElementName = new List<Request.ItemsChoiceType5>(); if (bodyPreferences != null) { foreach (Request.BodyPreference bodyPreference in bodyPreferences) { items.Add(bodyPreference); itemsElementName.Add(Request.ItemsChoiceType5.BodyPreference); // Include the MIMESupport element in request to retrieve the MIME body if (bodyPreference.Type == 4) { items.Add((byte)2); itemsElementName.Add(Request.ItemsChoiceType5.MIMESupport); } } } if (bodyPartPreferences != null) { foreach (Request.BodyPartPreference bodyPartPreference in bodyPartPreferences) { items.Add(bodyPartPreference); itemsElementName.Add(Request.ItemsChoiceType5.BodyPartPreference); } } if (items.Count > 0) { fetch.Options = new Request.ItemOperationsFetchOptions() { ItemsElementName = itemsElementName.ToArray(), Items = items.ToArray() }; } request.RequestData.Items = new object[] { fetch }; return request; } /// <summary> /// Build a Search request. /// </summary> /// <param name="query">The query string.</param> /// <param name="collectionId">The collection id of searched folder.</param> /// <param name="conversationId">The conversation for which to search.</param> /// <param name="bodyPreferences">The bodyPreference in the options element.</param> /// <param name="bodyPartPreferences">The bodyPartPreference in the options element.</param> /// <returns>A Search command request.</returns> internal static SearchRequest CreateSearchRequest(string query, string collectionId, string conversationId, Request.BodyPreference[] bodyPreferences, Request.BodyPartPreference[] bodyPartPreferences) { SearchRequest request = new SearchRequest { RequestData = { Items = new Request.SearchStore[] { new Request.SearchStore() { Name = SearchName.Mailbox.ToString(), Query = new Request.queryType() { Items = new object[] { new Request.queryType() { Items = new object[] { collectionId, query, conversationId }, ItemsElementName = new Request.ItemsChoiceType2[] { Request.ItemsChoiceType2.CollectionId, Request.ItemsChoiceType2.FreeText, Request.ItemsChoiceType2.ConversationId } } }, ItemsElementName = new Request.ItemsChoiceType2[] { Request.ItemsChoiceType2.And } } } } } }; List<object> items = new List<object>(); List<Request.ItemsChoiceType6> itemsElementName = new List<Request.ItemsChoiceType6>(); if (bodyPreferences != null) { foreach (Request.BodyPreference bodyPreference in bodyPreferences) { items.Add(bodyPreference); itemsElementName.Add(Request.ItemsChoiceType6.BodyPreference); // Include the MIMESupport element in request to retrieve the MIME body if (bodyPreference.Type == 4) { items.Add((byte)2); itemsElementName.Add(Request.ItemsChoiceType6.MIMESupport); } } } if (bodyPartPreferences != null) { foreach (Request.BodyPartPreference bodyPartPreference in bodyPartPreferences) { items.Add(bodyPartPreference); itemsElementName.Add(Request.ItemsChoiceType6.BodyPartPreference); } } items.Add(string.Empty); itemsElementName.Add(Request.ItemsChoiceType6.RebuildResults); items.Add("0-9"); itemsElementName.Add(Request.ItemsChoiceType6.Range); items.Add(string.Empty); itemsElementName.Add(Request.ItemsChoiceType6.DeepTraversal); request.RequestData.Items[0].Options = new Request.Options1() { ItemsElementName = itemsElementName.ToArray(), Items = items.ToArray() }; return request; } /// <summary> /// Create a sync add request. /// </summary> /// <param name="syncKey">Specify the sync key obtained from the last sync response</param> /// <param name="collectionId">Specify the server ID of the folder to be synchronized, which can be returned by ActiveSync FolderSync command.</param> /// <param name="applicationData">Contains the data used to specify the Add element for Sync command.</param> /// <returns>Returns the SyncRequest instance.</returns> internal static SyncRequest CreateSyncAddRequest(string syncKey, string collectionId, Request.SyncCollectionAddApplicationData applicationData) { SyncRequest syncAddRequest = TestSuiteHelper.CreateSyncRequest(syncKey, collectionId, null); Request.SyncCollectionAdd add = new Request.SyncCollectionAdd { ClientId = GetClientId(), ApplicationData = applicationData }; List<object> commandList = new List<object> { add }; syncAddRequest.RequestData.Collections[0].Commands = commandList.ToArray(); return syncAddRequest; } /// <summary> /// Build a generic Sync request without command references by using the specified sync key, folder collection ID and body preference option. /// If syncKey is /// In general, returns the XML formatted Sync request as follows: /// <!-- /// <?xml version="1.0" encoding="utf-8"?> /// <Sync xmlns="AirSync"> /// <Collections> /// <Collection> /// <SyncKey>0</SyncKey> /// <CollectionId>5</CollectionId> /// <DeletesAsMoves>1</DeletesAsMoves> /// <GetChanges>1</GetChanges> /// <WindowSize>100</WindowSize> /// <Options> /// <MIMESupport>0</MIMESupport> /// <airsyncbase:BodyPreference> /// <airsyncbase:Type>2</airsyncbase:Type> /// <airsyncbase:TruncationSize>5120</airsyncbase:TruncationSize> /// </airsyncbase:BodyPreference> /// </Options> /// </Collection> /// </Collections> /// </Sync> /// --> /// </summary> /// <param name="syncKey">Specify the sync key obtained from the last sync response(Refer to [MS-ASCMD]2.2.3.166.4)</param> /// <param name="collectionId">Specify the server ID of the folder to be synchronized, which can be returned by ActiveSync FolderSync command(Refer to [MS-ASCMD]2.2.3.30.5)</param> /// <param name="bodyPreference">Sets preference information related to the type and size of information for body (Refer to [MS-ASAIRS] 2.2.2.7)</param> /// <returns>Returns the SyncRequest instance</returns> internal static SyncRequest CreateSyncRequest(string syncKey, string collectionId, Request.BodyPreference bodyPreference) { Request.SyncCollection syncCollection = new Request.SyncCollection { SyncKey = syncKey, CollectionId = collectionId }; if (syncKey != "0") { syncCollection.GetChanges = true; syncCollection.GetChangesSpecified = true; } syncCollection.WindowSize = "100"; Request.Options syncOptions = new Request.Options(); List<object> syncOptionItems = new List<object>(); List<Request.ItemsChoiceType1> syncOptionItemsName = new List<Request.ItemsChoiceType1>(); if (null != bodyPreference) { syncOptionItemsName.Add(Request.ItemsChoiceType1.BodyPreference); syncOptionItems.Add(bodyPreference); // when body format is mime (Refer to [MS-ASAIRS] 2.2.2.22 Type) if (bodyPreference.Type == 0x4) { syncOptionItemsName.Add(Request.ItemsChoiceType1.MIMESupport); // Magic number '2' indicate server send MIME data for all messages but not S/MIME messages only syncOptionItems.Add((byte)0x2); } } syncOptions.Items = syncOptionItems.ToArray(); syncOptions.ItemsElementName = syncOptionItemsName.ToArray(); syncCollection.Options = new Request.Options[] { syncOptions }; return Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection }); } #endregion /// <summary> /// Create an instance of SyncCollection. /// </summary> /// <param name="syncKey">Specify the synchronization key obtained from the last sync command response.</param> /// <param name="collectionId">Specify the serverId of the folder to be synchronized, which can be returned by ActiveSync FolderSync command.</param> /// <returns>An instance of SyncCollection.</returns> internal static Request.SyncCollection CreateSyncCollection(string syncKey, string collectionId) { Request.SyncCollection syncCollection = new Request.SyncCollection { SyncKey = syncKey, GetChanges = true, GetChangesSpecified = true, CollectionId = collectionId, WindowSize = "100" }; return syncCollection; } #region Create MIME for SendMail command /// <summary> /// Create MIME for SendMail command. /// </summary> /// <param name="type">The email message body type.</param> /// <param name="from">The email address of sender.</param> /// <param name="to">The email address of recipient.</param> /// <param name="subject">The email subject.</param> /// <param name="body">The email body content.</param> /// <returns>A MIME for SendMail command.</returns> internal static string CreateMIME(EmailType type, string from, string to, string subject, string body) { string mime = null; string winmailData = null; // Create a plain text MIME if (type == EmailType.Plaintext) { mime = @"From: {0} To: {1} Subject: {2} Content-Type: text/plain; charset=""us-ascii"" MIME-Version: 1.0 {3} "; } // Create an HTML MIME if (type == EmailType.HTML) { mime = @"From: {0} To: {1} Subject: {2} Content-Type: text/html; charset=""us-ascii"" MIME-Version: 1.0 <html> <body> <font color=""blue"">{3}</font> </body> </html> "; } // Create a MIME with normal attachment if (type == EmailType.NormalAttachment) { mime = @"From: {0} To: {1} Subject: {2} Content-Type: multipart/mixed; boundary=""_boundary_""; type=""text/html"" MIME-Version: 1.0 --_boundary_ Content-Type: text/html; charset=""iso-8859-1"" Content-Transfer-Encoding: quoted-printable <html><body>{3}<img width=""128"" height=""94"" id=""Picture_x0020_1"" src=""cid:i= mage001.jpg@01CC1FB3.2053ED80"" alt=""Description: cid:ebdc14bd-deb4-4816-b= 00b-6e2a46097d17""></body></html> --_boundary_ Content-Type: image/jpeg; name=""number1.jpg"" Content-ID: {4} Content-Description: number1.jpg Content-Disposition: inline; size=4; filename=""number1.jpg"" Content-Location: <cid:ebdc14bd-deb4-4816-b00b-6e2a46097d17> Content-Transfer-Encoding: base64 MQ== --_boundary_-- "; } // Create a MIME with embedded attachment if (type == EmailType.EmbeddedAttachment) { mime = @"From: {0} To: {1} Subject: {2} Content-Type: multipart/mixed; boundary=""_boundary_""; type=""text/html"" MIME-Version: 1.0 --_boundary_ Content-Type: text/html; charset=""iso-8859-1"" Content-Transfer-Encoding: quoted-printable <html><body>{3}</body></html> --_boundary_ Content-Type: message/rfc822; name=""Embedded mail"" Content-Description: Embedded mail Content-Disposition: attachment; size=4; filename=""Embedded mail"" Content-Transfer-Encoding: base64 MQ== --_boundary_-- "; } // Create a MIME with OLE attachment if (type == EmailType.AttachOLE) { winmailData = Convert.ToBase64String(File.ReadAllBytes("winmail.dat")); // Split lines, for the maximum length of each line in MIME is no more than 76 characters for (int i = 1; i < winmailData.Length / 76; i++) { winmailData = winmailData.Insert((76 * i) - 1, "\r\n"); } // The string "contoso.com" is just a sample domain name, it has no relationship to the domain configured in deployment.ptfconfig file, and any changes of this string will lead to the update of winmail.dat file. mime = @"From: {0} To: {1} Subject: {2} MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=""_boundary_"" X-MS-TNEF-Correlator: <15CFAB655027B944AD65A26C7A6F2D7A0126D4994B34@DC01.contoso.com> {3} --_boundary_ Content-Type: text/plain; charset=""us-ascii"" Content-Transfer-Encoding: 7bit {3} --_boundary_ Content-Type: application/ms-tnef; name=""winmail.dat"" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=""winmail.dat"" {5} --_boundary_--"; } return Common.FormatString(mime, from, to, subject, body, Guid.NewGuid().ToString(), winmailData); } #endregion /// <summary> /// Get the specified email item from the sync add response by using the subject. /// </summary> /// <param name="syncStore">The sync result.</param> /// <param name="subject">The email subject.</param> /// <returns>Return the specified email item.</returns> internal static DataStructures.Sync GetSyncAddItem(DataStructures.SyncStore syncStore, string subject) { DataStructures.Sync item = null; if (syncStore.AddElements != null) { foreach (DataStructures.Sync syncItem in syncStore.AddElements) { if (syncItem.Email.Subject == subject) { item = syncItem; break; } if (syncItem.Calendar.Subject == subject) { item = syncItem; break; } if (syncItem.Contact.FileAs == subject) { item = syncItem; break; } } } return item; } /// <summary> /// Get the email item from the Search response by using the subject as the search criteria. /// </summary> /// <param name="searchStore">The Search command result.</param> /// <param name="subject">The email subject.</param> /// <returns>The email item corresponds to the specified subject.</returns> internal static DataStructures.Search GetSearchItem(DataStructures.SearchStore searchStore, string subject) { DataStructures.Search searchItem = null; if (searchStore.Results.Count > 0) { foreach (DataStructures.Search item in searchStore.Results) { if (item.Email.Subject == subject) { searchItem = item; break; } if (item.Calendar.Subject == subject) { searchItem = item; break; } } } return searchItem; } /// <summary> /// Truncate data according to the specified length. /// </summary> /// <param name="originalData">The original data.</param> /// <param name="length">The length of the byte array.</param> /// <returns>The truncated data.</returns> internal static string TruncateData(string originalData, int length) { byte[] bytes = System.Text.Encoding.ASCII.GetBytes(originalData); byte[] truncatedBytes = new byte[length]; for (int i = 0; i < length; i++) { truncatedBytes[i] = bytes[i]; } return System.Text.Encoding.ASCII.GetString(truncatedBytes); } /// <summary> /// Get the inner text of specified element. /// </summary> /// <param name="lastRawResponse">The raw xml response.</param> /// <param name="parentNodeName">The parent element of the specified node.</param> /// <param name="nodeName">The name of the node.</param> /// <param name="subject">The subject of the specified item.</param> /// <returns>The inner text of the specified element.</returns> internal static string GetDataInnerText(XmlElement lastRawResponse, string parentNodeName, string nodeName, string subject) { string data = null; XmlDocument doc = new XmlDocument(); doc.LoadXml(lastRawResponse.OuterXml); XmlNodeList subjectElementNodes = doc.SelectNodes("//*[name()='Subject']"); for (int i = 0; i < subjectElementNodes.Count; i++) { if (subjectElementNodes[i].InnerText == subject) { XmlNodeList bodyElementNodes = doc.SelectNodes("//*[name()='" + parentNodeName + "']"); XmlNodeList dataElementNodes = bodyElementNodes[i].SelectNodes("*[name()='" + nodeName + "']"); data = dataElementNodes[0].InnerText; break; } } return data; } /// <summary> /// Set the value of common meeting properties /// </summary> /// <param name="subject">The subject of the meeting.</param> /// <param name="attendeeEmailAddress">The email address of attendee.</param> /// <returns>The key and value pairs of common meeting properties.</returns> internal static Dictionary<Request.ItemsChoiceType8, object> SetMeetingProperties(string subject, string attendeeEmailAddress, ITestSite testSite) { Dictionary<Request.ItemsChoiceType8, object> propertiesToValueMap = new Dictionary<Request.ItemsChoiceType8, object> { { Request.ItemsChoiceType8.Subject, subject } }; // Set the subject element. // MeetingStauts is set to 1, which means it is a meeting and the user is the meeting organizer. byte meetingStatus = 1; propertiesToValueMap.Add(Request.ItemsChoiceType8.MeetingStatus, meetingStatus); // Set the UID string uID = Guid.NewGuid().ToString(); if (Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", testSite).Equals("16.0")|| Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", testSite).Equals("16.1")) { propertiesToValueMap.Add(Request.ItemsChoiceType8.ClientUid, uID); } else { propertiesToValueMap.Add(Request.ItemsChoiceType8.UID, uID); } // Set the TimeZone string timeZone = Common.GetTimeZone("(UTC) Coordinated Universal Time", 0); propertiesToValueMap.Add(Request.ItemsChoiceType8.Timezone, timeZone); // Set the attendee to user2 Request.Attendees attendees = TestSuiteHelper.CreateAttendees(attendeeEmailAddress); propertiesToValueMap.Add(Request.ItemsChoiceType8.Attendees, attendees); return propertiesToValueMap; } /// <summary> /// Create a Request.Attendees instance by the attendee email address. /// </summary> /// <param name="attendeeEmail">The email address of the attendee</param> /// <returns>The created Request.Attendees instance.</returns> internal static Request.Attendees CreateAttendees(string attendeeEmail) { List<Request.AttendeesAttendee> attendeelist = new List<Request.AttendeesAttendee> { new Request.AttendeesAttendee { Email = attendeeEmail, Name = attendeeEmail, AttendeeStatus = 0, AttendeeTypeSpecified=true, AttendeeType = 1 } }; Request.Attendees attendees = new Request.Attendees { Attendee = attendeelist.ToArray() }; return attendees; } /// <summary> /// Create iCalendar format string from one calendar instance /// </summary> /// <param name="calendar">Calendar information</param> /// <returns>iCalendar formatted string</returns> internal static string CreateiCalendarFormatContent(Calendar calendar) { StringBuilder ical = new StringBuilder(); ical.AppendLine("BEGIN: VCALENDAR"); ical.AppendLine("PRODID:-//Microosft Protocols TestSuites"); ical.AppendLine("VERSION:2.0"); ical.AppendLine("METHOD:REQUEST"); ical.AppendLine("X-MS-OLK-FORCEINSPECTOROPEN:TRUE"); ical.AppendLine("BEGIN:VTIMEZONE"); ical.AppendLine("TZID:UTC"); ical.AppendLine("BEGIN:STANDARD"); ical.AppendLine("DTSTART:16010101T000000"); ical.AppendLine("TZOFFSETFROM:-0000"); ical.AppendLine("TZOFFSETTO:-0000"); ical.AppendLine("END:STANDARD"); ical.AppendLine("END:VTIMEZONE"); ical.AppendLine("BEGIN:VEVENT"); ical.AppendLine("UID:" + calendar.UID); ical.AppendLine("DTSTAMP:" + ((DateTime)calendar.DtStamp).ToString("yyyyMMddTHHmmss")); ical.AppendLine("DESCRIPTION:" + calendar.Subject); ical.AppendLine("SUMMARY:" + calendar.Subject); ical.AppendLine("ATTENDEE;CN=\"\";RSVP=" + (calendar.ResponseRequested == true ? "TRUE" : "FALSE") + ":mailto:" + calendar.Attendees.Attendee[0].Email); ical.AppendLine("ORGANIZER:MAILTO:" + calendar.OrganizerEmail); ical.AppendLine("LOCATION:" + (calendar.Location ?? "My Office")); if (calendar.AllDayEvent == 1) { ical.AppendLine("DTSTART;VALUE=DATE:" + ((DateTime)calendar.StartTime).Date.ToString("yyyyMMdd")); ical.AppendLine("DTEND;VALUE=DATE:" + ((DateTime)calendar.EndTime).Date.ToString("yyyyMMdd")); ical.AppendLine("X-MICROSOFT-CDO-ALLDAYEVENT:TRUE"); } else { ical.AppendLine("DTSTART;TZID=\"UTC\":" + ((DateTime)calendar.StartTime).ToString("yyyyMMddTHHmmss")); ical.AppendLine("DTEND;TZID=\"UTC\":" + ((DateTime)calendar.EndTime).ToString("yyyyMMddTHHmmss")); } if (calendar.Recurrence != null) { switch (calendar.Recurrence.Type) { case 1: ical.AppendLine("RRULE:FREQ=WEEKLY;BYDAY=MO;UNTIL=" + calendar.Recurrence.Until); break; case 2: ical.AppendLine("RRULE:FREQ=MONTHLY;COUNT=3;BYMONTHDAY=1"); break; case 3: ical.AppendLine("RRULE:FREQ=MONTHLY;COUNT=3;BYDAY=1MO"); break; case 5: ical.AppendLine("RRULE:FREQ=YEARLY;COUNT=3;BYMONTHDAY=1;BYMONTH=1"); break; case 6: ical.AppendLine("RRULE:FREQ=YEARLY;COUNT=3;BYDAY=2MO;BYMONTH=1"); break; } } if (calendar.Exceptions != null) { ical.AppendLine("EXDATE;TZID=\"UTC\":" + ((DateTime)calendar.StartTime).AddDays(7).ToString("yyyyMMddTHHmmss")); ical.AppendLine("RECURRENCE-ID;TZID=\"UTC\":" + ((DateTime)calendar.StartTime).ToString("yyyyMMddTHHmmss")); } switch (calendar.BusyStatus) { case 0: ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:FREE"); break; case 1: ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE"); break; case 2: ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY"); break; case 3: ical.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:OOF"); break; } if (calendar.DisallowNewTimeProposal == true) { ical.AppendLine("X-MICROSOFT-DISALLOW-COUNTER:TRUE"); } if (calendar.Reminder.HasValue) { ical.AppendLine("BEGIN:VALARM"); ical.AppendLine("TRIGGER:-PT" + calendar.Reminder + "M"); ical.AppendLine("ACTION:DISPLAY"); ical.AppendLine("END:VALARM"); } ical.AppendLine("END:VEVENT"); ical.AppendLine("END:VCALENDAR"); return ical.ToString(); } /// <summary> /// Create a meeting request mime /// </summary> /// <param name="from">The from address of mail</param> /// <param name="to">The to address of the mail</param> /// <param name="subject">The subject of the mail</param> /// <param name="body">The body content of the mail</param> /// <param name="icalendarContent">The content of iCalendar required by this meeting</param> /// <returns>Returns the corresponding sample meeting mime</returns> internal static string CreateMeetingRequestMime(string from, string to, string subject, string body, string icalendarContent) { string meetingRequestMime = @"From: {0} To: {1} Subject: {2} Content-Type: multipart/alternative; boundary=""_001_MSASEMAIL_NextPart_"" MIME-Version: 1.0 --_001_MSASEMAIL_NextPart_ Content-Type: text/plain; charset=""us-ascii"" {3} --_001_MSASEMAIL_NextPart_ Content-Type: text/calendar; charset=""us-ascii""; method=REQUEST {4} --_001_MSASEMAIL_NextPart_-- "; return Common.FormatString(meetingRequestMime, from, to, subject, body, icalendarContent); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Interactivity; using Avalonia.VisualTree; namespace Avalonia.Input { /// <summary> /// Manages focus for the application. /// </summary> public class FocusManager : IFocusManager { /// <summary> /// The focus scopes in which the focus is currently defined. /// </summary> private readonly ConditionalWeakTable<IFocusScope, IInputElement?> _focusScopes = new ConditionalWeakTable<IFocusScope, IInputElement?>(); /// <summary> /// Initializes a new instance of the <see cref="FocusManager"/> class. /// </summary> static FocusManager() { InputElement.PointerPressedEvent.AddClassHandler( typeof(IInputElement), new EventHandler<RoutedEventArgs>(OnPreviewPointerPressed), RoutingStrategies.Tunnel); } /// <summary> /// Gets the instance of the <see cref="IFocusManager"/>. /// </summary> public static IFocusManager Instance => AvaloniaLocator.Current.GetService<IFocusManager>(); /// <summary> /// Gets the currently focused <see cref="IInputElement"/>. /// </summary> public IInputElement? Current => KeyboardDevice.Instance?.FocusedElement; /// <summary> /// Gets the current focus scope. /// </summary> public IFocusScope? Scope { get; private set; } /// <summary> /// Focuses a control. /// </summary> /// <param name="control">The control to focus.</param> /// <param name="method">The method by which focus was changed.</param> /// <param name="keyModifiers">Any key modifiers active at the time of focus.</param> public void Focus( IInputElement? control, NavigationMethod method = NavigationMethod.Unspecified, KeyModifiers keyModifiers = KeyModifiers.None) { if (control != null) { var scope = GetFocusScopeAncestors(control) .FirstOrDefault(); if (scope != null) { Scope = scope; SetFocusedElement(scope, control, method, keyModifiers); } } else if (Current != null) { // If control is null, set focus to the topmost focus scope. foreach (var scope in GetFocusScopeAncestors(Current).Reverse().ToList()) { if (_focusScopes.TryGetValue(scope, out var element) && element != null) { Focus(element, method); return; } } if (Scope is object) { // Couldn't find a focus scope, clear focus. SetFocusedElement(Scope, null); } } } /// <summary> /// Sets the currently focused element in the specified scope. /// </summary> /// <param name="scope">The focus scope.</param> /// <param name="element">The element to focus. May be null.</param> /// <param name="method">The method by which focus was changed.</param> /// <param name="keyModifiers">Any key modifiers active at the time of focus.</param> /// <remarks> /// If the specified scope is the current <see cref="Scope"/> then the keyboard focus /// will change. /// </remarks> public void SetFocusedElement( IFocusScope scope, IInputElement? element, NavigationMethod method = NavigationMethod.Unspecified, KeyModifiers keyModifiers = KeyModifiers.None) { scope = scope ?? throw new ArgumentNullException(nameof(scope)); if (_focusScopes.TryGetValue(scope, out var existingElement)) { if (element != existingElement) { _focusScopes.Remove(scope); _focusScopes.Add(scope, element); } } else { _focusScopes.Add(scope, element); } if (Scope == scope) { KeyboardDevice.Instance?.SetFocusedElement(element, method, keyModifiers); } } /// <summary> /// Notifies the focus manager of a change in focus scope. /// </summary> /// <param name="scope">The new focus scope.</param> public void SetFocusScope(IFocusScope scope) { scope = scope ?? throw new ArgumentNullException(nameof(scope)); if (!_focusScopes.TryGetValue(scope, out var e)) { // TODO: Make this do something useful, i.e. select the first focusable // control, select a control that the user has specified to have default // focus etc. e = scope as IInputElement; _focusScopes.Add(scope, e); } Scope = scope; Focus(e); } /// <summary> /// Checks if the specified element can be focused. /// </summary> /// <param name="e">The element.</param> /// <returns>True if the element can be focused.</returns> private static bool CanFocus(IInputElement e) => e.Focusable && e.IsEffectivelyEnabled && e.IsVisible; /// <summary> /// Gets the focus scope ancestors of the specified control, traversing popups. /// </summary> /// <param name="control">The control.</param> /// <returns>The focus scopes.</returns> private static IEnumerable<IFocusScope> GetFocusScopeAncestors(IInputElement control) { IInputElement? c = control; while (c != null) { var scope = c as IFocusScope; if (scope != null && c.VisualRoot?.IsVisible == true) { yield return scope; } c = c.GetVisualParent<IInputElement>() ?? ((c as IHostedVisualTreeRoot)?.Host as IInputElement); } } /// <summary> /// Global handler for pointer pressed events. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> private static void OnPreviewPointerPressed(object sender, RoutedEventArgs e) { var ev = (PointerPressedEventArgs)e; var visual = (IVisual)sender; if (sender == e.Source && ev.GetCurrentPoint(visual).Properties.IsLeftButtonPressed) { IVisual? element = ev.Pointer?.Captured ?? e.Source as IInputElement; while (element != null) { if (element is IInputElement inputElement && CanFocus(inputElement)) { Instance?.Focus(inputElement, NavigationMethod.Pointer, ev.KeyModifiers); break; } element = element.VisualParent; } } } } }
namespace Banshee { partial class PlayListView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); this.grid_menu = new System.Windows.Forms.ContextMenuStrip(this.components); this.removeTrackToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.propertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.addToPlaylistToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tracksBindingSource = new System.Windows.Forms.BindingSource(this.components); this.trackView = new Banshee.Controls.KryptonGrid(); this.trackColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.artistColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.titleColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.albumColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.genreColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.yearColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.timeColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ratingColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.playsColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.lastplayedColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.uriColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.grid_menu.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.tracksBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.trackView)).BeginInit(); this.SuspendLayout(); // // grid_menu // this.grid_menu.Font = new System.Drawing.Font("Segoe UI", 9F); this.grid_menu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.removeTrackToolStripMenuItem, this.propertiesToolStripMenuItem, this.addToPlaylistToolStripMenuItem}); this.grid_menu.Name = "grid_menu"; this.grid_menu.Size = new System.Drawing.Size(154, 70); this.grid_menu.Opening += new System.ComponentModel.CancelEventHandler(this.grid_menu_Opening); // // removeTrackToolStripMenuItem // this.removeTrackToolStripMenuItem.Name = "removeTrackToolStripMenuItem"; this.removeTrackToolStripMenuItem.Size = new System.Drawing.Size(153, 22); this.removeTrackToolStripMenuItem.Text = "Remove Track"; this.removeTrackToolStripMenuItem.Click += new System.EventHandler(this.removeTrackToolStripMenuItem_Click); // // propertiesToolStripMenuItem // this.propertiesToolStripMenuItem.Name = "propertiesToolStripMenuItem"; this.propertiesToolStripMenuItem.Size = new System.Drawing.Size(153, 22); this.propertiesToolStripMenuItem.Text = "Properties"; // // addToPlaylistToolStripMenuItem // this.addToPlaylistToolStripMenuItem.Name = "addToPlaylistToolStripMenuItem"; this.addToPlaylistToolStripMenuItem.Size = new System.Drawing.Size(153, 22); this.addToPlaylistToolStripMenuItem.Text = "Add To Playlist"; // // tracksBindingSource // this.tracksBindingSource.DataSource = typeof(Banshee.Base.TrackInfo); // // trackView // this.trackView.AllowUserToAddRows = false; this.trackView.AllowUserToDeleteRows = false; this.trackView.AllowUserToResizeRows = false; dataGridViewCellStyle1.BackColor = System.Drawing.Color.Gainsboro; this.trackView.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; this.trackView.AutoGenerateColumns = false; this.trackView.BackgroundColor = System.Drawing.Color.White; this.trackView.BorderStyle = System.Windows.Forms.BorderStyle.None; this.trackView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.trackView.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; this.trackView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.trackColumn, this.artistColumn, this.titleColumn, this.albumColumn, this.genreColumn, this.yearColumn, this.timeColumn, this.ratingColumn, this.playsColumn, this.lastplayedColumn, this.uriColumn}); this.trackView.ContextMenuStrip = this.grid_menu; this.trackView.DataSource = this.tracksBindingSource; dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle3.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold); dataGridViewCellStyle3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(70)))), ((int)(((byte)(70)))), ((int)(((byte)(70))))); dataGridViewCellStyle3.SelectionBackColor = System.Drawing.Color.Transparent; dataGridViewCellStyle3.SelectionForeColor = System.Drawing.Color.Navy; dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.trackView.DefaultCellStyle = dataGridViewCellStyle3; this.trackView.Dock = System.Windows.Forms.DockStyle.Fill; this.trackView.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold); this.trackView.GridColor = System.Drawing.Color.White; this.trackView.Location = new System.Drawing.Point(0, 0); this.trackView.Name = "trackView"; this.trackView.ReadOnly = true; this.trackView.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; this.trackView.RowHeadersVisible = false; this.trackView.RowTemplate.DefaultCellStyle.BackColor = System.Drawing.Color.WhiteSmoke; this.trackView.RowTemplate.DefaultCellStyle.ForeColor = System.Drawing.Color.Black; this.trackView.RowTemplate.DefaultCellStyle.SelectionBackColor = System.Drawing.Color.White; this.trackView.RowTemplate.DefaultCellStyle.SelectionForeColor = System.Drawing.Color.Black; this.trackView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.trackView.ShowDataError = false; this.trackView.Size = new System.Drawing.Size(543, 437); this.trackView.SuspendDraw = false; this.trackView.TabIndex = 1; this.trackView.CellMouseDown += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.trackView_CellMouseDown); this.trackView.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.trackView_CellDoubleClick); // // trackColumn // this.trackColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.ColumnHeader; this.trackColumn.DataPropertyName = "TrackNumber"; this.trackColumn.HeaderText = "Track"; this.trackColumn.Name = "trackColumn"; this.trackColumn.ReadOnly = true; this.trackColumn.Width = 63; // // artistColumn // this.artistColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; this.artistColumn.DataPropertyName = "Artist"; this.artistColumn.HeaderText = "Artist"; this.artistColumn.Name = "artistColumn"; this.artistColumn.ReadOnly = true; this.artistColumn.Width = 63; // // titleColumn // this.titleColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; this.titleColumn.DataPropertyName = "Title"; this.titleColumn.HeaderText = "Title"; this.titleColumn.Name = "titleColumn"; this.titleColumn.ReadOnly = true; this.titleColumn.Width = 57; // // albumColumn // this.albumColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; this.albumColumn.DataPropertyName = "Album"; this.albumColumn.HeaderText = "Album"; this.albumColumn.Name = "albumColumn"; this.albumColumn.ReadOnly = true; this.albumColumn.Width = 68; // // genreColumn // this.genreColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; this.genreColumn.DataPropertyName = "Genre"; this.genreColumn.HeaderText = "Genre"; this.genreColumn.Name = "genreColumn"; this.genreColumn.ReadOnly = true; this.genreColumn.Width = 67; // // yearColumn // this.yearColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; this.yearColumn.DataPropertyName = "Year"; this.yearColumn.HeaderText = "Year"; this.yearColumn.Name = "yearColumn"; this.yearColumn.ReadOnly = true; this.yearColumn.Width = 57; // // timeColumn // this.timeColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.ColumnHeader; this.timeColumn.DataPropertyName = "Duration"; dataGridViewCellStyle2.Format = "#:##"; dataGridViewCellStyle2.NullValue = "0:00"; this.timeColumn.DefaultCellStyle = dataGridViewCellStyle2; this.timeColumn.HeaderText = "Time"; this.timeColumn.Name = "timeColumn"; this.timeColumn.ReadOnly = true; this.timeColumn.Width = 60; // // ratingColumn // this.ratingColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; this.ratingColumn.DataPropertyName = "Rating"; this.ratingColumn.HeaderText = "Rating"; this.ratingColumn.Name = "ratingColumn"; this.ratingColumn.ReadOnly = true; this.ratingColumn.Width = 68; // // playsColumn // this.playsColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.ColumnHeader; this.playsColumn.DataPropertyName = "PlayCount"; this.playsColumn.HeaderText = "Plays"; this.playsColumn.Name = "playsColumn"; this.playsColumn.ReadOnly = true; this.playsColumn.Width = 59; // // lastplayedColumn // this.lastplayedColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; this.lastplayedColumn.DataPropertyName = "LastPlayed"; this.lastplayedColumn.HeaderText = "Last Played"; this.lastplayedColumn.Name = "lastplayedColumn"; this.lastplayedColumn.ReadOnly = true; this.lastplayedColumn.Width = 93; // // uriColumn // this.uriColumn.DataPropertyName = "Uri"; this.uriColumn.HeaderText = "Uri"; this.uriColumn.Name = "uriColumn"; this.uriColumn.ReadOnly = true; this.uriColumn.Visible = false; // // PlayListView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.trackView); this.Name = "PlayListView"; this.Size = new System.Drawing.Size(543, 437); this.Load += new System.EventHandler(this.PlayListViewI_Load); this.grid_menu.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.tracksBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.trackView)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ContextMenuStrip grid_menu; private System.Windows.Forms.ToolStripMenuItem removeTrackToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem propertiesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem addToPlaylistToolStripMenuItem; private System.Windows.Forms.BindingSource tracksBindingSource; private Controls.KryptonGrid trackView; private System.Windows.Forms.DataGridViewTextBoxColumn trackColumn; private System.Windows.Forms.DataGridViewTextBoxColumn artistColumn; private System.Windows.Forms.DataGridViewTextBoxColumn titleColumn; private System.Windows.Forms.DataGridViewTextBoxColumn albumColumn; private System.Windows.Forms.DataGridViewTextBoxColumn genreColumn; private System.Windows.Forms.DataGridViewTextBoxColumn yearColumn; private System.Windows.Forms.DataGridViewTextBoxColumn timeColumn; private System.Windows.Forms.DataGridViewTextBoxColumn ratingColumn; private System.Windows.Forms.DataGridViewTextBoxColumn playsColumn; private System.Windows.Forms.DataGridViewTextBoxColumn lastplayedColumn; private System.Windows.Forms.DataGridViewTextBoxColumn uriColumn; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using Microsoft.Xml; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Globalization; using System.Runtime.Serialization; namespace Microsoft.Xml { internal class XmlBinaryReader : XmlBaseReader { private bool _isTextWithEndElement; private bool _buffered; private ArrayState _arrayState; private int _arrayCount; private int _maxBytesPerRead; private XmlBinaryNodeType _arrayNodeType; public XmlBinaryReader() { } public void SetInput(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session) { if (buffer == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); if (offset < 0) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", string.Format(SRSerialization.ValueMustBeNonNegative))); if (offset > buffer.Length) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", string.Format(SRSerialization.OffsetExceedsBufferSize, buffer.Length))); if (count < 0) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", string.Format(SRSerialization.ValueMustBeNonNegative))); if (count > buffer.Length - offset) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", string.Format(SRSerialization.SizeExceedsRemainingBufferSpace, buffer.Length - offset))); MoveToInitial(quotas, session, null); BufferReader.SetBuffer(buffer, offset, count, dictionary, session); _buffered = true; } public void SetInput(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session) { if (stream == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); MoveToInitial(quotas, session, null); BufferReader.SetBuffer(stream, dictionary, session); _buffered = false; } private void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { MoveToInitial(quotas); _maxBytesPerRead = quotas.MaxBytesPerRead; _arrayState = ArrayState.None; _isTextWithEndElement = false; } public override void Close() { base.Close(); } public override string ReadElementContentAsString() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (!CanOptimizeReadElementContent()) return base.ReadElementContentAsString(); string value; switch (GetNodeType()) { case XmlBinaryNodeType.Chars8TextWithEndElement: SkipNodeType(); value = BufferReader.ReadUTF8String(ReadUInt8()); ReadTextWithEndElement(); break; case XmlBinaryNodeType.DictionaryTextWithEndElement: SkipNodeType(); value = BufferReader.GetDictionaryString(ReadDictionaryKey()).Value; ReadTextWithEndElement(); break; default: value = base.ReadElementContentAsString(); break; } if (value.Length > Quotas.MaxStringContentLength) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, Quotas.MaxStringContentLength); return value; } public override bool ReadElementContentAsBoolean() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (!CanOptimizeReadElementContent()) return base.ReadElementContentAsBoolean(); bool value; switch (GetNodeType()) { case XmlBinaryNodeType.TrueTextWithEndElement: SkipNodeType(); value = true; ReadTextWithEndElement(); break; case XmlBinaryNodeType.FalseTextWithEndElement: SkipNodeType(); value = false; ReadTextWithEndElement(); break; case XmlBinaryNodeType.BoolTextWithEndElement: SkipNodeType(); value = (BufferReader.ReadUInt8() != 0); ReadTextWithEndElement(); break; default: value = base.ReadElementContentAsBoolean(); break; } return value; } public override int ReadElementContentAsInt() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (!CanOptimizeReadElementContent()) return base.ReadElementContentAsInt(); int value; switch (GetNodeType()) { case XmlBinaryNodeType.ZeroTextWithEndElement: SkipNodeType(); value = 0; ReadTextWithEndElement(); break; case XmlBinaryNodeType.OneTextWithEndElement: SkipNodeType(); value = 1; ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int8TextWithEndElement: SkipNodeType(); value = BufferReader.ReadInt8(); ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int16TextWithEndElement: SkipNodeType(); value = BufferReader.ReadInt16(); ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int32TextWithEndElement: SkipNodeType(); value = BufferReader.ReadInt32(); ReadTextWithEndElement(); break; default: value = base.ReadElementContentAsInt(); break; } return value; } private bool CanOptimizeReadElementContent() { return (_arrayState == ArrayState.None); } public override float ReadElementContentAsFloat() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.FloatTextWithEndElement) { SkipNodeType(); float value = BufferReader.ReadSingle(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsFloat(); } public override double ReadElementContentAsDouble() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DoubleTextWithEndElement) { SkipNodeType(); double value = BufferReader.ReadDouble(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsDouble(); } public override decimal ReadElementContentAsDecimal() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DecimalTextWithEndElement) { SkipNodeType(); decimal value = BufferReader.ReadDecimal(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsDecimal(); } public override DateTime ReadElementContentAsDateTime() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DateTimeTextWithEndElement) { SkipNodeType(); DateTime value = BufferReader.ReadDateTime(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsDateTime(); } public override TimeSpan ReadElementContentAsTimeSpan() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.TimeSpanTextWithEndElement) { SkipNodeType(); TimeSpan value = BufferReader.ReadTimeSpan(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsTimeSpan(); } public override Guid ReadElementContentAsGuid() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.GuidTextWithEndElement) { SkipNodeType(); Guid value = BufferReader.ReadGuid(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsGuid(); } public override UniqueId ReadElementContentAsUniqueId() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.UniqueIdTextWithEndElement) { SkipNodeType(); UniqueId value = BufferReader.ReadUniqueId(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsUniqueId(); } public override bool TryGetBase64ContentLength(out int length) { length = 0; if (!_buffered) return false; if (_arrayState != ArrayState.None) return false; int totalLength; if (!this.Node.Value.TryGetByteArrayLength(out totalLength)) return false; int offset = BufferReader.Offset; try { bool done = false; while (!done && !BufferReader.EndOfFile) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); int actual; switch (nodeType) { case XmlBinaryNodeType.Bytes8TextWithEndElement: actual = BufferReader.ReadUInt8(); done = true; break; case XmlBinaryNodeType.Bytes16TextWithEndElement: actual = BufferReader.ReadUInt16(); done = true; break; case XmlBinaryNodeType.Bytes32TextWithEndElement: actual = BufferReader.ReadUInt31(); done = true; break; case XmlBinaryNodeType.EndElement: actual = 0; done = true; break; case XmlBinaryNodeType.Bytes8Text: actual = BufferReader.ReadUInt8(); break; case XmlBinaryNodeType.Bytes16Text: actual = BufferReader.ReadUInt16(); break; case XmlBinaryNodeType.Bytes32Text: actual = BufferReader.ReadUInt31(); break; default: // Non-optimal or unexpected node - fallback return false; } BufferReader.Advance(actual); if (totalLength > int.MaxValue - actual) return false; totalLength += actual; } length = totalLength; return true; } finally { BufferReader.Offset = offset; } } private void ReadTextWithEndElement() { ExitScope(); ReadNode(); } private XmlAtomicTextNode MoveToAtomicTextWithEndElement() { _isTextWithEndElement = true; return MoveToAtomicText(); } public override bool Read() { if (this.Node.ReadState == ReadState.Closed) return false; if (_isTextWithEndElement) { _isTextWithEndElement = false; MoveToEndElement(); return true; } if (_arrayState == ArrayState.Content) { if (_arrayCount != 0) { MoveToArrayElement(); return true; } _arrayState = ArrayState.None; } if (this.Node.ExitScope) { ExitScope(); } return ReadNode(); } private bool ReadNode() { if (!_buffered) BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead); if (BufferReader.EndOfFile) { MoveToEndOfFile(); return false; } XmlBinaryNodeType nodeType; if (_arrayState == ArrayState.None) { nodeType = GetNodeType(); SkipNodeType(); } else { DiagnosticUtility.DebugAssert(_arrayState == ArrayState.Element, ""); nodeType = _arrayNodeType; _arrayCount--; _arrayState = ArrayState.Content; } XmlElementNode elementNode; PrefixHandleType prefix; switch (nodeType) { case XmlBinaryNodeType.ShortElement: elementNode = EnterScope(); elementNode.Prefix.SetValue(PrefixHandleType.Empty); ReadName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.Element: elementNode = EnterScope(); ReadName(elementNode.Prefix); ReadName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(elementNode.Prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.ShortDictionaryElement: elementNode = EnterScope(); elementNode.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.DictionaryElement: elementNode = EnterScope(); ReadName(elementNode.Prefix); ReadDictionaryName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(elementNode.Prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.PrefixElementA: case XmlBinaryNodeType.PrefixElementB: case XmlBinaryNodeType.PrefixElementC: case XmlBinaryNodeType.PrefixElementD: case XmlBinaryNodeType.PrefixElementE: case XmlBinaryNodeType.PrefixElementF: case XmlBinaryNodeType.PrefixElementG: case XmlBinaryNodeType.PrefixElementH: case XmlBinaryNodeType.PrefixElementI: case XmlBinaryNodeType.PrefixElementJ: case XmlBinaryNodeType.PrefixElementK: case XmlBinaryNodeType.PrefixElementL: case XmlBinaryNodeType.PrefixElementM: case XmlBinaryNodeType.PrefixElementN: case XmlBinaryNodeType.PrefixElementO: case XmlBinaryNodeType.PrefixElementP: case XmlBinaryNodeType.PrefixElementQ: case XmlBinaryNodeType.PrefixElementR: case XmlBinaryNodeType.PrefixElementS: case XmlBinaryNodeType.PrefixElementT: case XmlBinaryNodeType.PrefixElementU: case XmlBinaryNodeType.PrefixElementV: case XmlBinaryNodeType.PrefixElementW: case XmlBinaryNodeType.PrefixElementX: case XmlBinaryNodeType.PrefixElementY: case XmlBinaryNodeType.PrefixElementZ: elementNode = EnterScope(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixElementA); elementNode.Prefix.SetValue(prefix); ReadName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.PrefixDictionaryElementA: case XmlBinaryNodeType.PrefixDictionaryElementB: case XmlBinaryNodeType.PrefixDictionaryElementC: case XmlBinaryNodeType.PrefixDictionaryElementD: case XmlBinaryNodeType.PrefixDictionaryElementE: case XmlBinaryNodeType.PrefixDictionaryElementF: case XmlBinaryNodeType.PrefixDictionaryElementG: case XmlBinaryNodeType.PrefixDictionaryElementH: case XmlBinaryNodeType.PrefixDictionaryElementI: case XmlBinaryNodeType.PrefixDictionaryElementJ: case XmlBinaryNodeType.PrefixDictionaryElementK: case XmlBinaryNodeType.PrefixDictionaryElementL: case XmlBinaryNodeType.PrefixDictionaryElementM: case XmlBinaryNodeType.PrefixDictionaryElementN: case XmlBinaryNodeType.PrefixDictionaryElementO: case XmlBinaryNodeType.PrefixDictionaryElementP: case XmlBinaryNodeType.PrefixDictionaryElementQ: case XmlBinaryNodeType.PrefixDictionaryElementR: case XmlBinaryNodeType.PrefixDictionaryElementS: case XmlBinaryNodeType.PrefixDictionaryElementT: case XmlBinaryNodeType.PrefixDictionaryElementU: case XmlBinaryNodeType.PrefixDictionaryElementV: case XmlBinaryNodeType.PrefixDictionaryElementW: case XmlBinaryNodeType.PrefixDictionaryElementX: case XmlBinaryNodeType.PrefixDictionaryElementY: case XmlBinaryNodeType.PrefixDictionaryElementZ: elementNode = EnterScope(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryElementA); elementNode.Prefix.SetValue(prefix); ReadDictionaryName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.EndElement: MoveToEndElement(); return true; case XmlBinaryNodeType.Comment: ReadName(MoveToComment().Value); return true; case XmlBinaryNodeType.EmptyTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Empty); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.ZeroTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Zero); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.OneTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.One); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.TrueTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.True); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.FalseTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.False); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.BoolTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ReadUInt8() != 0 ? ValueHandleType.True : ValueHandleType.False); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.Chars8TextWithEndElement: if (_buffered) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt8()); else ReadPartialUTF8Text(true, ReadUInt8()); return true; case XmlBinaryNodeType.Chars8Text: if (_buffered) ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt8()); else ReadPartialUTF8Text(false, ReadUInt8()); return true; case XmlBinaryNodeType.Chars16TextWithEndElement: if (_buffered) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt16()); else ReadPartialUTF8Text(true, ReadUInt16()); return true; case XmlBinaryNodeType.Chars16Text: if (_buffered) ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt16()); else ReadPartialUTF8Text(false, ReadUInt16()); return true; case XmlBinaryNodeType.Chars32TextWithEndElement: if (_buffered) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt31()); else ReadPartialUTF8Text(true, ReadUInt31()); return true; case XmlBinaryNodeType.Chars32Text: if (_buffered) ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt31()); else ReadPartialUTF8Text(false, ReadUInt31()); return true; case XmlBinaryNodeType.UnicodeChars8TextWithEndElement: ReadUnicodeText(true, ReadUInt8()); return true; case XmlBinaryNodeType.UnicodeChars8Text: ReadUnicodeText(false, ReadUInt8()); return true; case XmlBinaryNodeType.UnicodeChars16TextWithEndElement: ReadUnicodeText(true, ReadUInt16()); return true; case XmlBinaryNodeType.UnicodeChars16Text: ReadUnicodeText(false, ReadUInt16()); return true; case XmlBinaryNodeType.UnicodeChars32TextWithEndElement: ReadUnicodeText(true, ReadUInt31()); return true; case XmlBinaryNodeType.UnicodeChars32Text: ReadUnicodeText(false, ReadUInt31()); return true; case XmlBinaryNodeType.Bytes8TextWithEndElement: if (_buffered) ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt8()); else ReadPartialBinaryText(true, ReadUInt8()); return true; case XmlBinaryNodeType.Bytes8Text: if (_buffered) ReadBinaryText(MoveToComplexText(), ReadUInt8()); else ReadPartialBinaryText(false, ReadUInt8()); return true; case XmlBinaryNodeType.Bytes16TextWithEndElement: if (_buffered) ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt16()); else ReadPartialBinaryText(true, ReadUInt16()); return true; case XmlBinaryNodeType.Bytes16Text: if (_buffered) ReadBinaryText(MoveToComplexText(), ReadUInt16()); else ReadPartialBinaryText(false, ReadUInt16()); return true; case XmlBinaryNodeType.Bytes32TextWithEndElement: if (_buffered) ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt31()); else ReadPartialBinaryText(true, ReadUInt31()); return true; case XmlBinaryNodeType.Bytes32Text: if (_buffered) ReadBinaryText(MoveToComplexText(), ReadUInt31()); else ReadPartialBinaryText(false, ReadUInt31()); return true; case XmlBinaryNodeType.DictionaryTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetDictionaryValue(ReadDictionaryKey()); return true; case XmlBinaryNodeType.UniqueIdTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UniqueId, ValueHandleLength.UniqueId); return true; case XmlBinaryNodeType.GuidTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Guid, ValueHandleLength.Guid); return true; case XmlBinaryNodeType.DecimalTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Decimal, ValueHandleLength.Decimal); return true; case XmlBinaryNodeType.Int8TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int8, ValueHandleLength.Int8); return true; case XmlBinaryNodeType.Int16TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int16, ValueHandleLength.Int16); return true; case XmlBinaryNodeType.Int32TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int32, ValueHandleLength.Int32); return true; case XmlBinaryNodeType.Int64TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int64, ValueHandleLength.Int64); return true; case XmlBinaryNodeType.UInt64TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UInt64, ValueHandleLength.UInt64); return true; case XmlBinaryNodeType.FloatTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Single, ValueHandleLength.Single); return true; case XmlBinaryNodeType.DoubleTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Double, ValueHandleLength.Double); return true; case XmlBinaryNodeType.TimeSpanTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.TimeSpan, ValueHandleLength.TimeSpan); return true; case XmlBinaryNodeType.DateTimeTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.DateTime, ValueHandleLength.DateTime); return true; case XmlBinaryNodeType.QNameDictionaryTextWithEndElement: BufferReader.ReadQName(MoveToAtomicTextWithEndElement().Value); return true; case XmlBinaryNodeType.Array: ReadArray(); return true; default: BufferReader.ReadValue(nodeType, MoveToComplexText().Value); return true; } } private void VerifyWhitespace() { if (!this.Node.Value.IsWhitespace()) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } private void ReadAttributes() { XmlBinaryNodeType nodeType = GetNodeType(); if (nodeType < XmlBinaryNodeType.MinAttribute || nodeType > XmlBinaryNodeType.MaxAttribute) return; ReadAttributes2(); } private void ReadAttributes2() { int startOffset = 0; if (_buffered) startOffset = BufferReader.Offset; while (true) { XmlAttributeNode attributeNode; Namespace nameSpace; PrefixHandleType prefix; XmlBinaryNodeType nodeType = GetNodeType(); switch (nodeType) { case XmlBinaryNodeType.ShortAttribute: SkipNodeType(); attributeNode = AddAttribute(); attributeNode.Prefix.SetValue(PrefixHandleType.Empty); ReadName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.Attribute: SkipNodeType(); attributeNode = AddAttribute(); ReadName(attributeNode.Prefix); ReadName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); FixXmlAttribute(attributeNode); break; case XmlBinaryNodeType.ShortDictionaryAttribute: SkipNodeType(); attributeNode = AddAttribute(); attributeNode.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.DictionaryAttribute: SkipNodeType(); attributeNode = AddAttribute(); ReadName(attributeNode.Prefix); ReadDictionaryName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.XmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); ReadName(nameSpace.Prefix); ReadName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.ShortXmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); nameSpace.Prefix.SetValue(PrefixHandleType.Empty); ReadName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.ShortDictionaryXmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); nameSpace.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.DictionaryXmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); ReadName(nameSpace.Prefix); ReadDictionaryName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.PrefixDictionaryAttributeA: case XmlBinaryNodeType.PrefixDictionaryAttributeB: case XmlBinaryNodeType.PrefixDictionaryAttributeC: case XmlBinaryNodeType.PrefixDictionaryAttributeD: case XmlBinaryNodeType.PrefixDictionaryAttributeE: case XmlBinaryNodeType.PrefixDictionaryAttributeF: case XmlBinaryNodeType.PrefixDictionaryAttributeG: case XmlBinaryNodeType.PrefixDictionaryAttributeH: case XmlBinaryNodeType.PrefixDictionaryAttributeI: case XmlBinaryNodeType.PrefixDictionaryAttributeJ: case XmlBinaryNodeType.PrefixDictionaryAttributeK: case XmlBinaryNodeType.PrefixDictionaryAttributeL: case XmlBinaryNodeType.PrefixDictionaryAttributeM: case XmlBinaryNodeType.PrefixDictionaryAttributeN: case XmlBinaryNodeType.PrefixDictionaryAttributeO: case XmlBinaryNodeType.PrefixDictionaryAttributeP: case XmlBinaryNodeType.PrefixDictionaryAttributeQ: case XmlBinaryNodeType.PrefixDictionaryAttributeR: case XmlBinaryNodeType.PrefixDictionaryAttributeS: case XmlBinaryNodeType.PrefixDictionaryAttributeT: case XmlBinaryNodeType.PrefixDictionaryAttributeU: case XmlBinaryNodeType.PrefixDictionaryAttributeV: case XmlBinaryNodeType.PrefixDictionaryAttributeW: case XmlBinaryNodeType.PrefixDictionaryAttributeX: case XmlBinaryNodeType.PrefixDictionaryAttributeY: case XmlBinaryNodeType.PrefixDictionaryAttributeZ: SkipNodeType(); attributeNode = AddAttribute(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryAttributeA); attributeNode.Prefix.SetValue(prefix); ReadDictionaryName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.PrefixAttributeA: case XmlBinaryNodeType.PrefixAttributeB: case XmlBinaryNodeType.PrefixAttributeC: case XmlBinaryNodeType.PrefixAttributeD: case XmlBinaryNodeType.PrefixAttributeE: case XmlBinaryNodeType.PrefixAttributeF: case XmlBinaryNodeType.PrefixAttributeG: case XmlBinaryNodeType.PrefixAttributeH: case XmlBinaryNodeType.PrefixAttributeI: case XmlBinaryNodeType.PrefixAttributeJ: case XmlBinaryNodeType.PrefixAttributeK: case XmlBinaryNodeType.PrefixAttributeL: case XmlBinaryNodeType.PrefixAttributeM: case XmlBinaryNodeType.PrefixAttributeN: case XmlBinaryNodeType.PrefixAttributeO: case XmlBinaryNodeType.PrefixAttributeP: case XmlBinaryNodeType.PrefixAttributeQ: case XmlBinaryNodeType.PrefixAttributeR: case XmlBinaryNodeType.PrefixAttributeS: case XmlBinaryNodeType.PrefixAttributeT: case XmlBinaryNodeType.PrefixAttributeU: case XmlBinaryNodeType.PrefixAttributeV: case XmlBinaryNodeType.PrefixAttributeW: case XmlBinaryNodeType.PrefixAttributeX: case XmlBinaryNodeType.PrefixAttributeY: case XmlBinaryNodeType.PrefixAttributeZ: SkipNodeType(); attributeNode = AddAttribute(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixAttributeA); attributeNode.Prefix.SetValue(prefix); ReadName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; default: ProcessAttributes(); return; } } } private void ReadText(XmlTextNode textNode, ValueHandleType type, int length) { int offset = BufferReader.ReadBytes(length); textNode.Value.SetValue(type, offset, length); if (this.OutsideRootElement) VerifyWhitespace(); } private void ReadBinaryText(XmlTextNode textNode, int length) { ReadText(textNode, ValueHandleType.Base64, length); } private void ReadPartialUTF8Text(bool withEndElement, int length) { // The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need // to account for that. const int maxTextNodeLength = 5; int maxLength = Math.Max(_maxBytesPerRead - maxTextNodeLength, 0); if (length <= maxLength) { if (withEndElement) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, length); else ReadText(MoveToComplexText(), ValueHandleType.UTF8, length); } else { // We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode // for the split data. int actual = Math.Max(maxLength - maxTextNodeLength, 0); int offset = BufferReader.ReadBytes(actual); // We need to make sure we don't split a utf8 character, so scan backwards for a // character boundary. We'll actually always push off at least one character since // although we find the character boundary, we don't bother to figure out if we have // all the bytes that comprise the character. int i; for (i = offset + actual - 1; i >= offset; i--) { byte b = BufferReader.GetByte(i); // The first byte of UTF8 character sequence has either the high bit off, or the // two high bits set. if ((b & 0x80) == 0 || (b & 0xC0) == 0xC0) break; } // Move any split characters so we can insert the node int byteCount = (offset + actual - i); // Include the split characters in the count BufferReader.Offset = BufferReader.Offset - byteCount; actual -= byteCount; MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, actual); if (this.OutsideRootElement) VerifyWhitespace(); XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Chars32TextWithEndElement : XmlBinaryNodeType.Chars32Text); InsertNode(nodeType, length - actual); } } private void ReadUnicodeText(bool withEndElement, int length) { if ((length & 1) != 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); if (_buffered) { if (withEndElement) { ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length); } else { ReadText(MoveToComplexText(), ValueHandleType.Unicode, length); } } else { ReadPartialUnicodeText(withEndElement, length); } } private void ReadPartialUnicodeText(bool withEndElement, int length) { // The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need // to account for that. const int maxTextNodeLength = 5; int maxLength = Math.Max(_maxBytesPerRead - maxTextNodeLength, 0); if (length <= maxLength) { if (withEndElement) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length); else ReadText(MoveToComplexText(), ValueHandleType.Unicode, length); } else { // We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode // for the split data. int actual = Math.Max(maxLength - maxTextNodeLength, 0); // Make sure we break on a char boundary if ((actual & 1) != 0) actual--; int offset = BufferReader.ReadBytes(actual); // We need to make sure we don't split a unicode surrogate character int byteCount = 0; char ch = (char)BufferReader.GetInt16(offset + actual - sizeof(char)); // If the last char is a high surrogate char, then move back if (ch >= 0xD800 && ch < 0xDC00) byteCount = sizeof(char); // Include the split characters in the count BufferReader.Offset = BufferReader.Offset - byteCount; actual -= byteCount; MoveToComplexText().Value.SetValue(ValueHandleType.Unicode, offset, actual); if (this.OutsideRootElement) VerifyWhitespace(); XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.UnicodeChars32TextWithEndElement : XmlBinaryNodeType.UnicodeChars32Text); InsertNode(nodeType, length - actual); } } private void ReadPartialBinaryText(bool withEndElement, int length) { const int nodeLength = 5; int maxBytesPerRead = Math.Max(_maxBytesPerRead - nodeLength, 0); if (length <= maxBytesPerRead) { if (withEndElement) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Base64, length); else ReadText(MoveToComplexText(), ValueHandleType.Base64, length); } else { int actual = maxBytesPerRead; if (actual > 3) actual -= (actual % 3); ReadText(MoveToComplexText(), ValueHandleType.Base64, actual); XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Bytes32TextWithEndElement : XmlBinaryNodeType.Bytes32Text); InsertNode(nodeType, length - actual); } } private void InsertNode(XmlBinaryNodeType nodeType, int length) { byte[] buffer = new byte[5]; buffer[0] = (byte)nodeType; buffer[1] = (byte)length; length >>= 8; buffer[2] = (byte)length; length >>= 8; buffer[3] = (byte)length; length >>= 8; buffer[4] = (byte)length; BufferReader.InsertBytes(buffer, 0, buffer.Length); } private void ReadAttributeText(XmlAttributeTextNode textNode) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); BufferReader.ReadValue(nodeType, textNode.Value); } private void ReadName(ValueHandle value) { int length = ReadMultiByteUInt31(); int offset = BufferReader.ReadBytes(length); value.SetValue(ValueHandleType.UTF8, offset, length); } private void ReadName(StringHandle handle) { int length = ReadMultiByteUInt31(); int offset = BufferReader.ReadBytes(length); handle.SetValue(offset, length); } private void ReadName(PrefixHandle prefix) { int length = ReadMultiByteUInt31(); int offset = BufferReader.ReadBytes(length); prefix.SetValue(offset, length); } private void ReadDictionaryName(StringHandle s) { int key = ReadDictionaryKey(); s.SetValue(key); } private XmlBinaryNodeType GetNodeType() { return BufferReader.GetNodeType(); } private void SkipNodeType() { BufferReader.SkipNodeType(); } private int ReadDictionaryKey() { return BufferReader.ReadDictionaryKey(); } private int ReadMultiByteUInt31() { return BufferReader.ReadMultiByteUInt31(); } private int ReadUInt8() { return BufferReader.ReadUInt8(); } private int ReadUInt16() { return BufferReader.ReadUInt16(); } private int ReadUInt31() { return BufferReader.ReadUInt31(); } private bool IsValidArrayType(XmlBinaryNodeType nodeType) { switch (nodeType) { case XmlBinaryNodeType.BoolTextWithEndElement: case XmlBinaryNodeType.Int16TextWithEndElement: case XmlBinaryNodeType.Int32TextWithEndElement: case XmlBinaryNodeType.Int64TextWithEndElement: case XmlBinaryNodeType.FloatTextWithEndElement: case XmlBinaryNodeType.DoubleTextWithEndElement: case XmlBinaryNodeType.DecimalTextWithEndElement: case XmlBinaryNodeType.DateTimeTextWithEndElement: case XmlBinaryNodeType.TimeSpanTextWithEndElement: case XmlBinaryNodeType.GuidTextWithEndElement: return true; default: return false; } } private void ReadArray() { if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion XmlExceptionHelper.ThrowInvalidBinaryFormat(this); ReadNode(); // ReadStartElement if (this.Node.NodeType != XmlNodeType.Element) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion XmlExceptionHelper.ThrowInvalidBinaryFormat(this); ReadNode(); // ReadEndElement if (this.Node.NodeType != XmlNodeType.EndElement) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); _arrayState = ArrayState.Element; _arrayNodeType = GetNodeType(); if (!IsValidArrayType(_arrayNodeType)) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); SkipNodeType(); _arrayCount = ReadMultiByteUInt31(); if (_arrayCount == 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); MoveToArrayElement(); } private void MoveToArrayElement() { _arrayState = ArrayState.Element; MoveToNode(ElementNode); } private void SkipArrayElements(int count) { _arrayCount -= count; if (_arrayCount == 0) { _arrayState = ArrayState.None; ExitScope(); ReadNode(); } } public override bool IsStartArray(out Type type) { type = null; if (_arrayState != ArrayState.Element) return false; switch (_arrayNodeType) { case XmlBinaryNodeType.BoolTextWithEndElement: type = typeof(bool); break; case XmlBinaryNodeType.Int16TextWithEndElement: type = typeof(Int16); break; case XmlBinaryNodeType.Int32TextWithEndElement: type = typeof(Int32); break; case XmlBinaryNodeType.Int64TextWithEndElement: type = typeof(Int64); break; case XmlBinaryNodeType.FloatTextWithEndElement: type = typeof(float); break; case XmlBinaryNodeType.DoubleTextWithEndElement: type = typeof(double); break; case XmlBinaryNodeType.DecimalTextWithEndElement: type = typeof(decimal); break; case XmlBinaryNodeType.DateTimeTextWithEndElement: type = typeof(DateTime); break; case XmlBinaryNodeType.GuidTextWithEndElement: type = typeof(Guid); break; case XmlBinaryNodeType.TimeSpanTextWithEndElement: type = typeof(TimeSpan); break; case XmlBinaryNodeType.UniqueIdTextWithEndElement: type = typeof(UniqueId); break; default: return false; } return true; } public override bool TryGetArrayLength(out int count) { count = 0; if (!_buffered) return false; if (_arrayState != ArrayState.Element) return false; count = _arrayCount; return true; } private bool IsStartArray(string localName, string namespaceUri, XmlBinaryNodeType nodeType) { return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType; } private bool IsStartArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, XmlBinaryNodeType nodeType) { return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType; } private void CheckArray(Array array, int offset, int count) { if (array == null) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array")); if (offset < 0) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", string.Format(SRSerialization.ValueMustBeNonNegative))); if (offset > array.Length) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", string.Format(SRSerialization.OffsetExceedsBufferSize, array.Length))); if (count < 0) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", string.Format(SRSerialization.ValueMustBeNonNegative))); if (count > array.Length - offset) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", string.Format(SRSerialization.SizeExceedsRemainingBufferSpace, array.Length - offset))); } // bool /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] private unsafe int ReadArray(bool[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (bool* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // Int16 /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] private unsafe int ReadArray(Int16[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (Int16* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, Int16[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int16[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // Int32 /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] private unsafe int ReadArray(Int32[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (Int32* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, Int32[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int32[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // Int64 /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] private unsafe int ReadArray(Int64[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (Int64* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, Int64[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int64[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // float /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] private unsafe int ReadArray(float[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (float* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // double /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] private unsafe int ReadArray(double[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (double* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // decimal /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] private unsafe int ReadArray(decimal[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); fixed (decimal* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // DateTime private int ReadArray(DateTime[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); for (int i = 0; i < actual; i++) { array[offset + i] = BufferReader.ReadDateTime(); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // Guid private int ReadArray(Guid[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); for (int i = 0; i < actual; i++) { array[offset + i] = BufferReader.ReadGuid(); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // TimeSpan private int ReadArray(TimeSpan[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, _arrayCount); for (int i = 0; i < actual; i++) { array[offset + i] = BufferReader.ReadTimeSpan(); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } private enum ArrayState { None, Element, Content } } }
// SubmissionEditPanel.Designer.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### namespace Submissions { partial class SubmissionEditPanel { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.panel1 = new System.Windows.Forms.Panel(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.notes = new System.Windows.Forms.RichTextBox(); this.panel2 = new System.Windows.Forms.Panel(); this.textDaysOut = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.dateReply = new System.Windows.Forms.DateTimePicker(); this.rights = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.earned = new System.Windows.Forms.NumericUpDown(); this.feedback = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.replytype = new System.Windows.Forms.ComboBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label11 = new System.Windows.Forms.Label(); this.textBoxDraft = new System.Windows.Forms.TextBox(); this.textBoxSale = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.labelHiatus = new System.Windows.Forms.Label(); this.prioritylabel = new System.Windows.Forms.Label(); this.ePriority = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.dateSubmission = new System.Windows.Forms.DateTimePicker(); this.postage = new System.Windows.Forms.NumericUpDown(); this.label3 = new System.Windows.Forms.Label(); this.SubmissionType = new System.Windows.Forms.ComboBox(); this.panelHeader = new System.Windows.Forms.Panel(); // this.editMarketName = new System.Windows.Forms.LinkLabel(); this.labelMarket = new System.Windows.Forms.Label(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.panel1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.panel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.earned)).BeginInit(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.postage)).BeginInit(); this.panelHeader.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.AutoScroll = true; this.panel1.BackColor = System.Drawing.SystemColors.Control; this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.groupBox2); this.panel1.Controls.Add(this.groupBox1); this.panel1.Controls.Add(this.panelHeader); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Padding = new System.Windows.Forms.Padding(5); this.panel1.Size = new System.Drawing.Size(740, 501); this.panel1.TabIndex = 0; // // groupBox2 // this.groupBox2.BackColor = System.Drawing.SystemColors.ControlDark; this.groupBox2.Controls.Add(this.groupBox3); this.groupBox2.Controls.Add(this.panel2); this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.groupBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox2.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.groupBox2.Location = new System.Drawing.Point(5, 184); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(728, 310); this.groupBox2.TabIndex = 17; this.groupBox2.TabStop = false; this.groupBox2.Text = "Reply Details"; // // groupBox3 // this.groupBox3.Controls.Add(this.notes); this.groupBox3.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox3.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.groupBox3.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox3.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.groupBox3.Location = new System.Drawing.Point(313, 22); this.groupBox3.Name = "groupBox3"; this.groupBox3.Padding = new System.Windows.Forms.Padding(5); this.groupBox3.Size = new System.Drawing.Size(412, 285); this.groupBox3.TabIndex = 18; this.groupBox3.TabStop = false; this.groupBox3.Text = " Notes"; // // notes // this.notes.Dock = System.Windows.Forms.DockStyle.Fill; this.notes.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.notes.Location = new System.Drawing.Point(5, 20); this.notes.Name = "notes"; this.notes.Size = new System.Drawing.Size(402, 260); this.notes.TabIndex = 9; // this.notes.Text = global::Worgan2006.Header.Blank; this.notes.TextChanged += new System.EventHandler(this.notes_TextChanged); // // panel2 // this.panel2.BackColor = System.Drawing.SystemColors.ControlDark; this.panel2.Controls.Add(this.textDaysOut); this.panel2.Controls.Add(this.label9); this.panel2.Controls.Add(this.label4); this.panel2.Controls.Add(this.dateReply); this.panel2.Controls.Add(this.rights); this.panel2.Controls.Add(this.label5); this.panel2.Controls.Add(this.label8); this.panel2.Controls.Add(this.label7); this.panel2.Controls.Add(this.earned); this.panel2.Controls.Add(this.feedback); this.panel2.Controls.Add(this.label6); this.panel2.Controls.Add(this.replytype); this.panel2.Dock = System.Windows.Forms.DockStyle.Left; this.panel2.Location = new System.Drawing.Point(3, 22); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(310, 285); this.panel2.TabIndex = 4; // // textDaysOut // this.textDaysOut.Location = new System.Drawing.Point(138, 229); this.textDaysOut.Name = "textDaysOut"; this.textDaysOut.ReadOnly = true; this.textDaysOut.Size = new System.Drawing.Size(162, 26); this.textDaysOut.TabIndex = 17; this.toolTip1.SetToolTip(this.textDaysOut, "If this submission has not been \"returned\" this field will \r\ndisplay the number o" + "f days since submission until today.\r\nOtherwise, it will use the reply date as t" + "he end date.\r\n"); // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label9.Location = new System.Drawing.Point(3, 229); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(73, 16); this.label9.TabIndex = 18; this.label9.Text = "Days Out"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label4.Location = new System.Drawing.Point(3, 13); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(118, 16); this.label4.TabIndex = 8; this.label4.Text = "Amount of Sale"; // // dateReply // this.dateReply.Enabled = false; this.dateReply.Location = new System.Drawing.Point(138, 47); this.dateReply.Name = "dateReply"; this.dateReply.Size = new System.Drawing.Size(162, 26); this.dateReply.TabIndex = 5; this.dateReply.ValueChanged += new System.EventHandler(this.dateReply_ValueChanged); // // rights // this.rights.Location = new System.Drawing.Point(138, 149); this.rights.Multiline = true; this.rights.Name = "rights"; this.rights.Size = new System.Drawing.Size(162, 74); this.rights.TabIndex = 8; this.rights.TextChanged += new System.EventHandler(this.rights_TextChanged); // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label5.Location = new System.Drawing.Point(3, 47); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(85, 16); this.label5.TabIndex = 10; this.label5.Text = "Reply Date"; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label8.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label8.Location = new System.Drawing.Point(3, 149); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(88, 16); this.label8.TabIndex = 16; this.label8.Text = "Rights Sold"; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label7.Location = new System.Drawing.Point(3, 84); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(89, 16); this.label7.TabIndex = 14; this.label7.Text = "Reply Type"; // // earned // this.earned.DecimalPlaces = 2; this.earned.Location = new System.Drawing.Point(138, 13); this.earned.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.earned.Name = "earned"; this.earned.Size = new System.Drawing.Size(162, 26); this.earned.TabIndex = 4; this.earned.ValueChanged += new System.EventHandler(this.earned_ValueChanged); // // feedback // this.feedback.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.feedback.FormattingEnabled = true; this.feedback.Location = new System.Drawing.Point(138, 115); this.feedback.Name = "feedback"; this.feedback.Size = new System.Drawing.Size(162, 28); this.feedback.TabIndex = 7; this.feedback.SelectedIndexChanged += new System.EventHandler(this.feedback_SelectedIndexChanged); // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label6.Location = new System.Drawing.Point(3, 115); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(120, 16); this.label6.TabIndex = 12; this.label6.Text = "Reply Feedback"; // // replytype // this.replytype.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.replytype.FormattingEnabled = true; this.replytype.Location = new System.Drawing.Point(138, 79); this.replytype.Name = "replytype"; this.replytype.Size = new System.Drawing.Size(162, 28); this.replytype.TabIndex = 6; this.replytype.SelectedIndexChanged += new System.EventHandler(this.replytype_SelectedIndexChanged); // // groupBox1 // this.groupBox1.BackColor = System.Drawing.SystemColors.ControlDark; this.groupBox1.Controls.Add(this.label11); this.groupBox1.Controls.Add(this.textBoxDraft); this.groupBox1.Controls.Add(this.textBoxSale); this.groupBox1.Controls.Add(this.label10); this.groupBox1.Controls.Add(this.labelHiatus); this.groupBox1.Controls.Add(this.prioritylabel); this.groupBox1.Controls.Add(this.ePriority); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.dateSubmission); this.groupBox1.Controls.Add(this.postage); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.SubmissionType); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top; this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox1.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.groupBox1.Location = new System.Drawing.Point(5, 32); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(728, 152); this.groupBox1.TabIndex = 16; this.groupBox1.TabStop = false; this.groupBox1.Text = "Submission Details"; // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label11.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label11.Location = new System.Drawing.Point(315, 33); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(80, 16); this.label11.TabIndex = 12; this.label11.Text = "Draft Sent"; this.toolTip1.SetToolTip(this.label11, "Enter the version (i.e., draft 1, draft 2) of this story that was submitted."); // // textBoxDraft // this.textBoxDraft.Location = new System.Drawing.Point(432, 27); this.textBoxDraft.Name = "textBoxDraft"; this.textBoxDraft.Size = new System.Drawing.Size(200, 26); this.textBoxDraft.TabIndex = 11; this.textBoxDraft.TextChanged += new System.EventHandler(this.textBoxDraft_TextChanged); // // textBoxSale // this.textBoxSale.Location = new System.Drawing.Point(432, 97); this.textBoxSale.Name = "textBoxSale"; this.textBoxSale.ReadOnly = true; this.textBoxSale.Size = new System.Drawing.Size(80, 26); this.textBoxSale.TabIndex = 10; // // label10 // this.label10.AutoSize = true; this.label10.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label10.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label10.Location = new System.Drawing.Point(315, 97); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(106, 16); this.label10.TabIndex = 9; this.label10.Text = "Potential Sale"; this.toolTip1.SetToolTip(this.label10, "This is an estimate of how much this submission would earn, if accepted"); // // labelHiatus // this.labelHiatus.AutoSize = true; this.labelHiatus.BackColor = System.Drawing.Color.Orange; this.labelHiatus.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.labelHiatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelHiatus.ForeColor = System.Drawing.Color.SteelBlue; this.labelHiatus.Location = new System.Drawing.Point(171, 126); this.labelHiatus.Name = "labelHiatus"; this.labelHiatus.Size = new System.Drawing.Size(309, 20); this.labelHiatus.TabIndex = 8; this.labelHiatus.Text = "Market on Hiatus or outside reading period"; this.labelHiatus.Visible = false; // // prioritylabel // this.prioritylabel.AutoSize = true; this.prioritylabel.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.prioritylabel.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.prioritylabel.Location = new System.Drawing.Point(6, 103); this.prioritylabel.Name = "prioritylabel"; this.prioritylabel.Size = new System.Drawing.Size(65, 16); this.prioritylabel.TabIndex = 7; this.prioritylabel.Text = "Priority"; this.toolTip1.SetToolTip(this.prioritylabel, "For destinations this number will be used to rank the markets\r\n "); // // ePriority // this.ePriority.Location = new System.Drawing.Point(141, 99); this.ePriority.Name = "ePriority"; this.ePriority.Size = new System.Drawing.Size(80, 26); this.ePriority.TabIndex = 6; this.ePriority.TextChanged += new System.EventHandler(this.ePriority_TextChanged); // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label2.Location = new System.Drawing.Point(6, 33); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(129, 16); this.label2.TabIndex = 2; this.label2.Text = "Submission Date"; this.label2.Click += new System.EventHandler(this.label2_Click); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label1.Location = new System.Drawing.Point(315, 65); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(63, 16); this.label1.TabIndex = 1; this.label1.Text = "Postage"; // // dateSubmission // this.dateSubmission.Location = new System.Drawing.Point(141, 33); this.dateSubmission.Name = "dateSubmission"; this.dateSubmission.Size = new System.Drawing.Size(162, 26); this.dateSubmission.TabIndex = 1; this.dateSubmission.ValueChanged += new System.EventHandler(this.dateSubmission_ValueChanged); // // postage // this.postage.DecimalPlaces = 2; this.postage.Location = new System.Drawing.Point(432, 65); this.postage.Maximum = new decimal(new int[] { 1000000, 0, 0, 0}); this.postage.Name = "postage"; this.postage.Size = new System.Drawing.Size(162, 26); this.postage.TabIndex = 3; this.postage.ValueChanged += new System.EventHandler(this.postage_ValueChanged); // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Georgia", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.label3.Location = new System.Drawing.Point(6, 65); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(133, 16); this.label3.TabIndex = 5; this.label3.Text = "Submission Type"; // // SubmissionType // this.SubmissionType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.SubmissionType.FormattingEnabled = true; this.SubmissionType.Location = new System.Drawing.Point(141, 65); this.SubmissionType.Name = "SubmissionType"; this.SubmissionType.Size = new System.Drawing.Size(162, 28); this.SubmissionType.TabIndex = 2; this.SubmissionType.SelectedIndexChanged += new System.EventHandler(this.SubmissionType_SelectedIndexChanged); // // panelHeader // this.panelHeader.BackColor = System.Drawing.SystemColors.ControlDark; this.panelHeader.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; // this.panelHeader.Controls.Add(this.editMarketName); this.panelHeader.Controls.Add(this.labelMarket); this.panelHeader.Dock = System.Windows.Forms.DockStyle.Top; this.panelHeader.Location = new System.Drawing.Point(5, 5); this.panelHeader.Name = "panelHeader"; this.panelHeader.Size = new System.Drawing.Size(728, 27); this.panelHeader.TabIndex = 0; // // editMarketName // // this.editMarketName.AutoSize = true; // this.editMarketName.Dock = System.Windows.Forms.DockStyle.Left; // this.editMarketName.Location = new System.Drawing.Point(219, 0); // this.editMarketName.Name = "editMarketName"; // this.editMarketName.Size = new System.Drawing.Size(50, 13); // this.editMarketName.TabIndex = 0; // this.editMarketName.TabStop = true; // this.editMarketName.Text = "(Change)"; // this.editMarketName.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.editMarketName_LinkClicked); // // labelMarket // this.labelMarket.AutoSize = true; this.labelMarket.Cursor = System.Windows.Forms.Cursors.Hand; this.labelMarket.Dock = System.Windows.Forms.DockStyle.Left; this.labelMarket.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelMarket.Location = new System.Drawing.Point(0, 0); this.labelMarket.Name = "labelMarket"; this.labelMarket.Size = new System.Drawing.Size(219, 24); this.labelMarket.TabIndex = 0; this.labelMarket.Text = "Select or add a market"; this.labelMarket.Click += new System.EventHandler(this.labelMarket_Click); // // SubmissionEditPanel // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.Black; this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.Controls.Add(this.panel1); this.Name = "SubmissionEditPanel"; this.Size = new System.Drawing.Size(740, 501); this.Load += new System.EventHandler(this.SubmissionEditPanel_Load); this.Leave += new System.EventHandler(this.SubmissionEditPanel_Leave); this.panel1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.earned)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.postage)).EndInit(); this.panelHeader.ResumeLayout(false); this.panelHeader.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panelHeader; // private System.Windows.Forms.LinkLabel editMarketName; private System.Windows.Forms.ComboBox SubmissionType; private System.Windows.Forms.Label label3; private System.Windows.Forms.NumericUpDown postage; private System.Windows.Forms.DateTimePicker dateSubmission; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox feedback; private System.Windows.Forms.Label label6; private System.Windows.Forms.DateTimePicker dateReply; private System.Windows.Forms.Label label5; private System.Windows.Forms.NumericUpDown earned; private System.Windows.Forms.Label label4; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.ComboBox replytype; private System.Windows.Forms.Label label7; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.TextBox rights; private System.Windows.Forms.Label label8; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.TextBox textDaysOut; private System.Windows.Forms.Label label9; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.TextBox ePriority; private System.Windows.Forms.Label prioritylabel; public System.Windows.Forms.RichTextBox notes; public System.Windows.Forms.Label labelHiatus; private System.Windows.Forms.Label labelMarket; private System.Windows.Forms.TextBox textBoxSale; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox textBoxDraft; } }