context
stringlengths
2.52k
185k
gt
stringclasses
1 value
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 AspNetIdentityWebAPIDemo.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; } } }
// ReSharper disable All using System.Collections.Generic; using System.Dynamic; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; using Frapid.WebApi; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Email Queues. /// </summary> [RoutePrefix("api/v1.0/config/email-queue")] public class EmailQueueController : FrapidApiController { /// <summary> /// The EmailQueue repository. /// </summary> private IEmailQueueRepository EmailQueueRepository; public EmailQueueController() { } public EmailQueueController(IEmailQueueRepository repository) { this.EmailQueueRepository = repository; } protected override void Initialize(HttpControllerContext context) { base.Initialize(context); if (this.EmailQueueRepository == null) { this.EmailQueueRepository = new Frapid.Config.DataAccess.EmailQueue { _Catalog = this.MetaUser.Catalog, _LoginId = this.MetaUser.LoginId, _UserId = this.MetaUser.UserId }; } } /// <summary> /// Creates meta information of "email queue" entity. /// </summary> /// <returns>Returns the "email queue" meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("meta")] [Route("~/api/config/email-queue/meta")] [RestAuthorize] public EntityView GetEntityView() { return new EntityView { PrimaryKey = "queue_id", Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "queue_id", PropertyName = "QueueId", DataType = "long", DbDataType = "int8", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "from_name", PropertyName = "FromName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "reply_to", PropertyName = "ReplyTo", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "subject", PropertyName = "Subject", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "send_to", PropertyName = "SendTo", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "attachments", PropertyName = "Attachments", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "message", PropertyName = "Message", DataType = "string", DbDataType = "text", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "added_on", PropertyName = "AddedOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "delivered", PropertyName = "Delivered", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "delivered_on", PropertyName = "DeliveredOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "canceled", PropertyName = "Canceled", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "canceled_on", PropertyName = "CanceledOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 } } }; } /// <summary> /// Counts the number of email queues. /// </summary> /// <returns>Returns the count of the email queues.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/config/email-queue/count")] [RestAuthorize] public long Count() { try { return this.EmailQueueRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns all collection of email queue. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("all")] [Route("~/api/config/email-queue/all")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> GetAll() { try { return this.EmailQueueRepository.GetAll(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of email queue for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("~/api/config/email-queue/export")] [RestAuthorize] public IEnumerable<dynamic> Export() { try { return this.EmailQueueRepository.Export(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns an instance of email queue. /// </summary> /// <param name="queueId">Enter QueueId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("{queueId}")] [Route("~/api/config/email-queue/{queueId}")] [RestAuthorize] public Frapid.Config.Entities.EmailQueue Get(long queueId) { try { return this.EmailQueueRepository.Get(queueId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } [AcceptVerbs("GET", "HEAD")] [Route("get")] [Route("~/api/config/email-queue/get")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> Get([FromUri] long[] queueIds) { try { return this.EmailQueueRepository.Get(queueIds); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the first instance of email queue. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("first")] [Route("~/api/config/email-queue/first")] [RestAuthorize] public Frapid.Config.Entities.EmailQueue GetFirst() { try { return this.EmailQueueRepository.GetFirst(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the previous instance of email queue. /// </summary> /// <param name="queueId">Enter QueueId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("previous/{queueId}")] [Route("~/api/config/email-queue/previous/{queueId}")] [RestAuthorize] public Frapid.Config.Entities.EmailQueue GetPrevious(long queueId) { try { return this.EmailQueueRepository.GetPrevious(queueId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the next instance of email queue. /// </summary> /// <param name="queueId">Enter QueueId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("next/{queueId}")] [Route("~/api/config/email-queue/next/{queueId}")] [RestAuthorize] public Frapid.Config.Entities.EmailQueue GetNext(long queueId) { try { return this.EmailQueueRepository.GetNext(queueId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the last instance of email queue. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("last")] [Route("~/api/config/email-queue/last")] [RestAuthorize] public Frapid.Config.Entities.EmailQueue GetLast() { try { return this.EmailQueueRepository.GetLast(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 email queues on each page, sorted by the property QueueId. /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/config/email-queue")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> GetPaginatedResult() { try { return this.EmailQueueRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 email queues on each page, sorted by the property QueueId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/config/email-queue/page/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> GetPaginatedResult(long pageNumber) { try { return this.EmailQueueRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of email queues using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered email queues.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/config/email-queue/count-where")] [RestAuthorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.EmailQueueRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 email queues on each page, sorted by the property QueueId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/config/email-queue/get-where/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.EmailQueueRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of email queues using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered email queues.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/config/email-queue/count-filtered/{filterName}")] [RestAuthorize] public long CountFiltered(string filterName) { try { return this.EmailQueueRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 email queues on each page, sorted by the property QueueId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/config/email-queue/get-filtered/{pageNumber}/{filterName}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> GetFiltered(long pageNumber, string filterName) { try { return this.EmailQueueRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Displayfield is a lightweight key/value collection of email queues. /// </summary> /// <returns>Returns an enumerable key/value collection of email queues.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/config/email-queue/display-fields")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { try { return this.EmailQueueRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for email queues. /// </summary> /// <returns>Returns an enumerable custom field collection of email queues.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields")] [Route("~/api/config/email-queue/custom-fields")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields() { try { return this.EmailQueueRepository.GetCustomFields(null); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for email queues. /// </summary> /// <returns>Returns an enumerable custom field collection of email queues.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields/{resourceId}")] [Route("~/api/config/email-queue/custom-fields/{resourceId}")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { try { return this.EmailQueueRepository.GetCustomFields(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds or edits your instance of EmailQueue class. /// </summary> /// <param name="emailQueue">Your instance of email queues class to add or edit.</param> [AcceptVerbs("POST")] [Route("add-or-edit")] [Route("~/api/config/email-queue/add-or-edit")] [RestAuthorize] public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form) { dynamic emailQueue = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer()); List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer()); if (emailQueue == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { return this.EmailQueueRepository.AddOrEdit(emailQueue, customFields); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds your instance of EmailQueue class. /// </summary> /// <param name="emailQueue">Your instance of email queues class to add.</param> [AcceptVerbs("POST")] [Route("add/{emailQueue}")] [Route("~/api/config/email-queue/add/{emailQueue}")] [RestAuthorize] public void Add(Frapid.Config.Entities.EmailQueue emailQueue) { if (emailQueue == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.EmailQueueRepository.Add(emailQueue); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Edits existing record with your instance of EmailQueue class. /// </summary> /// <param name="emailQueue">Your instance of EmailQueue class to edit.</param> /// <param name="queueId">Enter the value for QueueId in order to find and edit the existing record.</param> [AcceptVerbs("PUT")] [Route("edit/{queueId}")] [Route("~/api/config/email-queue/edit/{queueId}")] [RestAuthorize] public void Edit(long queueId, [FromBody] Frapid.Config.Entities.EmailQueue emailQueue) { if (emailQueue == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.EmailQueueRepository.Update(emailQueue, queueId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } private List<ExpandoObject> ParseCollection(JArray collection) { return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings()); } /// <summary> /// Adds or edits multiple instances of EmailQueue class. /// </summary> /// <param name="collection">Your collection of EmailQueue class to bulk import.</param> /// <returns>Returns list of imported queueIds.</returns> /// <exception cref="DataAccessException">Thrown when your any EmailQueue class in the collection is invalid or malformed.</exception> [AcceptVerbs("POST")] [Route("bulk-import")] [Route("~/api/config/email-queue/bulk-import")] [RestAuthorize] public List<object> BulkImport([FromBody]JArray collection) { List<ExpandoObject> emailQueueCollection = this.ParseCollection(collection); if (emailQueueCollection == null || emailQueueCollection.Count.Equals(0)) { return null; } try { return this.EmailQueueRepository.BulkImport(emailQueueCollection); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Deletes an existing instance of EmailQueue class via QueueId. /// </summary> /// <param name="queueId">Enter the value for QueueId in order to find and delete the existing record.</param> [AcceptVerbs("DELETE")] [Route("delete/{queueId}")] [Route("~/api/config/email-queue/delete/{queueId}")] [RestAuthorize] public void Delete(long queueId) { try { this.EmailQueueRepository.Delete(queueId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using JetBrains.Annotations; namespace NLog { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Threading; using NLog.Common; using NLog.Internal; using NLog.Layouts; using NLog.MessageTemplates; using NLog.Time; /// <summary> /// Represents the logging event. /// </summary> public class LogEventInfo { /// <summary> /// Gets the date of the first log event created. /// </summary> public static readonly DateTime ZeroDate = DateTime.UtcNow; internal static readonly LogMessageFormatter StringFormatMessageFormatter = GetStringFormatMessageFormatter; internal static LogMessageFormatter DefaultMessageFormatter { get; private set; } = LogMessageTemplateFormatter.DefaultAuto.MessageFormatter; private static int globalSequenceId; /// <summary> /// The formatted log message. /// </summary> private string _formattedMessage; /// <summary> /// The log message including any parameter placeholders /// </summary> private string _message; private object[] _parameters; private IFormatProvider _formatProvider; private LogMessageFormatter _messageFormatter = DefaultMessageFormatter; private IDictionary<Layout, object> _layoutCache; private PropertiesDictionary _properties; /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> public LogEventInfo() { TimeStamp = TimeSource.Current.Time; SequenceID = Interlocked.Increment(ref globalSequenceId); } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Logger name.</param> /// <param name="message">Log message including parameter placeholders.</param> public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message) : this(level, loggerName, null, message, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Logger name.</param> /// <param name="message">Log message including parameter placeholders.</param> /// <param name="messageTemplateParameters">Log message including parameter placeholders.</param> public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message, IList<MessageTemplateParameter> messageTemplateParameters) : this(level, loggerName, null, message, null, null) { if (messageTemplateParameters != null && messageTemplateParameters.Count > 0) { _properties = new PropertiesDictionary(messageTemplateParameters); } } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Logger name.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">Log message including parameter placeholders.</param> /// <param name="parameters">Parameter array.</param> public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters) : this(level, loggerName, formatProvider, message, parameters, null) { } /// <summary> /// Initializes a new instance of the <see cref="LogEventInfo" /> class. /// </summary> /// <param name="level">Log level.</param> /// <param name="loggerName">Logger name.</param> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">Log message including parameter placeholders.</param> /// <param name="parameters">Parameter array.</param> /// <param name="exception">Exception information.</param> public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters, Exception exception): this() { Level = level; LoggerName = loggerName; Message = message; Parameters = parameters; FormatProvider = formatProvider; Exception = exception; if (NeedToPreformatMessage(parameters)) { CalcFormattedMessage(); } } /// <summary> /// Gets the unique identifier of log event which is automatically generated /// and monotonously increasing. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID", Justification = "Backwards compatibility")] // ReSharper disable once InconsistentNaming public int SequenceID { get; private set; } /// <summary> /// Gets or sets the timestamp of the logging event. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp", Justification = "Backwards compatibility.")] public DateTime TimeStamp { get; set; } /// <summary> /// Gets or sets the level of the logging event. /// </summary> public LogLevel Level { get; set; } [CanBeNull] internal CallSiteInformation CallSiteInformation { get; private set; } [NotNull] internal CallSiteInformation GetCallSiteInformationInternal() { return CallSiteInformation ?? (CallSiteInformation = new CallSiteInformation()); } /// <summary> /// Gets a value indicating whether stack trace has been set for this event. /// </summary> public bool HasStackTrace => CallSiteInformation?.StackTrace != null; /// <summary> /// Gets the stack frame of the method that did the logging. /// </summary> public StackFrame UserStackFrame => CallSiteInformation?.UserStackFrame; /// <summary> /// Gets the number index of the stack frame that represents the user /// code (not the NLog code). /// </summary> public int UserStackFrameNumber => CallSiteInformation?.UserStackFrameNumberLegacy ?? CallSiteInformation?.UserStackFrameNumber ?? 0; /// <summary> /// Gets the entire stack trace. /// </summary> public StackTrace StackTrace => CallSiteInformation?.StackTrace; /// <summary> /// Gets the callsite class name /// </summary> public string CallerClassName => CallSiteInformation?.GetCallerClassName(null, true, true, true); /// <summary> /// Gets the callsite member function name /// </summary> public string CallerMemberName => CallSiteInformation?.GetCallerMemberName(null, false, true, true); /// <summary> /// Gets the callsite source file path /// </summary> public string CallerFilePath => CallSiteInformation?.GetCallerFilePath(0); /// <summary> /// Gets the callsite source file line number /// </summary> public int CallerLineNumber => CallSiteInformation?.GetCallerLineNumber(0) ?? 0; /// <summary> /// Gets or sets the exception information. /// </summary> [CanBeNull] public Exception Exception { get; set; } /// <summary> /// Gets or sets the logger name. /// </summary> [CanBeNull] public string LoggerName { get; set; } /// <summary> /// Gets the logger short name. /// </summary> /// <remarks>This property was marked as obsolete on NLog 2.0 and it may be removed in a future release.</remarks> [Obsolete("This property should not be used. Marked obsolete on NLog 2.0")] public string LoggerShortName { // NOTE: This property is not referenced by NLog code anymore. get { if (LoggerName == null) return LoggerName; int lastDot = LoggerName.LastIndexOf('.'); if (lastDot >= 0) { return LoggerName.Substring(lastDot + 1); } return LoggerName; } } /// <summary> /// Gets or sets the log message including any parameter placeholders. /// </summary> public string Message { get => _message; set { bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters(); _message = value; ResetFormattedMessage(rebuildMessageTemplateParameters); } } /// <summary> /// Gets or sets the parameter values or null if no parameters have been specified. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "For backwards compatibility.")] public object[] Parameters { get => _parameters; set { bool rebuildMessageTemplateParameters = ResetMessageTemplateParameters(); _parameters = value; ResetFormattedMessage(rebuildMessageTemplateParameters); } } /// <summary> /// Gets or sets the format provider that was provided while logging or <see langword="null" /> /// when no formatProvider was specified. /// </summary> public IFormatProvider FormatProvider { get => _formatProvider; set { if (_formatProvider != value) { _formatProvider = value; ResetFormattedMessage(false); } } } /// <summary> /// Gets or sets the message formatter for generating <see cref="LogEventInfo.FormattedMessage"/> /// Uses string.Format(...) when nothing else has been configured. /// </summary> public LogMessageFormatter MessageFormatter { get => _messageFormatter; set { _messageFormatter = value ?? StringFormatMessageFormatter; ResetFormattedMessage(false); } } /// <summary> /// Gets the formatted message. /// </summary> public string FormattedMessage { get { if (_formattedMessage == null) { CalcFormattedMessage(); } return _formattedMessage; } } /// <summary> /// Checks if any per-event properties (Without allocation) /// </summary> public bool HasProperties { get { if (_properties != null) { return _properties.Count > 0; } else { return CreateOrUpdatePropertiesInternal(false)?.Count > 0; } } } /// <summary> /// Gets the dictionary of per-event context properties. /// </summary> public IDictionary<object, object> Properties => CreateOrUpdatePropertiesInternal(); /// <summary> /// Gets the dictionary of per-event context properties. /// Internal helper for the PropertiesDictionary type. /// </summary> /// <param name="forceCreate">Create the event-properties dictionary, even if no initial template parameters</param> /// <param name="templateParameters">Provided when having parsed the message template and capture template parameters (else null)</param> /// <returns></returns> internal PropertiesDictionary CreateOrUpdatePropertiesInternal(bool forceCreate = true, IList<MessageTemplateParameter> templateParameters = null) { var properties = _properties; if (properties == null) { if (forceCreate || templateParameters?.Count > 0 || (templateParameters == null && HasMessageTemplateParameters)) { properties = new PropertiesDictionary(templateParameters); Interlocked.CompareExchange(ref _properties, properties, null); if (templateParameters == null && (!forceCreate || HasMessageTemplateParameters)) { // Trigger capture of MessageTemplateParameters from logevent-message CalcFormattedMessage(); } } } else if (templateParameters != null) { properties.MessageProperties = templateParameters; } return _properties; } private bool HasMessageTemplateParameters { get { // Have not yet parsed/rendered the FormattedMessage, so check with ILogMessageFormatter if (_formattedMessage == null && _parameters?.Length > 0) { var logMessageFormatter = _messageFormatter?.Target as ILogMessageFormatter; return logMessageFormatter?.HasProperties(this) ?? false; } return false; } } /// <summary> /// Gets the named parameters extracted from parsing <see cref="Message"/> as MessageTemplate /// </summary> public MessageTemplateParameters MessageTemplateParameters { get { if (_properties != null && _properties.MessageProperties.Count > 0) { return new MessageTemplateParameters(_properties.MessageProperties, _message, _parameters); } else if (_parameters?.Length > 0) { return new MessageTemplateParameters(_message, _parameters); } else { return MessageTemplateParameters.Empty; // No parameters, means nothing to parse } } } /// <summary> /// Gets the dictionary of per-event context properties. /// </summary> /// <remarks>This property was marked as obsolete on NLog 2.0 and it may be removed in a future release.</remarks> [Obsolete("Use LogEventInfo.Properties instead. Marked obsolete on NLog 2.0", true)] public IDictionary Context => CreateOrUpdatePropertiesInternal().EventContext; /// <summary> /// Creates the null event. /// </summary> /// <returns>Null log event.</returns> public static LogEventInfo CreateNullEvent() { return new LogEventInfo(LogLevel.Off, string.Empty, string.Empty); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Name of the logger.</param> /// <param name="message">The message.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message) { return new LogEventInfo(logLevel, loggerName, null, message, null); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Name of the logger.</param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <param name="parameters">The parameters.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters) { return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Name of the logger.</param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, object message) { Exception exception = message as Exception; if (exception == null && message is LogEventInfo logEvent) { logEvent.LoggerName = loggerName; logEvent.Level = logLevel; logEvent.FormatProvider = formatProvider ?? logEvent.FormatProvider; return logEvent; } return new LogEventInfo(logLevel, loggerName, formatProvider, "{0}", new[] { message }, exception); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Name of the logger.</param> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("use Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, string message) instead. Marked obsolete before v4.3.11")] public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message, Exception exception) { return new LogEventInfo(logLevel, loggerName, null, message, null, exception); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Name of the logger.</param> /// <param name="exception">The exception.</param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message) { return Create(logLevel, loggerName, exception, formatProvider, message, null); } /// <summary> /// Creates the log event. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="loggerName">Name of the logger.</param> /// <param name="exception">The exception.</param> /// <param name="formatProvider">The format provider.</param> /// <param name="message">The message.</param> /// <param name="parameters">The parameters.</param> /// <returns>Instance of <see cref="LogEventInfo"/>.</returns> public static LogEventInfo Create(LogLevel logLevel, string loggerName, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters) { return new LogEventInfo(logLevel, loggerName,formatProvider, message, parameters, exception); } /// <summary> /// Creates <see cref="AsyncLogEventInfo"/> from this <see cref="LogEventInfo"/> by attaching the specified asynchronous continuation. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <returns>Instance of <see cref="AsyncLogEventInfo"/> with attached continuation.</returns> public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation) { return new AsyncLogEventInfo(this, asyncContinuation); } /// <summary> /// Returns a string representation of this log event. /// </summary> /// <returns>String representation of the log event.</returns> public override string ToString() { return $"Log Event: Logger='{LoggerName}' Level={Level} Message='{FormattedMessage}' SequenceID={SequenceID}"; } /// <summary> /// Sets the stack trace for the event info. /// </summary> /// <param name="stackTrace">The stack trace.</param> /// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param> public void SetStackTrace(StackTrace stackTrace, int userStackFrame) { GetCallSiteInformationInternal().SetStackTrace(stackTrace, userStackFrame, null); } /// <summary> /// Sets the details retrieved from the Caller Information Attributes /// </summary> /// <param name="callerClassName"></param> /// <param name="callerMemberName"></param> /// <param name="callerFilePath"></param> /// <param name="callerLineNumber"></param> public void SetCallerInfo(string callerClassName, string callerMemberName, string callerFilePath, int callerLineNumber) { GetCallSiteInformationInternal().SetCallerInfo(callerClassName, callerMemberName, callerFilePath, callerLineNumber); } internal void AddCachedLayoutValue(Layout layout, object value) { if (_layoutCache == null) { var dictionary = new Dictionary<Layout, object>(); dictionary[layout] = value; // Faster than collection initializer if (Interlocked.CompareExchange(ref _layoutCache, dictionary, null) == null) { return; // No need to use lock } } lock (_layoutCache) { _layoutCache[layout] = value; } } internal bool TryGetCachedLayoutValue(Layout layout, out object value) { if (_layoutCache == null) { // We don't need lock to see if dictionary has been created value = null; return false; } lock (_layoutCache) { if (_layoutCache.Count == 0) { value = null; return false; } return _layoutCache.TryGetValue(layout, out value); } } private static bool NeedToPreformatMessage(object[] parameters) { // we need to preformat message if it contains any parameters which could possibly // do logging in their ToString() if (parameters == null || parameters.Length == 0) { return false; } if (parameters.Length > 5) { // too many parameters, too costly to check return true; } for (int i = 0; i < parameters.Length; ++i) { if (!IsSafeToDeferFormatting(parameters[i])) return true; } return false; } private static bool IsSafeToDeferFormatting(object value) { return Convert.GetTypeCode(value) != TypeCode.Object; } internal bool IsLogEventMutableSafe() { if (Exception != null || _formattedMessage != null) return false; var properties = CreateOrUpdatePropertiesInternal(false); if (properties == null || properties.Count == 0) return true; // No mutable state, no need to precalculate if (properties.Count > 5) return false; // too many properties, too costly to check if (properties.Count == _parameters?.Length && properties.Count == properties.MessageProperties.Count) return true; // Already checked formatted message, no need to do it twice return HasImmutableProperties(properties); } private static bool HasImmutableProperties(PropertiesDictionary properties) { if (properties.Count == properties.MessageProperties.Count) { // Skip enumerator allocation when all properties comes from the message-template for (int i = 0; i < properties.MessageProperties.Count; ++i) { var property = properties.MessageProperties[i]; if (!IsSafeToDeferFormatting(property.Value)) return false; } } else { // Already spent the time on allocating a Dictionary, also have time for an enumerator foreach (var property in properties) { if (!IsSafeToDeferFormatting(property.Value)) return false; } } return true; } internal bool CanLogEventDeferMessageFormat() { if (_formattedMessage != null) return false; // Already formatted, cannot be deferred if (_parameters == null || _parameters.Length == 0) return false; // No parameters to format if (_message?.Length < 256 && ReferenceEquals(MessageFormatter, LogMessageTemplateFormatter.DefaultAuto.MessageFormatter)) return true; // Not too expensive to scan for properties else return false; } private static string GetStringFormatMessageFormatter(LogEventInfo logEvent) { if (logEvent.Parameters == null || logEvent.Parameters.Length == 0) { return logEvent.Message; } else { return string.Format(logEvent.FormatProvider ?? CultureInfo.CurrentCulture, logEvent.Message, logEvent.Parameters); } } private void CalcFormattedMessage() { try { _formattedMessage = _messageFormatter(this); } catch (Exception exception) { _formattedMessage = Message; InternalLogger.Warn(exception, "Error when formatting a message."); if (exception.MustBeRethrown()) { throw; } } } internal void AppendFormattedMessage(ILogMessageFormatter messageFormatter, System.Text.StringBuilder builder) { if (_formattedMessage != null) { builder.Append(_formattedMessage); } else { int originalLength = builder.Length; try { messageFormatter.AppendFormattedMessage(this, builder); } catch (Exception ex) { builder.Length = originalLength; builder.Append(_message ?? string.Empty); InternalLogger.Warn(ex, "Error when formatting a message."); if (ex.MustBeRethrown()) { throw; } } } } private void ResetFormattedMessage(bool rebuildMessageTemplateParameters) { _formattedMessage = null; if (rebuildMessageTemplateParameters && HasMessageTemplateParameters) { CalcFormattedMessage(); } } private bool ResetMessageTemplateParameters() { if (_properties != null) { if (HasMessageTemplateParameters) _properties.MessageProperties = null; return _properties.MessageProperties.Count == 0; } return false; } /// <summary> /// Set the <see cref="DefaultMessageFormatter"/> /// </summary> /// <param name="mode">true = Always, false = Never, null = Auto Detect</param> internal static void SetDefaultMessageFormatter(bool? mode) { if (mode == true) { InternalLogger.Info("Message Template Format always enabled"); DefaultMessageFormatter = LogMessageTemplateFormatter.Default.MessageFormatter; } else if (mode == false) { InternalLogger.Info("Message Template String Format always enabled"); DefaultMessageFormatter = StringFormatMessageFormatter; } else { //null = auto InternalLogger.Info("Message Template Auto Format enabled"); DefaultMessageFormatter = LogMessageTemplateFormatter.DefaultAuto.MessageFormatter; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="GroupPlacementViewServiceClient"/> instances.</summary> public sealed partial class GroupPlacementViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="GroupPlacementViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="GroupPlacementViewServiceSettings"/>.</returns> public static GroupPlacementViewServiceSettings GetDefault() => new GroupPlacementViewServiceSettings(); /// <summary> /// Constructs a new <see cref="GroupPlacementViewServiceSettings"/> object with default settings. /// </summary> public GroupPlacementViewServiceSettings() { } private GroupPlacementViewServiceSettings(GroupPlacementViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetGroupPlacementViewSettings = existing.GetGroupPlacementViewSettings; OnCopy(existing); } partial void OnCopy(GroupPlacementViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>GroupPlacementViewServiceClient.GetGroupPlacementView</c> and /// <c>GroupPlacementViewServiceClient.GetGroupPlacementViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetGroupPlacementViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="GroupPlacementViewServiceSettings"/> object.</returns> public GroupPlacementViewServiceSettings Clone() => new GroupPlacementViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="GroupPlacementViewServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class GroupPlacementViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<GroupPlacementViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public GroupPlacementViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public GroupPlacementViewServiceClientBuilder() { UseJwtAccessWithScopes = GroupPlacementViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref GroupPlacementViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<GroupPlacementViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override GroupPlacementViewServiceClient Build() { GroupPlacementViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<GroupPlacementViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<GroupPlacementViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private GroupPlacementViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return GroupPlacementViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<GroupPlacementViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return GroupPlacementViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => GroupPlacementViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => GroupPlacementViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => GroupPlacementViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>GroupPlacementViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch Group Placement views. /// </remarks> public abstract partial class GroupPlacementViewServiceClient { /// <summary> /// The default endpoint for the GroupPlacementViewService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default GroupPlacementViewService scopes.</summary> /// <remarks> /// The default GroupPlacementViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="GroupPlacementViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="GroupPlacementViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="GroupPlacementViewServiceClient"/>.</returns> public static stt::Task<GroupPlacementViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new GroupPlacementViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="GroupPlacementViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="GroupPlacementViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="GroupPlacementViewServiceClient"/>.</returns> public static GroupPlacementViewServiceClient Create() => new GroupPlacementViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="GroupPlacementViewServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="GroupPlacementViewServiceSettings"/>.</param> /// <returns>The created <see cref="GroupPlacementViewServiceClient"/>.</returns> internal static GroupPlacementViewServiceClient Create(grpccore::CallInvoker callInvoker, GroupPlacementViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } GroupPlacementViewService.GroupPlacementViewServiceClient grpcClient = new GroupPlacementViewService.GroupPlacementViewServiceClient(callInvoker); return new GroupPlacementViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC GroupPlacementViewService client</summary> public virtual GroupPlacementViewService.GroupPlacementViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Group Placement view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::GroupPlacementView GetGroupPlacementView(GetGroupPlacementViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Group Placement view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GroupPlacementView> GetGroupPlacementViewAsync(GetGroupPlacementViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested Group Placement view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GroupPlacementView> GetGroupPlacementViewAsync(GetGroupPlacementViewRequest request, st::CancellationToken cancellationToken) => GetGroupPlacementViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested Group Placement view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Group Placement view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::GroupPlacementView GetGroupPlacementView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetGroupPlacementView(new GetGroupPlacementViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Group Placement view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Group Placement view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GroupPlacementView> GetGroupPlacementViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetGroupPlacementViewAsync(new GetGroupPlacementViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Group Placement view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Group Placement view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GroupPlacementView> GetGroupPlacementViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetGroupPlacementViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested Group Placement view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Group Placement view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::GroupPlacementView GetGroupPlacementView(gagvr::GroupPlacementViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetGroupPlacementView(new GetGroupPlacementViewRequest { ResourceNameAsGroupPlacementViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Group Placement view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Group Placement view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GroupPlacementView> GetGroupPlacementViewAsync(gagvr::GroupPlacementViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetGroupPlacementViewAsync(new GetGroupPlacementViewRequest { ResourceNameAsGroupPlacementViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested Group Placement view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the Group Placement view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::GroupPlacementView> GetGroupPlacementViewAsync(gagvr::GroupPlacementViewName resourceName, st::CancellationToken cancellationToken) => GetGroupPlacementViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>GroupPlacementViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch Group Placement views. /// </remarks> public sealed partial class GroupPlacementViewServiceClientImpl : GroupPlacementViewServiceClient { private readonly gaxgrpc::ApiCall<GetGroupPlacementViewRequest, gagvr::GroupPlacementView> _callGetGroupPlacementView; /// <summary> /// Constructs a client wrapper for the GroupPlacementViewService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="GroupPlacementViewServiceSettings"/> used within this client. /// </param> public GroupPlacementViewServiceClientImpl(GroupPlacementViewService.GroupPlacementViewServiceClient grpcClient, GroupPlacementViewServiceSettings settings) { GrpcClient = grpcClient; GroupPlacementViewServiceSettings effectiveSettings = settings ?? GroupPlacementViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetGroupPlacementView = clientHelper.BuildApiCall<GetGroupPlacementViewRequest, gagvr::GroupPlacementView>(grpcClient.GetGroupPlacementViewAsync, grpcClient.GetGroupPlacementView, effectiveSettings.GetGroupPlacementViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetGroupPlacementView); Modify_GetGroupPlacementViewApiCall(ref _callGetGroupPlacementView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetGroupPlacementViewApiCall(ref gaxgrpc::ApiCall<GetGroupPlacementViewRequest, gagvr::GroupPlacementView> call); partial void OnConstruction(GroupPlacementViewService.GroupPlacementViewServiceClient grpcClient, GroupPlacementViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC GroupPlacementViewService client</summary> public override GroupPlacementViewService.GroupPlacementViewServiceClient GrpcClient { get; } partial void Modify_GetGroupPlacementViewRequest(ref GetGroupPlacementViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested Group Placement view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::GroupPlacementView GetGroupPlacementView(GetGroupPlacementViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetGroupPlacementViewRequest(ref request, ref callSettings); return _callGetGroupPlacementView.Sync(request, callSettings); } /// <summary> /// Returns the requested Group Placement view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::GroupPlacementView> GetGroupPlacementViewAsync(GetGroupPlacementViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetGroupPlacementViewRequest(ref request, ref callSettings); return _callGetGroupPlacementView.Async(request, callSettings); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.ObjectModel; namespace System.Management.Automation { /// <summary> /// /// Class HelpInfo keeps track of help information to be returned by help system. /// /// HelpInfo includes information in following aspect, /// /// a. Name: the target name for help /// b. Category: what category the help belongs to /// This class will be derived to track help info for different help categories like, /// AliasHelpInfo /// CommandHelpInfo /// ProviderHelpInfo /// /// etc. /// /// In general, there will be a specific helpInfo child class for each kind of help provider. /// /// </summary> internal abstract class HelpInfo { /// <summary> /// Constructor for HelpInfo /// </summary> internal HelpInfo() { } /// <summary> /// Name for help info /// </summary> /// <value>Name for help info</value> internal abstract string Name { get; } /// <summary> /// Synopsis for help info /// </summary> /// <value>Synopsis for help info</value> internal abstract string Synopsis { get; } /// <summary> /// Component for help info. /// </summary> /// <value>Component for help info</value> internal virtual string Component { get { return string.Empty; } } /// <summary> /// Role for help info. /// </summary> /// <value>Role for help ino</value> internal virtual string Role { get { return string.Empty; } } /// <summary> /// Functionality for help info. /// </summary> /// <value>Functionality for help info</value> internal virtual string Functionality { get { return string.Empty; } } /// <summary> /// Help category for help info /// </summary> /// <value>Help category for help info</value> internal abstract HelpCategory HelpCategory { get; } /// <summary> /// Forward help category for this help info /// </summary> /// <remarks> /// If this is not HelpCategory.None, then some other help provider /// (as specified in the HelpCategory bit pattern) need /// to process this helpInfo before it can be returned to end user. /// </remarks> /// <value>Help category to forward this helpInfo to</value> internal HelpCategory ForwardHelpCategory { get; set; } = HelpCategory.None; /// <summary> /// Target object in forward-help-provider that should process this HelpInfo. /// This will serve as auxilliary information to be passed to forward help provider. /// /// In the case of AliasHelpInfo, for example, it needs to be forwarded to /// CommandHelpProvider to fill in detailed helpInfo. In that case, ForwardHelpCategory /// will be HelpCategory.Command and the help target is the cmdlet name that matches this /// alias. /// </summary> /// <value>forward target object name</value> internal string ForwardTarget { get; set; } = ""; /// <summary> /// Full help object for this help item. /// </summary> /// <value>Full help object for this help item</value> internal abstract PSObject FullHelp { get; } /// <summary> /// Short help object for this help item. /// </summary> /// <value>Short help object for this help item</value> internal PSObject ShortHelp { get { if (this.FullHelp == null) return null; PSObject shortHelpObject = new PSObject(this.FullHelp); shortHelpObject.TypeNames.Clear(); shortHelpObject.TypeNames.Add("HelpInfoShort"); return shortHelpObject; } } /// <summary> /// Returs help information for a parameter(s) identified by pattern /// </summary> /// <param name="pattern">pattern to search for parameters</param> /// <returns>A collection of parameters that match pattern</returns> /// <remarks> /// The base method returns an empty list. /// </remarks> internal virtual PSObject[] GetParameter(string pattern) { return new PSObject[0]; } /// <summary> /// Returns the Uri used by get-help cmdlet to show help /// online. /// </summary> /// <returns> /// Null if no Uri is specified by the helpinfo or a /// valid Uri. /// </returns> /// <exception cref="InvalidOperationException"> /// Specified Uri is not valid. /// </exception> internal virtual Uri GetUriForOnlineHelp() { return null; } /// <summary> /// Returns true if help content in help info matches the /// pattern contained in <paramref name="pattern"/>. /// The underlying code will usually run pattern.IsMatch() on /// content it wants to search. /// </summary> /// <param name="pattern"></param> /// <returns></returns> internal virtual bool MatchPatternInContent(WildcardPattern pattern) { // this is base class implementation..derived classes can choose // what is best to them. return false; } /// <summary> /// Add common help properties to the helpObject which is in PSObject format. /// /// Intrinsic help properties include properties like, /// Name, /// Synopsis /// HelpCategory /// etc. /// /// Since help object from different help category has different format, it is /// needed that we generate these basic information uniformly in the help object /// itself. /// /// This function is normally called at the end of each child class constructor. /// </summary> /// <returns></returns> protected void AddCommonHelpProperties() { if (this.FullHelp == null) return; if (this.FullHelp.Properties["Name"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Name", this.Name.ToString())); } if (this.FullHelp.Properties["Category"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Category", this.HelpCategory.ToString())); } if (this.FullHelp.Properties["Synopsis"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Synopsis", this.Synopsis.ToString())); } if (this.FullHelp.Properties["Component"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Component", this.Component)); } if (this.FullHelp.Properties["Role"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Role", this.Role)); } if (this.FullHelp.Properties["Functionality"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Functionality", this.Functionality)); } } /// <summary> /// Update common help user-defined properties of the help object which is in PSObject format. /// Call this function to update Mshobject after it is created. /// </summary> /// <remarks> /// This function wont create new properties.This will update only user-defined properties created in /// <paramref name="AddCommonHelpProperties"/> /// </remarks> protected void UpdateUserDefinedDataProperties() { if (this.FullHelp == null) return; this.FullHelp.Properties.Remove("Component"); this.FullHelp.Properties.Add(new PSNoteProperty("Component", this.Component)); this.FullHelp.Properties.Remove("Role"); this.FullHelp.Properties.Add(new PSNoteProperty("Role", this.Role)); this.FullHelp.Properties.Remove("Functionality"); this.FullHelp.Properties.Add(new PSNoteProperty("Functionality", this.Functionality)); } #region Error handling /// <summary> /// This is for tracking the set of errors happened during the parsing of /// of this helpinfo. /// </summary> /// <value></value> internal Collection<ErrorRecord> Errors { get; set; } #endregion } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class ClusterSessionDecoder { public const ushort BLOCK_LENGTH = 40; public const ushort TEMPLATE_ID = 103; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private ClusterSessionDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public ClusterSessionDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ClusterSessionDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ClusterSessionIdId() { return 1; } public static int ClusterSessionIdSinceVersion() { return 0; } public static int ClusterSessionIdEncodingOffset() { return 0; } public static int ClusterSessionIdEncodingLength() { return 8; } public static string ClusterSessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long ClusterSessionIdNullValue() { return -9223372036854775808L; } public static long ClusterSessionIdMinValue() { return -9223372036854775807L; } public static long ClusterSessionIdMaxValue() { return 9223372036854775807L; } public long ClusterSessionId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int CorrelationIdId() { return 2; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int OpenedLogPositionId() { return 3; } public static int OpenedLogPositionSinceVersion() { return 0; } public static int OpenedLogPositionEncodingOffset() { return 16; } public static int OpenedLogPositionEncodingLength() { return 8; } public static string OpenedLogPositionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long OpenedLogPositionNullValue() { return -9223372036854775808L; } public static long OpenedLogPositionMinValue() { return -9223372036854775807L; } public static long OpenedLogPositionMaxValue() { return 9223372036854775807L; } public long OpenedLogPosition() { return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian); } public static int TimeOfLastActivityId() { return 4; } public static int TimeOfLastActivitySinceVersion() { return 0; } public static int TimeOfLastActivityEncodingOffset() { return 24; } public static int TimeOfLastActivityEncodingLength() { return 8; } public static string TimeOfLastActivityMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long TimeOfLastActivityNullValue() { return -9223372036854775808L; } public static long TimeOfLastActivityMinValue() { return -9223372036854775807L; } public static long TimeOfLastActivityMaxValue() { return 9223372036854775807L; } public long TimeOfLastActivity() { return _buffer.GetLong(_offset + 24, ByteOrder.LittleEndian); } public static int CloseReasonId() { return 5; } public static int CloseReasonSinceVersion() { return 0; } public static int CloseReasonEncodingOffset() { return 32; } public static int CloseReasonEncodingLength() { return 4; } public static string CloseReasonMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public CloseReason CloseReason() { return (CloseReason)_buffer.GetInt(_offset + 32, ByteOrder.LittleEndian); } public static int ResponseStreamIdId() { return 6; } public static int ResponseStreamIdSinceVersion() { return 0; } public static int ResponseStreamIdEncodingOffset() { return 36; } public static int ResponseStreamIdEncodingLength() { return 4; } public static string ResponseStreamIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ResponseStreamIdNullValue() { return -2147483648; } public static int ResponseStreamIdMinValue() { return -2147483647; } public static int ResponseStreamIdMaxValue() { return 2147483647; } public int ResponseStreamId() { return _buffer.GetInt(_offset + 36, ByteOrder.LittleEndian); } public static int ResponseChannelId() { return 7; } public static int ResponseChannelSinceVersion() { return 0; } public static string ResponseChannelCharacterEncoding() { return "US-ASCII"; } public static string ResponseChannelMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ResponseChannelHeaderLength() { return 4; } public int ResponseChannelLength() { int limit = _parentMessage.Limit(); return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); } public int GetResponseChannel(IMutableDirectBuffer dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public int GetResponseChannel(byte[] dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public string ResponseChannel() { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); _parentMessage.Limit(limit + headerLength + dataLength); byte[] tmp = new byte[dataLength]; _buffer.GetBytes(limit + headerLength, tmp, 0, dataLength); return Encoding.ASCII.GetString(tmp); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[ClusterSession](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='clusterSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ClusterSessionId="); builder.Append(ClusterSessionId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='openedLogPosition', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("OpenedLogPosition="); builder.Append(OpenedLogPosition()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='timeOfLastActivity', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='time_t', referencedName='null', description='Epoch time since 1 Jan 1970 UTC.', id=-1, version=0, deprecated=0, encodedLength=8, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("TimeOfLastActivity="); builder.Append(TimeOfLastActivity()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='closeReason', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=32, componentTokenCount=7, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=BEGIN_ENUM, name='CloseReason', referencedName='null', description='Reason why a session was closed.', id=-1, version=0, deprecated=0, encodedLength=4, offset=32, componentTokenCount=5, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}} builder.Append("CloseReason="); builder.Append(CloseReason()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='responseStreamId', referencedName='null', description='null', id=6, version=0, deprecated=0, encodedLength=0, offset=36, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=36, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ResponseStreamId="); builder.Append(ResponseStreamId()); builder.Append('|'); //Token{signal=BEGIN_VAR_DATA, name='responseChannel', referencedName='null', description='null', id=7, version=0, deprecated=0, encodedLength=0, offset=40, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ResponseChannel="); builder.Append(ResponseChannel()); Limit(originalLimit); return builder; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// BindingResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Notify.V1.Service { public class BindingResource : Resource { public sealed class BindingTypeEnum : StringEnum { private BindingTypeEnum(string value) : base(value) {} public BindingTypeEnum() {} public static implicit operator BindingTypeEnum(string value) { return new BindingTypeEnum(value); } public static readonly BindingTypeEnum Apn = new BindingTypeEnum("apn"); public static readonly BindingTypeEnum Gcm = new BindingTypeEnum("gcm"); public static readonly BindingTypeEnum Sms = new BindingTypeEnum("sms"); public static readonly BindingTypeEnum Fcm = new BindingTypeEnum("fcm"); public static readonly BindingTypeEnum FacebookMessenger = new BindingTypeEnum("facebook-messenger"); public static readonly BindingTypeEnum Alexa = new BindingTypeEnum("alexa"); } private static Request BuildFetchRequest(FetchBindingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Notify, "/v1/Services/" + options.PathServiceSid + "/Bindings/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Binding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Binding </returns> public static BindingResource Fetch(FetchBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Binding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Binding </returns> public static async System.Threading.Tasks.Task<BindingResource> FetchAsync(FetchBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Binding </returns> public static BindingResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchBindingOptions(pathServiceSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Binding </returns> public static async System.Threading.Tasks.Task<BindingResource> FetchAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchBindingOptions(pathServiceSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteBindingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Notify, "/v1/Services/" + options.PathServiceSid + "/Bindings/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Binding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Binding </returns> public static bool Delete(DeleteBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Binding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Binding </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Binding </returns> public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteBindingOptions(pathServiceSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Binding </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteBindingOptions(pathServiceSid, pathSid); return await DeleteAsync(options, client); } #endif private static Request BuildCreateRequest(CreateBindingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Notify, "/v1/Services/" + options.PathServiceSid + "/Bindings", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Binding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Binding </returns> public static BindingResource Create(CreateBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create Binding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Binding </returns> public static async System.Threading.Tasks.Task<BindingResource> CreateAsync(CreateBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the resource under </param> /// <param name="identity"> The `identity` value that identifies the new resource's User </param> /// <param name="bindingType"> The type of the Binding </param> /// <param name="address"> The channel-specific address </param> /// <param name="tag"> A tag that can be used to select the Bindings to notify </param> /// <param name="notificationProtocolVersion"> The protocol version to use to send the notification </param> /// <param name="credentialSid"> The SID of the Credential resource to be used to send notifications to this Binding /// </param> /// <param name="endpoint"> Deprecated </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Binding </returns> public static BindingResource Create(string pathServiceSid, string identity, BindingResource.BindingTypeEnum bindingType, string address, List<string> tag = null, string notificationProtocolVersion = null, string credentialSid = null, string endpoint = null, ITwilioRestClient client = null) { var options = new CreateBindingOptions(pathServiceSid, identity, bindingType, address){Tag = tag, NotificationProtocolVersion = notificationProtocolVersion, CredentialSid = credentialSid, Endpoint = endpoint}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the resource under </param> /// <param name="identity"> The `identity` value that identifies the new resource's User </param> /// <param name="bindingType"> The type of the Binding </param> /// <param name="address"> The channel-specific address </param> /// <param name="tag"> A tag that can be used to select the Bindings to notify </param> /// <param name="notificationProtocolVersion"> The protocol version to use to send the notification </param> /// <param name="credentialSid"> The SID of the Credential resource to be used to send notifications to this Binding /// </param> /// <param name="endpoint"> Deprecated </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Binding </returns> public static async System.Threading.Tasks.Task<BindingResource> CreateAsync(string pathServiceSid, string identity, BindingResource.BindingTypeEnum bindingType, string address, List<string> tag = null, string notificationProtocolVersion = null, string credentialSid = null, string endpoint = null, ITwilioRestClient client = null) { var options = new CreateBindingOptions(pathServiceSid, identity, bindingType, address){Tag = tag, NotificationProtocolVersion = notificationProtocolVersion, CredentialSid = credentialSid, Endpoint = endpoint}; return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadBindingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Notify, "/v1/Services/" + options.PathServiceSid + "/Bindings", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Binding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Binding </returns> public static ResourceSet<BindingResource> Read(ReadBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<BindingResource>.FromJson("bindings", response.Content); return new ResourceSet<BindingResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Binding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Binding </returns> public static async System.Threading.Tasks.Task<ResourceSet<BindingResource>> ReadAsync(ReadBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<BindingResource>.FromJson("bindings", response.Content); return new ResourceSet<BindingResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resource from </param> /// <param name="startDate"> Only include usage that has occurred on or after this date </param> /// <param name="endDate"> Only include usage that occurred on or before this date </param> /// <param name="identity"> The `identity` value of the resources to read </param> /// <param name="tag"> Only list Bindings that have all of the specified Tags </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Binding </returns> public static ResourceSet<BindingResource> Read(string pathServiceSid, DateTime? startDate = null, DateTime? endDate = null, List<string> identity = null, List<string> tag = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadBindingOptions(pathServiceSid){StartDate = startDate, EndDate = endDate, Identity = identity, Tag = tag, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resource from </param> /// <param name="startDate"> Only include usage that has occurred on or after this date </param> /// <param name="endDate"> Only include usage that occurred on or before this date </param> /// <param name="identity"> The `identity` value of the resources to read </param> /// <param name="tag"> Only list Bindings that have all of the specified Tags </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Binding </returns> public static async System.Threading.Tasks.Task<ResourceSet<BindingResource>> ReadAsync(string pathServiceSid, DateTime? startDate = null, DateTime? endDate = null, List<string> identity = null, List<string> tag = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadBindingOptions(pathServiceSid){StartDate = startDate, EndDate = endDate, Identity = identity, Tag = tag, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<BindingResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<BindingResource>.FromJson("bindings", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<BindingResource> NextPage(Page<BindingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Notify) ); var response = client.Request(request); return Page<BindingResource>.FromJson("bindings", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<BindingResource> PreviousPage(Page<BindingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Notify) ); var response = client.Request(request); return Page<BindingResource>.FromJson("bindings", response.Content); } /// <summary> /// Converts a JSON string into a BindingResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> BindingResource object represented by the provided JSON </returns> public static BindingResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<BindingResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Service that the resource is associated with /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The SID of the Credential resource to be used to send notifications to this Binding /// </summary> [JsonProperty("credential_sid")] public string CredentialSid { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The protocol version to use to send the notification /// </summary> [JsonProperty("notification_protocol_version")] public string NotificationProtocolVersion { get; private set; } /// <summary> /// Deprecated /// </summary> [JsonProperty("endpoint")] public string Endpoint { get; private set; } /// <summary> /// The `identity` value that identifies the new resource's User /// </summary> [JsonProperty("identity")] public string Identity { get; private set; } /// <summary> /// The type of the Binding /// </summary> [JsonProperty("binding_type")] public string BindingType { get; private set; } /// <summary> /// The channel-specific address /// </summary> [JsonProperty("address")] public string Address { get; private set; } /// <summary> /// The list of tags associated with this Binding /// </summary> [JsonProperty("tags")] public List<string> Tags { get; private set; } /// <summary> /// The absolute URL of the Binding resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The URLs of related resources /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private BindingResource() { } } }
// --------------------------------------------------------------------------- // <copyright file="LegacyAvailabilityTimeZoneTime.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the LegacyAvailabilityTimeZoneTime class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Text; /// <summary> /// Represents a custom time zone time change. /// </summary> internal sealed class LegacyAvailabilityTimeZoneTime : ComplexProperty { private TimeSpan delta; private int year; private int month; private int dayOrder; private DayOfTheWeek dayOfTheWeek; private TimeSpan timeOfDay; /// <summary> /// Initializes a new instance of the <see cref="LegacyAvailabilityTimeZoneTime"/> class. /// </summary> internal LegacyAvailabilityTimeZoneTime() : base() { } /// <summary> /// Initializes a new instance of the <see cref="LegacyAvailabilityTimeZoneTime"/> class. /// </summary> /// <param name="transitionTime">The transition time used to initialize this instance.</param> /// <param name="delta">The offset used to initialize this instance.</param> internal LegacyAvailabilityTimeZoneTime(TimeZoneInfo.TransitionTime transitionTime, TimeSpan delta) : this() { this.delta = delta; if (transitionTime.IsFixedDateRule) { // TimeZoneInfo doesn't support an actual year. Fixed date transitions occur at the same // date every year the adjustment rule the transition belongs to applies. The best thing // we can do here is use the current year. this.year = DateTime.Today.Year; this.month = transitionTime.Month; this.dayOrder = transitionTime.Day; this.timeOfDay = transitionTime.TimeOfDay.TimeOfDay; } else { // For floating rules, the mapping is direct. this.year = 0; this.month = transitionTime.Month; this.dayOfTheWeek = EwsUtilities.SystemToEwsDayOfTheWeek(transitionTime.DayOfWeek); this.dayOrder = transitionTime.Week; this.timeOfDay = transitionTime.TimeOfDay.TimeOfDay; } } /// <summary> /// Converts this instance to TimeZoneInfo.TransitionTime. /// </summary> /// <returns>A TimeZoneInfo.TransitionTime</returns> internal TimeZoneInfo.TransitionTime ToTransitionTime() { if (this.year == 0) { return TimeZoneInfo.TransitionTime.CreateFloatingDateRule( new DateTime( DateTime.MinValue.Year, DateTime.MinValue.Month, DateTime.MinValue.Day, this.timeOfDay.Hours, this.timeOfDay.Minutes, this.timeOfDay.Seconds), this.month, this.dayOrder, EwsUtilities.EwsToSystemDayOfWeek(this.dayOfTheWeek)); } else { return TimeZoneInfo.TransitionTime.CreateFixedDateRule( new DateTime(this.timeOfDay.Ticks), this.month, this.dayOrder); } } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.Bias: this.delta = TimeSpan.FromMinutes(reader.ReadElementValue<int>()); return true; case XmlElementNames.Time: this.timeOfDay = TimeSpan.Parse(reader.ReadElementValue()); return true; case XmlElementNames.DayOrder: this.dayOrder = reader.ReadElementValue<int>(); return true; case XmlElementNames.DayOfWeek: this.dayOfTheWeek = reader.ReadElementValue<DayOfTheWeek>(); return true; case XmlElementNames.Month: this.month = reader.ReadElementValue<int>(); return true; case XmlElementNames.Year: this.year = reader.ReadElementValue<int>(); return true; default: return false; } } /// <summary> /// Loads from json. /// </summary> /// <param name="jsonProperty">The json property.</param> /// <param name="service"></param> internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service) { foreach (string key in jsonProperty.Keys) { switch (key) { case XmlElementNames.Bias: this.delta = TimeSpan.FromMinutes(jsonProperty.ReadAsInt(key)); break; case XmlElementNames.Time: this.timeOfDay = TimeSpan.Parse(jsonProperty.ReadAsString(key)); break; case XmlElementNames.DayOrder: this.dayOrder = jsonProperty.ReadAsInt(key); break; case XmlElementNames.DayOfWeek: this.dayOfTheWeek = jsonProperty.ReadEnumValue<DayOfTheWeek>(key); break; case XmlElementNames.Month: this.month = jsonProperty.ReadAsInt(key); break; case XmlElementNames.Year: this.year = jsonProperty.ReadAsInt(key); break; default: break; } } } /// <summary> /// Writes the elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Bias, (int)this.delta.TotalMinutes); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Time, EwsUtilities.TimeSpanToXSTime(this.timeOfDay)); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DayOrder, this.dayOrder); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Month, (int)this.month); // Only write DayOfWeek if this is a recurring time change if (this.Year == 0) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DayOfWeek, this.dayOfTheWeek); } // Only emit year if it's non zero, otherwise AS returns "Request is invalid" if (this.Year != 0) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Year, this.Year); } } /// <summary> /// Serializes the property to a Json value. /// </summary> /// <param name="service"></param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> internal override object InternalToJson(ExchangeService service) { JsonObject jsonProperty = new JsonObject(); jsonProperty.Add( XmlElementNames.Bias, (int)this.delta.TotalMinutes); jsonProperty.Add( XmlElementNames.Time, EwsUtilities.TimeSpanToXSTime(this.timeOfDay)); jsonProperty.Add( XmlElementNames.DayOrder, this.dayOrder); jsonProperty.Add( XmlElementNames.Month, (int)this.month); // Only write DayOfWeek if this is a recurring time change if (this.Year == 0) { jsonProperty.Add( XmlElementNames.DayOfWeek, this.dayOfTheWeek); } // Only emit year if it's non zero, otherwise AS returns "Request is invalid" if (this.Year != 0) { jsonProperty.Add( XmlElementNames.Year, this.Year); } return jsonProperty; } /// <summary> /// Gets if current time presents DST transition time /// </summary> internal bool HasTransitionTime { get { return this.month >= 1 && this.month <= 12; } } /// <summary> /// Gets or sets the delta. /// </summary> internal TimeSpan Delta { get { return this.delta; } set { this.delta = value; } } /// <summary> /// Gets or sets the time of day. /// </summary> internal TimeSpan TimeOfDay { get { return this.timeOfDay; } set { this.timeOfDay = value; } } /// <summary> /// Gets or sets a value that represents: /// - The day of the month when Year is non zero, /// - The index of the week in the month if Year is equal to zero. /// </summary> internal int DayOrder { get { return this.dayOrder; } set { this.dayOrder = value; } } /// <summary> /// Gets or sets the month. /// </summary> internal int Month { get { return this.month; } set { this.month = value; } } /// <summary> /// Gets or sets the day of the week. /// </summary> internal DayOfTheWeek DayOfTheWeek { get { return this.dayOfTheWeek; } set { this.dayOfTheWeek = value; } } /// <summary> /// Gets or sets the year. If Year is 0, the time change occurs every year according to a recurring pattern; /// otherwise, the time change occurs at the date specified by Day, Month, Year. /// </summary> internal int Year { get { return this.year; } set { this.year = value; } } } }
//--------------------------------------------------------------------------- // // <copyright file="GeometryCollection.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media { /// <summary> /// A collection of Geometry objects. /// </summary> public sealed partial class GeometryCollection : Animatable, IList, IList<Geometry> { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new GeometryCollection Clone() { return (GeometryCollection)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new GeometryCollection CloneCurrentValue() { return (GeometryCollection)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region IList<T> /// <summary> /// Adds "value" to the list /// </summary> public void Add(Geometry value) { AddHelper(value); } /// <summary> /// Removes all elements from the list /// </summary> public void Clear() { WritePreamble(); // As part of Clear()'ing the collection, we will iterate it and call // OnFreezablePropertyChanged and OnRemove for each item. // However, OnRemove assumes that the item to be removed has already been // pulled from the underlying collection. To statisfy this condition, // we store the old collection and clear _collection before we call these methods. // As Clear() semantics do not include TrimToFit behavior, we create the new // collection storage at the same size as the previous. This is to provide // as close as possible the same perf characteristics as less complicated collections. FrugalStructList<Geometry> oldCollection = _collection; _collection = new FrugalStructList<Geometry>(_collection.Capacity); for (int i = oldCollection.Count - 1; i >= 0; i--) { OnFreezablePropertyChanged(/* oldValue = */ oldCollection[i], /* newValue = */ null); // Fire the OnRemove handlers for each item. We're not ensuring that // all OnRemove's get called if a resumable exception is thrown. // At this time, these call-outs are not public, so we do not handle exceptions. OnRemove( /* oldValue */ oldCollection[i]); } ++_version; WritePostscript(); } /// <summary> /// Determines if the list contains "value" /// </summary> public bool Contains(Geometry value) { ReadPreamble(); return _collection.Contains(value); } /// <summary> /// Returns the index of "value" in the list /// </summary> public int IndexOf(Geometry value) { ReadPreamble(); return _collection.IndexOf(value); } /// <summary> /// Inserts "value" into the list at the specified position /// </summary> public void Insert(int index, Geometry value) { if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); OnFreezablePropertyChanged(/* oldValue = */ null, /* newValue = */ value); _collection.Insert(index, value); OnInsert(value); ++_version; WritePostscript(); } /// <summary> /// Removes "value" from the list /// </summary> public bool Remove(Geometry value) { WritePreamble(); // By design collections "succeed silently" if you attempt to remove an item // not in the collection. Therefore we need to first verify the old value exists // before calling OnFreezablePropertyChanged. Since we already need to locate // the item in the collection we keep the index and use RemoveAt(...) to do // the work. (Windows OS #1016178) // We use the public IndexOf to guard our UIContext since OnFreezablePropertyChanged // is only called conditionally. IList.IndexOf returns -1 if the value is not found. int index = IndexOf(value); if (index >= 0) { Geometry oldValue = _collection[index]; OnFreezablePropertyChanged(oldValue, null); _collection.RemoveAt(index); OnRemove(oldValue); ++_version; WritePostscript(); return true; } // Collection_Remove returns true, calls WritePostscript, // increments version, and does UpdateResource if it succeeds return false; } /// <summary> /// Removes the element at the specified index /// </summary> public void RemoveAt(int index) { RemoveAtWithoutFiringPublicEvents(index); // RemoveAtWithoutFiringPublicEvents incremented the version WritePostscript(); } /// <summary> /// Removes the element at the specified index without firing /// the public Changed event. /// The caller - typically a public method - is responsible for calling /// WritePostscript if appropriate. /// </summary> internal void RemoveAtWithoutFiringPublicEvents(int index) { WritePreamble(); Geometry oldValue = _collection[ index ]; OnFreezablePropertyChanged(oldValue, null); _collection.RemoveAt(index); OnRemove(oldValue); ++_version; // No WritePostScript to avoid firing the Changed event. } /// <summary> /// Indexer for the collection /// </summary> public Geometry this[int index] { get { ReadPreamble(); return _collection[index]; } set { if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); if (!Object.ReferenceEquals(_collection[ index ], value)) { Geometry oldValue = _collection[ index ]; OnFreezablePropertyChanged(oldValue, value); _collection[ index ] = value; OnSet(oldValue, value); } ++_version; WritePostscript(); } } #endregion #region ICollection<T> /// <summary> /// The number of elements contained in the collection. /// </summary> public int Count { get { ReadPreamble(); return _collection.Count; } } /// <summary> /// Copies the elements of the collection into "array" starting at "index" /// </summary> public void CopyTo(Geometry[] array, int index) { ReadPreamble(); if (array == null) { throw new ArgumentNullException("array"); } // This will not throw in the case that we are copying // from an empty collection. This is consistent with the // BCL Collection implementations. (Windows 1587365) if (index < 0 || (index + _collection.Count) > array.Length) { throw new ArgumentOutOfRangeException("index"); } _collection.CopyTo(array, index); } bool ICollection<Geometry>.IsReadOnly { get { ReadPreamble(); return IsFrozen; } } #endregion #region IEnumerable<T> /// <summary> /// Returns an enumerator for the collection /// </summary> public Enumerator GetEnumerator() { ReadPreamble(); return new Enumerator(this); } IEnumerator<Geometry> IEnumerable<Geometry>.GetEnumerator() { return this.GetEnumerator(); } #endregion #region IList bool IList.IsReadOnly { get { return ((ICollection<Geometry>)this).IsReadOnly; } } bool IList.IsFixedSize { get { ReadPreamble(); return IsFrozen; } } object IList.this[int index] { get { return this[index]; } set { // Forwards to typed implementation this[index] = Cast(value); } } int IList.Add(object value) { // Forward to typed helper return AddHelper(Cast(value)); } bool IList.Contains(object value) { return Contains(value as Geometry); } int IList.IndexOf(object value) { return IndexOf(value as Geometry); } void IList.Insert(int index, object value) { // Forward to IList<T> Insert Insert(index, Cast(value)); } void IList.Remove(object value) { Remove(value as Geometry); } #endregion #region ICollection void ICollection.CopyTo(Array array, int index) { ReadPreamble(); if (array == null) { throw new ArgumentNullException("array"); } // This will not throw in the case that we are copying // from an empty collection. This is consistent with the // BCL Collection implementations. (Windows 1587365) if (index < 0 || (index + _collection.Count) > array.Length) { throw new ArgumentOutOfRangeException("index"); } if (array.Rank != 1) { throw new ArgumentException(SR.Get(SRID.Collection_BadRank)); } // Elsewhere in the collection we throw an AE when the type is // bad so we do it here as well to be consistent try { int count = _collection.Count; for (int i = 0; i < count; i++) { array.SetValue(_collection[i], index + i); } } catch (InvalidCastException e) { throw new ArgumentException(SR.Get(SRID.Collection_BadDestArray, this.GetType().Name), e); } } bool ICollection.IsSynchronized { get { ReadPreamble(); return IsFrozen || Dispatcher != null; } } object ICollection.SyncRoot { get { ReadPreamble(); return this; } } #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Internal Helpers /// <summary> /// A frozen empty GeometryCollection. /// </summary> internal static GeometryCollection Empty { get { if (s_empty == null) { GeometryCollection collection = new GeometryCollection(); collection.Freeze(); s_empty = collection; } return s_empty; } } /// <summary> /// Helper to return read only access. /// </summary> internal Geometry Internal_GetItem(int i) { return _collection[i]; } /// <summary> /// Freezable collections need to notify their contained Freezables /// about the change in the InheritanceContext /// </summary> internal override void OnInheritanceContextChangedCore(EventArgs args) { base.OnInheritanceContextChangedCore(args); for (int i=0; i<this.Count; i++) { DependencyObject inheritanceChild = _collection[i]; if (inheritanceChild!= null && inheritanceChild.InheritanceContext == this) { inheritanceChild.OnInheritanceContextChanged(args); } } } #endregion #region Private Helpers private Geometry Cast(object value) { if( value == null ) { throw new System.ArgumentNullException("value"); } if (!(value is Geometry)) { throw new System.ArgumentException(SR.Get(SRID.Collection_BadType, this.GetType().Name, value.GetType().Name, "Geometry")); } return (Geometry) value; } // IList.Add returns int and IList<T>.Add does not. This // is called by both Adds and IList<T>'s just ignores the // integer private int AddHelper(Geometry value) { int index = AddWithoutFiringPublicEvents(value); // AddAtWithoutFiringPublicEvents incremented the version WritePostscript(); return index; } internal int AddWithoutFiringPublicEvents(Geometry value) { int index = -1; if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); Geometry newValue = value; OnFreezablePropertyChanged(/* oldValue = */ null, newValue); index = _collection.Add(newValue); OnInsert(newValue); ++_version; // No WritePostScript to avoid firing the Changed event. return index; } internal event ItemInsertedHandler ItemInserted; internal event ItemRemovedHandler ItemRemoved; private void OnInsert(object item) { if (ItemInserted != null) { ItemInserted(this, item); } } private void OnRemove(object oldValue) { if (ItemRemoved != null) { ItemRemoved(this, oldValue); } } private void OnSet(object oldValue, object newValue) { OnInsert(newValue); OnRemove(oldValue); } #endregion Private Helpers private static GeometryCollection s_empty; #region Public Properties #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new GeometryCollection(); } /// <summary> /// Implementation of Freezable.CloneCore() /// </summary> protected override void CloneCore(Freezable source) { GeometryCollection sourceGeometryCollection = (GeometryCollection) source; base.CloneCore(source); int count = sourceGeometryCollection._collection.Count; _collection = new FrugalStructList<Geometry>(count); for (int i = 0; i < count; i++) { Geometry newValue = (Geometry) sourceGeometryCollection._collection[i].Clone(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of Freezable.CloneCurrentValueCore() /// </summary> protected override void CloneCurrentValueCore(Freezable source) { GeometryCollection sourceGeometryCollection = (GeometryCollection) source; base.CloneCurrentValueCore(source); int count = sourceGeometryCollection._collection.Count; _collection = new FrugalStructList<Geometry>(count); for (int i = 0; i < count; i++) { Geometry newValue = (Geometry) sourceGeometryCollection._collection[i].CloneCurrentValue(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of Freezable.GetAsFrozenCore() /// </summary> protected override void GetAsFrozenCore(Freezable source) { GeometryCollection sourceGeometryCollection = (GeometryCollection) source; base.GetAsFrozenCore(source); int count = sourceGeometryCollection._collection.Count; _collection = new FrugalStructList<Geometry>(count); for (int i = 0; i < count; i++) { Geometry newValue = (Geometry) sourceGeometryCollection._collection[i].GetAsFrozen(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of Freezable.GetCurrentValueAsFrozenCore() /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable source) { GeometryCollection sourceGeometryCollection = (GeometryCollection) source; base.GetCurrentValueAsFrozenCore(source); int count = sourceGeometryCollection._collection.Count; _collection = new FrugalStructList<Geometry>(count); for (int i = 0; i < count; i++) { Geometry newValue = (Geometry) sourceGeometryCollection._collection[i].GetCurrentValueAsFrozen(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>. /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); int count = _collection.Count; for (int i = 0; i < count && canFreeze; i++) { canFreeze &= Freezable.Freeze(_collection[i], isChecking); } return canFreeze; } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal FrugalStructList<Geometry> _collection; internal uint _version = 0; #endregion Internal Fields #region Enumerator /// <summary> /// Enumerates the items in a GeometryCollection /// </summary> public struct Enumerator : IEnumerator, IEnumerator<Geometry> { #region Constructor internal Enumerator(GeometryCollection list) { Debug.Assert(list != null, "list may not be null."); _list = list; _version = list._version; _index = -1; _current = default(Geometry); } #endregion #region Methods void IDisposable.Dispose() { } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element, /// false if the enumerator has passed the end of the collection. /// </returns> public bool MoveNext() { _list.ReadPreamble(); if (_version == _list._version) { if (_index > -2 && _index < _list._collection.Count - 1) { _current = _list._collection[++_index]; return true; } else { _index = -2; // -2 indicates "past the end" return false; } } else { throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged)); } } /// <summary> /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// </summary> public void Reset() { _list.ReadPreamble(); if (_version == _list._version) { _index = -1; } else { throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged)); } } #endregion #region Properties object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Current element /// /// The behavior of IEnumerable&lt;T>.Current is undefined /// before the first MoveNext and after we have walked /// off the end of the list. However, the IEnumerable.Current /// contract requires that we throw exceptions /// </summary> public Geometry Current { get { if (_index > -1) { return _current; } else if (_index == -1) { throw new InvalidOperationException(SR.Get(SRID.Enumerator_NotStarted)); } else { Debug.Assert(_index == -2, "expected -2, got " + _index + "\n"); throw new InvalidOperationException(SR.Get(SRID.Enumerator_ReachedEnd)); } } } #endregion #region Data private Geometry _current; private GeometryCollection _list; private uint _version; private int _index; #endregion } #endregion #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> /// Initializes a new instance that is empty. /// </summary> public GeometryCollection() { _collection = new FrugalStructList<Geometry>(); } /// <summary> /// Initializes a new instance that is empty and has the specified initial capacity. /// </summary> /// <param name="capacity"> int - The number of elements that the new list is initially capable of storing. </param> public GeometryCollection(int capacity) { _collection = new FrugalStructList<Geometry>(capacity); } /// <summary> /// Creates a GeometryCollection with all of the same elements as collection /// </summary> public GeometryCollection(IEnumerable<Geometry> collection) { // The WritePreamble and WritePostscript aren't technically necessary // in the constructor as of 1/20/05 but they are put here in case // their behavior changes at a later date WritePreamble(); if (collection != null) { bool needsItemValidation = true; ICollection<Geometry> icollectionOfT = collection as ICollection<Geometry>; if (icollectionOfT != null) { _collection = new FrugalStructList<Geometry>(icollectionOfT); } else { ICollection icollection = collection as ICollection; if (icollection != null) // an IC but not and IC<T> { _collection = new FrugalStructList<Geometry>(icollection); } else // not a IC or IC<T> so fall back to the slower Add { _collection = new FrugalStructList<Geometry>(); foreach (Geometry item in collection) { if (item == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } Geometry newValue = item; OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } needsItemValidation = false; } } if (needsItemValidation) { foreach (Geometry item in collection) { if (item == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } OnFreezablePropertyChanged(/* oldValue = */ null, item); OnInsert(item); } } WritePostscript(); } else { throw new ArgumentNullException("collection"); } } #endregion Constructors } }
// 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.Reflection.Emit.Tests { public class MethodBuilderSetSignature { [Fact] public void SetSignature_GenericMethod_SingleGenericParameter() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder returnType = typeParameters[0]; method.SetSignature(returnType.AsType(), null, null, null, null, null); VerifyMethodSignature(type, method, returnType.AsType()); } [Fact] public void SetSignature_GenericMethod_MultipleGenericParameters() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T", "U"); GenericTypeParameterBuilder desiredReturnType = typeParameters[1]; method.SetSignature(desiredReturnType.AsType(), null, null, null, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ReturnType_RequiredCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; method.SetSignature(desiredReturnType.AsType(), null, null, null, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ReturnType_RequiredModifier_OptionalCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; method.SetSignature(desiredReturnType.AsType(), null, null, null, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ReturnType_OptionalCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; method.SetSignature(desiredReturnType.AsType(), null, null, null, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ParameterTypes() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(int) }; method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_MultipleParameters() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T", "U"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(int), typeParameters[1].AsType() }; method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, null, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ParameterType_RequiredCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); string[] typeParamNames = new string[] { "T" }; GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters(typeParamNames); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(int) }; Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][]; for (int i = 0; i < desiredParamType.Length; ++i) { parameterTypeRequiredCustomModifiers[i] = null; } method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, parameterTypeRequiredCustomModifiers, null); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ParameterType_RequiredCustomModifer_OptionalCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(int) }; Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][]; Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][]; for (int i = 0; i < desiredParamType.Length; ++i) { parameterTypeRequiredCustomModifiers[i] = null; parameterTypeOptionalCustomModifiers[i] = null; } method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_GenericMethod_ParameterType_OptionalCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(int) }; Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][]; for (int i = 0; i < desiredParamType.Length; ++i) { parameterTypeOptionalCustomModifiers[i] = null; } method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, null, parameterTypeOptionalCustomModifiers); VerifyMethodSignature(type, method, desiredReturnType.AsType()); } [Fact] public void SetSignature_NonGenericMethod() { Type[] parameterTypes = new Type[] { typeof(string), typeof(object) }; TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), parameterTypes); string[] parameterNames = new string[parameterTypes.Length]; for (int i = 0; i < parameterNames.Length; ++i) { parameterNames[i] = "P" + i.ToString(); method.DefineParameter(i + 1, ParameterAttributes.In, parameterNames[i]); } Type desiredReturnType = typeof(void); Type[] desiredParamType = new Type[] { typeof(int) }; Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][]; Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][]; for (int i = 0; i < desiredParamType.Length; ++i) { parameterTypeRequiredCustomModifiers[i] = null; parameterTypeOptionalCustomModifiers[i] = null; } method.SetSignature(desiredReturnType, null, null, desiredParamType, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); } [Fact] public void SetSignature_AllParametersNull() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); method.SetSignature(null, null, null, null, null, null); VerifyMethodSignature(type, method, null); } [Fact] public void SetSignature_NullReturnType_CustomModifiersSetToWrongTypes() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; method.SetSignature(null, null, null, null, null, null); VerifyMethodSignature(type, method, null); } [Fact] public void SetSignature_NullOnReturnType_CustomModifiersSetCorrectly() { int arraySize = 10; TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = null; Type[][] parameterTypeRequiredCustomModifiers = new Type[arraySize][]; Type[][] parameterTypeOptionalCustomModifiers = new Type[arraySize][]; for (int i = 0; i < arraySize; ++i) { parameterTypeRequiredCustomModifiers[i] = null; parameterTypeOptionalCustomModifiers[i] = null; } method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); } [Fact] public void SetSignature_NullReturnType_RequiredCustomModifiers_OptionalCustomModifiers() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual); GenericTypeParameterBuilder[] typeParameters = method.DefineGenericParameters("T"); GenericTypeParameterBuilder desiredReturnType = typeParameters[0]; Type[] desiredParamType = new Type[] { typeof(void) }; Type[][] parameterTypeRequiredCustomModifiers = new Type[desiredParamType.Length][]; Type[][] parameterTypeOptionalCustomModifiers = new Type[desiredParamType.Length][]; for (int i = 0; i < desiredParamType.Length; ++i) { parameterTypeRequiredCustomModifiers[i] = null; parameterTypeOptionalCustomModifiers[i] = null; } method.SetSignature(desiredReturnType.AsType(), null, null, desiredParamType, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); } private void VerifyMethodSignature(TypeBuilder type, MethodBuilder method, Type desiredReturnType) { Type ret = type.CreateTypeInfo().AsType(); MethodInfo methodInfo = method.GetBaseDefinition(); Type actualReturnType = methodInfo.ReturnType; if (desiredReturnType == null) { Assert.Null(actualReturnType); } else { Assert.NotNull(actualReturnType); Assert.Equal(desiredReturnType.Name, actualReturnType.Name); Assert.True(actualReturnType.Equals(desiredReturnType)); } } } }
// // CTStringAttributes.cs: Implements the managed CTStringAttributes // // Authors: Mono Team // Marek Safar (marek.safar@gmail.com) // // Copyright 2010 Novell, Inc // Copyright 2012, Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; #if !MONOMAC using MonoMac.UIKit; #endif namespace MonoMac.CoreText { #region CFAttributedStringRef AttributeKey Prototypes [Since (3,2)] public enum CTUnderlineStyle { None = 0x00, Single = 0x01, Thick = 0x02, Double = 0x09, } [Since (3,2)] public enum CTUnderlineStyleModifiers { PatternSolid = 0x0000, PatternDot = 0x0100, PatternDash = 0x0200, PatternDashDot = 0x0300, PatternDashDotDot = 0x0400, } [Since (3,2)] public enum CTLigatureFormation { Essential = 0, Standard = 1, All = 2, } [Since (3,2)] public enum CTSuperscriptStyle { None = 0, Superscript = 1, Subscript = -1, } [Since (3,2)] public static class CTStringAttributeKey { public static readonly NSString Font; public static readonly NSString ForegroundColorFromContext; public static readonly NSString KerningAdjustment; public static readonly NSString LigatureFormation; public static readonly NSString ForegroundColor; public static readonly NSString ParagraphStyle; public static readonly NSString StrokeWidth; public static readonly NSString StrokeColor; public static readonly NSString UnderlineStyle; public static readonly NSString Superscript; public static readonly NSString UnderlineColor; public static readonly NSString VerticalForms; public static readonly NSString GlyphInfo; public static readonly NSString CharacterShape; public static readonly NSString RunDelegate; // Since 6,0 internal static readonly NSString BaselineClass; internal static readonly NSString BaselineInfo; internal static readonly NSString BaselineReferenceInfo; internal static readonly NSString WritingDirection; static CTStringAttributeKey () { var handle = Dlfcn.dlopen (Constants.CoreTextLibrary, 0); if (handle == IntPtr.Zero) return; try { Font = Dlfcn.GetStringConstant (handle, "kCTFontAttributeName"); ForegroundColorFromContext = Dlfcn.GetStringConstant (handle, "kCTForegroundColorFromContextAttributeName"); KerningAdjustment = Dlfcn.GetStringConstant (handle, "kCTKernAttributeName"); LigatureFormation = Dlfcn.GetStringConstant (handle, "kCTLigatureAttributeName"); ForegroundColor = Dlfcn.GetStringConstant (handle, "kCTForegroundColorAttributeName"); ParagraphStyle = Dlfcn.GetStringConstant (handle, "kCTParagraphStyleAttributeName"); StrokeWidth = Dlfcn.GetStringConstant (handle, "kCTStrokeWidthAttributeName"); StrokeColor = Dlfcn.GetStringConstant (handle, "kCTStrokeColorAttributeName"); UnderlineStyle = Dlfcn.GetStringConstant (handle, "kCTUnderlineStyleAttributeName"); Superscript = Dlfcn.GetStringConstant (handle, "kCTSuperscriptAttributeName"); UnderlineColor = Dlfcn.GetStringConstant (handle, "kCTUnderlineColorAttributeName"); VerticalForms = Dlfcn.GetStringConstant (handle, "kCTVerticalFormsAttributeName"); GlyphInfo = Dlfcn.GetStringConstant (handle, "kCTGlyphInfoAttributeName"); CharacterShape = Dlfcn.GetStringConstant (handle, "kCTCharacterShapeAttributeName"); RunDelegate = Dlfcn.GetStringConstant (handle, "kCTRunDelegateAttributeName"); #if !MONOMAC var version = new Version (UIDevice.CurrentDevice.SystemVersion); if (version.Major >= 6) { BaselineClass = Dlfcn.GetStringConstant (handle, "kCTBaselineClassAttributeName"); BaselineInfo = Dlfcn.GetStringConstant (handle, "kCTBaselineInfoAttributeName"); BaselineReferenceInfo = Dlfcn.GetStringConstant (handle, "kCTBaselineReferenceInfoAttributeName"); WritingDirection = Dlfcn.GetStringConstant (handle, "kCTWritingDirectionAttributeName"); } #endif } finally { Dlfcn.dlclose (handle); } } } #endregion [Since (3,2)] public class CTStringAttributes { public CTStringAttributes () : this (new NSMutableDictionary ()) { } public CTStringAttributes (NSDictionary dictionary) { if (dictionary == null) throw new ArgumentNullException ("dictionary"); Dictionary = dictionary; } public NSDictionary Dictionary {get; private set;} public CTFont Font { get { var h = CFDictionary.GetValue (Dictionary.Handle, CTStringAttributeKey.Font.Handle); return h == IntPtr.Zero ? null : new CTFont (h, false); } set {Adapter.SetNativeValue (Dictionary, CTStringAttributeKey.Font, value);} } public bool ForegroundColorFromContext { get { return CFDictionary.GetBooleanValue (Dictionary.Handle, CTStringAttributeKey.ForegroundColorFromContext.Handle); } set { Adapter.AssertWritable (Dictionary); CFMutableDictionary.SetValue (Dictionary.Handle, CTStringAttributeKey.ForegroundColorFromContext.Handle, value); } } public float? KerningAdjustment { get {return Adapter.GetSingleValue (Dictionary, CTStringAttributeKey.KerningAdjustment);} set {Adapter.SetValue (Dictionary, CTStringAttributeKey.KerningAdjustment, value);} } public CTLigatureFormation? LigatureFormation { get { var value = Adapter.GetInt32Value (Dictionary, CTStringAttributeKey.LigatureFormation); return !value.HasValue ? null : (CTLigatureFormation?) value.Value; } set { Adapter.SetValue (Dictionary, CTStringAttributeKey.LigatureFormation, value.HasValue ? (int?) value.Value : null); } } public CGColor ForegroundColor { get { var h = CFDictionary.GetValue (Dictionary.Handle, CTStringAttributeKey.ForegroundColor.Handle); return h == IntPtr.Zero ? null : new CGColor (h); } set {Adapter.SetNativeValue (Dictionary, CTStringAttributeKey.ForegroundColor, value);} } public CTParagraphStyle ParagraphStyle { get { var h = CFDictionary.GetValue (Dictionary.Handle, CTStringAttributeKey.ParagraphStyle.Handle); return h == IntPtr.Zero ? null : new CTParagraphStyle (h, false); } set {Adapter.SetNativeValue (Dictionary, CTStringAttributeKey.ParagraphStyle, value);} } public float? StrokeWidth { get {return Adapter.GetSingleValue (Dictionary, CTStringAttributeKey.StrokeWidth);} set {Adapter.SetValue (Dictionary, CTStringAttributeKey.StrokeWidth, value);} } public CGColor StrokeColor { get { var h = CFDictionary.GetValue (Dictionary.Handle, CTStringAttributeKey.StrokeColor.Handle); return h == IntPtr.Zero ? null : new CGColor (h); } set {Adapter.SetNativeValue (Dictionary, CTStringAttributeKey.StrokeColor, value);} } public int? UnderlineStyleValue { get {return Adapter.GetInt32Value (Dictionary, CTStringAttributeKey.UnderlineStyle);} set {Adapter.SetValue (Dictionary, CTStringAttributeKey.UnderlineStyle, value);} } const int UnderlineStyleMask = 0x000F; const int UnderlineStyleModifiersMask = 0x0700; public CTUnderlineStyle? UnderlineStyle { get { var v = UnderlineStyleValue; return !v.HasValue ? null : (CTUnderlineStyle?) (v.Value & UnderlineStyleMask); } set { var m = UnderlineStyleModifiers; UnderlineStyleValue = Adapter.BitwiseOr ( m.HasValue ? (int?) m.Value : null, value.HasValue ? (int?) value.Value : null); } } public CTUnderlineStyleModifiers? UnderlineStyleModifiers { get { var v = UnderlineStyleValue; return !v.HasValue ? null : (CTUnderlineStyleModifiers?) (v.Value & UnderlineStyleModifiersMask); } set { var m = UnderlineStyleModifiers; UnderlineStyleValue = Adapter.BitwiseOr ( m.HasValue ? (int?) m.Value : null, value.HasValue ? (int?) value.Value : null); } } public CTSuperscriptStyle? Superscript { get { var value = Adapter.GetInt32Value (Dictionary, CTStringAttributeKey.Superscript); return !value.HasValue ? null : (CTSuperscriptStyle?) value.Value; } set { Adapter.SetValue (Dictionary, CTStringAttributeKey.Superscript, value.HasValue ? (int?) value.Value : null); } } public CGColor UnderlineColor { get { var h = CFDictionary.GetValue (Dictionary.Handle, CTStringAttributeKey.UnderlineColor.Handle); return h == IntPtr.Zero ? null : new CGColor (h); } set {Adapter.SetNativeValue (Dictionary, CTStringAttributeKey.UnderlineColor, value);} } public bool VerticalForms { get { return CFDictionary.GetBooleanValue (Dictionary.Handle, CTStringAttributeKey.VerticalForms.Handle); } set { Adapter.AssertWritable (Dictionary); CFMutableDictionary.SetValue (Dictionary.Handle, CTStringAttributeKey.VerticalForms.Handle, value); } } public CTGlyphInfo GlyphInfo { get { var h = CFDictionary.GetValue (Dictionary.Handle, CTStringAttributeKey.GlyphInfo.Handle); return h == IntPtr.Zero ? null : new CTGlyphInfo (h, false); } set {Adapter.SetNativeValue (Dictionary, CTStringAttributeKey.GlyphInfo, value);} } public int? CharacterShape { get {return Adapter.GetInt32Value (Dictionary, CTStringAttributeKey.CharacterShape);} set {Adapter.SetValue (Dictionary, CTStringAttributeKey.CharacterShape, value);} } public CTRunDelegate RunDelegate { get { var h = CFDictionary.GetValue (Dictionary.Handle, CTStringAttributeKey.RunDelegate.Handle); return h == IntPtr.Zero ? null : new CTRunDelegate (h, false); } set {Adapter.SetNativeValue (Dictionary, CTStringAttributeKey.RunDelegate, value);} } [Since (6, 0)] public CTBaselineClass? BaselineClass { get { var value = CFDictionary.GetValue (Dictionary.Handle, CTStringAttributeKey.BaselineClass.Handle); return value == IntPtr.Zero ? (CTBaselineClass?) null : CTBaselineClassID.FromHandle (value); } set { var ns_value = value == null ? null : CTBaselineClassID.ToNSString (value.Value); Adapter.SetNativeValue (Dictionary, CTStringAttributeKey.BaselineClass, ns_value); } } [Since (6, 0)] public void SetBaselineInfo (CTBaselineClass baselineClass, double offset) { SetBaseline (baselineClass, offset, CTStringAttributeKey.BaselineInfo); } [Since (6, 0)] public void SetBaselineReferenceInfo (CTBaselineClass baselineClass, double offset) { SetBaseline (baselineClass, offset, CTStringAttributeKey.BaselineReferenceInfo); } void SetBaseline (CTBaselineClass baselineClass, double offset, NSString infoKey) { var ptr = CFDictionary.GetValue (Dictionary.Handle, infoKey.Handle); var dict = ptr == IntPtr.Zero ? new NSMutableDictionary () : new NSMutableDictionary (ptr); var key = CTBaselineClassID.ToNSString (baselineClass); Adapter.SetValue (dict, key, new NSNumber (offset)); if (ptr == IntPtr.Zero) Adapter.SetNativeValue (Dictionary, infoKey, (INativeObject)dict); } [Since (6, 0)] public void SetWritingDirection (params CTWritingDirection[] writingDirections) { var ptrs = new IntPtr [writingDirections.Length]; for (int i = 0; i < writingDirections.Length; ++i) { ptrs[i] = (new NSNumber ((int) writingDirections[i])).Handle; } var array = CFArray.Create (ptrs); CFMutableDictionary.SetValue (Dictionary.Handle, CTStringAttributeKey.WritingDirection.Handle, array); } } }
using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using CuttingEdge.Conditions; using log4net; using VDS.RDF; using ZimmerBot.Core.Knowledge; using ZimmerBot.Core.Patterns; using ZimmerBot.Core.Statements; using ZimmerBot.Core.Utilities; using ZimmerBot.Core.WordRegex; namespace ZimmerBot.Core.ConfigParser { internal partial class ConfigParser { private static ILog Logger = LogManager.GetLogger(typeof(ConfigParser)); protected KnowledgeBase KnowledgeBase { get; set; } protected string CurrentTopic { get; set; } public ConfigParser(KnowledgeBase kb) : base(null) { Condition.Requires(kb, nameof(kb)).IsNotNull(); KnowledgeBase = kb; } public void Parse(string s) { byte[] inputBuffer = System.Text.Encoding.Default.GetBytes(s); MemoryStream stream = new MemoryStream(inputBuffer); Parse(stream, "string input"); } public void Parse(Stream s, string filename) { Scanner = new ConfigScanner(s); Parse(); if (((ConfigScanner)Scanner).Errors != null && ((ConfigScanner)Scanner).Errors.Count > 0) throw new ParserException(filename, ((ConfigScanner)Scanner).Errors); } protected void RegisterConcept(string name, List<List<string>> patterns) { Concept c = KnowledgeBase.AddConcept(name, patterns); } protected void BeginTopic(string name) { CurrentTopic = name; KnowledgeBase.AddTopic(name); } protected string CurrentTopicToStart = null; protected void BeginTopicStarters(string topic) { CurrentTopicToStart = topic; } protected void EndTopicStarters() { CurrentTopicToStart = null; } protected void FinalizeTopic(string name) { Condition.Requires(name, nameof(name)).IsEqualTo(CurrentTopic); CurrentTopic = null; } protected void RegisterEntities(string className, List<WRegexBase> entityPatterns) { KnowledgeBase.RegisterEntityClass(className, entityPatterns); } protected void RegisterIgnorable(List<WRegexBase> entityPatterns) { KnowledgeBase.RegisterEntityClass(Constants.IgnoreValue, entityPatterns); } protected void RegisterPatternSet(List<KeyValuePair<string, List<string>>> identifiers, List<Pattern> patterns) { KnowledgeBase.RegisterPatternSet(identifiers, patterns); } protected void RegisterDefinitions(List<string> mainClasses, List<WordDefinition> definition) { KnowledgeBase.RegisterDefinitions(mainClasses, definition); } protected void RegisterScheduledAction(string cronExpr, List<RuleModifier> modifiers, List<Statement> statements) { KnowledgeBase.RegisterScheduledAction(cronExpr, modifiers, statements); } protected void RegisterPipelineItem(string stage, List<RuleModifier> modifiers, List<Statement> statements) { KnowledgeBase.RegisterPipelineItem(stage, modifiers, statements); } protected bool DoStripRegexLiterals = false; static Regex LabelReducer = new Regex("[^\\w ]"); protected WRegexBase BuildLiteralWRegex(string literal) { if (DoStripRegexLiterals) { literal = LabelReducer.Replace(literal, ""); return new LiteralWRegex(literal); } else return new LiteralWRegex(literal); } protected WRegexBase BuildConceptWRegex(string s) { if (s == "%ENTITY") { return new GroupWRegex( new ChoiceWRegex( new WildcardWRegex(), new EntityWRegex())); } else return new ConceptWRegex(KnowledgeBase, s); } protected void RegisterEventHandler(string e, List<Statement> statements) { KnowledgeBase.RegisterEventHandler(e, statements, null); } protected void RDFImport(string filename) { KnowledgeBase.MemoryStore.LoadFromFile(filename); } protected void RDFPrefix(string prefix, string url) { KnowledgeBase.MemoryStore.DeclarePrefix(prefix, url); } protected void RDFEntities(string sparql) { KnowledgeBase.RegisterSparqlForEntities(sparql); } protected RdfUriValue RdfResourceUriValue(List<string> names, string prefix) { return new RdfUriValue(names, KnowledgeBase.MemoryStore, prefix); } protected RdfZPropertyValue RdfProperty(string name) { return new RdfZPropertyValue(name); } protected StandardRule AddRegexRule(string label, List<WRegexBase> patterns, List<RuleModifier> modifiers, List<Statement> statements) { if (CurrentTopicToStart != null) statements.Add(new StartTopicStatement(CurrentTopicToStart, false)); return KnowledgeBase.AddRegexRule(label, CurrentTopic, patterns, modifiers, statements); } protected StandardRule AddFuzzyRule(string label, List<OperatorKeyValueList> pattern, List<RuleModifier> modifiers, List<Statement> statements) { if (CurrentTopicToStart != null) statements.Add(new StartTopicStatement(CurrentTopicToStart, false)); return KnowledgeBase.AddFuzzyRule(label, CurrentTopic, pattern, modifiers, statements); } protected TopicRule AddTopicRule(string label, OutputTemplate output, List<Statement> statements) { statements.Insert(0, new OutputTemplateStatement(output)); return KnowledgeBase.AddTopicRule(label, CurrentTopic, statements); } protected WRegexBase CombineSequence(WRegexBase left, WRegexBase right) { if (left == null && right != null) return right; if (left is SequenceWRegex && !(right is SequenceWRegex)) { ((SequenceWRegex)left).Add(right); return left; } else if (!(left is SequenceWRegex) && !(right is SequenceWRegex)) { SequenceWRegex seq = new SequenceWRegex(); seq.Add(left); seq.Add(right); return seq; } else if (!(left is SequenceWRegex) && right is SequenceWRegex) { ((SequenceWRegex)right).Insert(0, left); return right; } else // (left is SequenceWRegex && right is SequenceWRegex) { foreach (WRegexBase r in ((SequenceWRegex)right).Sequence) ((SequenceWRegex)left).Add(r); return left; } } } }
namespace PokerTell.LiveTracker.Tests.PokerRooms { using System.Collections.Generic; using Interfaces; using LiveTracker.PokerRooms; using Machine.Specifications; using Moq; using Tools.FunctionalCSharp; using Tools.Interfaces; using It = Machine.Specifications.It; // Resharper disable InconsistentNaming public abstract class PokerRoomSettingsDetectorSpecs { protected static Mock<IPokerRoomInfo> _roomInfo_Stub; protected static Mock<IPokerRoomDetective> _detective_Mock; protected const string _handHistoryDirectory = "someFolder"; protected const string _helpWithHandHistoryDirectorySetupLink = "someLink"; protected const string _site = "someSite"; protected static ITuple<string, string> _site_Directory_Pair; protected static ITuple<string, string> _site_HelpLink_Pair; protected static IPokerRoomSettingsDetector _sut; Establish specContext = () => { _detective_Mock = new Mock<IPokerRoomDetective>(); _detective_Mock .SetupGet(d => d.HandHistoryDirectory) .Returns(_handHistoryDirectory); _detective_Mock .Setup(d => d.Investigate()) .Returns(_detective_Mock.Object); _roomInfo_Stub = new Mock<IPokerRoomInfo>(); _roomInfo_Stub .SetupGet(ri => ri.Detective) .Returns(_detective_Mock.Object); _roomInfo_Stub .SetupGet(ri => ri.HelpWithHandHistoryDirectorySetupLink) .Returns(_helpWithHandHistoryDirectorySetupLink); _roomInfo_Stub .SetupGet(ri => ri.Site) .Returns(_site); _site_Directory_Pair = Tuple.New(_site, _handHistoryDirectory); _site_HelpLink_Pair = Tuple.New(_site, _helpWithHandHistoryDirectorySetupLink); _sut = new PokerRoomSettingsDetector().InitializeWith(new[] { _roomInfo_Stub.Object }); }; [Subject(typeof(PokerRoomSettingsDetector), "Detect HandHistoryFolders")] public class when_detecting_HandHistoryFolders_and_poker_room_detective_did_not_find_the_room_to_be_installed : PokerRoomSettingsDetectorSpecs { const bool isInstalled = false; Establish context = () => _detective_Mock .SetupGet(d => d.PokerRoomIsInstalled) .Returns(isInstalled); Because of = () => _sut.DetectHandHistoryFolders(); It should_tell_the_detective_to_investigate = () => _detective_Mock.Verify(d => d.Investigate()); It should_not_add_the_room_name_and_corresponding_handhistory_directory_to_the_PokerRoomsWithDetectedHandHistoryDirectories = () => _sut.PokerRoomsWithDetectedHandHistoryDirectories.ShouldNotContain(_site_Directory_Pair); It should_not_add_the_room_name_and_corresponding_help_link_to_the_PokerRoomsWithoutDetectedHandHistoryDirectories = () => _sut.PokerRoomsWithoutDetectedHandHistoryDirectories.ShouldNotContain(_site_HelpLink_Pair); } [Subject(typeof(PokerRoomSettingsDetector), "Detect HandHistoryFolders")] public class when_detecting_HandHistoryFolders_and_poker_room_detective_found_the_room_to_be_installed_and_detected_the_handHistory_folder : PokerRoomSettingsDetectorSpecs { const bool isInstalled = true; const bool detectedHandHistoryDirectory = true; Establish context = () => { _detective_Mock .SetupGet(d => d.PokerRoomIsInstalled) .Returns(isInstalled); _detective_Mock .SetupGet(d => d.DetectedHandHistoryDirectory) .Returns(detectedHandHistoryDirectory); }; Because of = () => _sut.DetectHandHistoryFolders(); It should_tell_the_detective_to_investigate = () => _detective_Mock.Verify(d => d.Investigate()); It should_add_the_room_name_and_corresponding_handhistory_directory_to_the_PokerRoomsWithDetectedHandHistoryDirectories = () => _sut.PokerRoomsWithDetectedHandHistoryDirectories.ShouldContain(_site_Directory_Pair); It should_not_add_the_room_name_and_corresponding_help_link_to_the_PokerRoomsWithoutDetectedHandHistoryDirectories = () => _sut.PokerRoomsWithoutDetectedHandHistoryDirectories.ShouldNotContain(_site_HelpLink_Pair); } [Subject(typeof(PokerRoomSettingsDetector), "Detect HandHistoryFolders")] public class when_detecting_HandHistoryFolders_and_poker_room_detective_found_the_room_to_be_installed_but_was_unable_to_detecte_the_handHistory_folder : PokerRoomSettingsDetectorSpecs { const bool isInstalled = true; const bool detectedHandHistoryDirectory = false; Establish context = () => { _detective_Mock .SetupGet(d => d.PokerRoomIsInstalled) .Returns(isInstalled); _detective_Mock .SetupGet(d => d.DetectedHandHistoryDirectory) .Returns(detectedHandHistoryDirectory); }; Because of = () => _sut.DetectHandHistoryFolders(); It should_tell_the_detective_to_investigate = () => _detective_Mock.Verify(d => d.Investigate()); It should_not_add_the_room_name_and_corresponding_handhistory_directory_to_the_PokerRoomsWithDetectedHandHistoryDirectories = () => _sut.PokerRoomsWithDetectedHandHistoryDirectories.ShouldNotContain(_site_Directory_Pair); It should_add_the_room_name_and_corresponding_help_link_to_the_PokerRoomsWithoutDetectedHandHistoryDirectories = () => _sut.PokerRoomsWithoutDetectedHandHistoryDirectories.ShouldContain(_site_HelpLink_Pair); } [Subject(typeof(PokerRoomSettingsDetector), "Detect PreferredSeats")] public class when_detecting_preferredSeats_and_poker_room_detective_says_the_PokerRoom_does_not_save_PreferredSeats : PokerRoomSettingsDetectorSpecs { const bool savesPreferredSeats = false; Establish context = () => _detective_Mock .SetupGet(d => d.PokerRoomSavesPreferredSeats) .Returns(savesPreferredSeats); Because of = () => _sut.DetectPreferredSeats(); It should_not_tell_the_detective_to_investigate = () => _detective_Mock.Verify(d => d.Investigate(), Times.Never()); } [Subject(typeof(PokerRoomSettingsDetector), "Detect PreferredSeats")] public class when_detecting_preferredSeats_and_poker_room_detective_did_not_find_the_room_to_be_installed : PokerRoomSettingsDetectorSpecs { const bool savesPreferredSeats = true; const bool isInstalled = false; Establish context = () => { _detective_Mock .SetupGet(d => d.PokerRoomSavesPreferredSeats) .Returns(savesPreferredSeats); _detective_Mock .SetupGet(d => d.PokerRoomIsInstalled) .Returns(isInstalled); }; Because of = () => _sut.DetectPreferredSeats(); It should_tell_the_detective_to_investigate = () => _detective_Mock.Verify(d => d.Investigate()); It should_not_add_the_room_name_and_corresponding_preferredSeats_the_PokerRoomsWithDetectedPreferredSeats = () => _sut.PokerRoomsWithDetectedPreferredSeats.ShouldBeEmpty(); } [Subject(typeof(PokerRoomSettingsDetector), "Detect PreferredSeats")] public class when_detecting_preferredSeats_and_poker_room_detective_did_find_the_room_to_be_installed_but_did_not_detect_the_preferredSeats : PokerRoomSettingsDetectorSpecs { const bool savesPreferredSeats = true; const bool isInstalled = true; const bool detectedPreferredSeats = false; Establish context = () => { _detective_Mock .SetupGet(d => d.PokerRoomSavesPreferredSeats) .Returns(savesPreferredSeats); _detective_Mock .SetupGet(d => d.PokerRoomIsInstalled) .Returns(isInstalled); _detective_Mock .SetupGet(d => d.DetectedPreferredSeats) .Returns(detectedPreferredSeats); }; Because of = () => _sut.DetectPreferredSeats(); It should_tell_the_detective_to_investigate = () => _detective_Mock.Verify(d => d.Investigate()); It should_not_add_the_room_name_and_corresponding_preferredSeats_the_PokerRoomsWithDetectedPreferredSeats = () => _sut.PokerRoomsWithDetectedPreferredSeats.ShouldBeEmpty(); } [Subject(typeof(PokerRoomSettingsDetector), "Detect PreferredSeats")] public class when_detecting_preferredSeats_and_poker_room_detective_found_the_room_to_be_installed_and_detected_the_preferredSeats : PokerRoomSettingsDetectorSpecs { const bool savesPreferredSeats = true; const bool isInstalled = true; const bool detectedPreferredSeats = true; static IDictionary<int, int> preferredSeats_Stub; static ITuple<string, IDictionary<int, int>> expectedPreferredSeatsForSite; Establish context = () => { preferredSeats_Stub = new Dictionary<int, int> { { 2, 1 } }; expectedPreferredSeatsForSite = Tuple.New(_site, preferredSeats_Stub); _detective_Mock .SetupGet(d => d.PokerRoomSavesPreferredSeats) .Returns(savesPreferredSeats); _detective_Mock .SetupGet(d => d.PokerRoomIsInstalled) .Returns(isInstalled); _detective_Mock .SetupGet(d => d.DetectedPreferredSeats) .Returns(detectedPreferredSeats); _detective_Mock .SetupGet(d => d.PreferredSeats) .Returns(preferredSeats_Stub); }; Because of = () => _sut.DetectPreferredSeats(); It should_tell_the_detective_to_investigate = () => _detective_Mock.Verify(d => d.Investigate()); It should_add_the_room_name_and_corresponding_preferredSeats_to_the_PokerRoomsWithDetectedPreferredSeats = () => _sut.PokerRoomsWithDetectedPreferredSeats.ShouldContain(expectedPreferredSeatsForSite); } } }
/* ==================================================================== 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 TestCases.HSSF.UserModel { using System; using System.IO; using NPOI.HSSF.UserModel; using NUnit.Framework; using TestCases.HSSF; using NPOI.SS.UserModel; /** * Tests row shifting capabilities. * * * @author Shawn Laubach (slaubach at apache dot com) * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) */ [TestFixture] public class TestSheetShiftRows { /** * Tests the ShiftRows function. Does three different shifts. * After each shift, Writes the workbook to file and reads back to * Check. This ensures that if some changes code that breaks * writing or what not, they realize it. * * @author Shawn Laubach (slaubach at apache dot org) */ [Test] public void TestShiftRows() { // Read initial file in HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("SimpleMultiCell.xls"); NPOI.SS.UserModel.ISheet s = wb.GetSheetAt(0); // Shift the second row down 1 and Write to temp file s.ShiftRows(1, 1, 1); wb = HSSFTestDataSamples.WriteOutAndReadBack(wb); // Read from temp file and Check the number of cells in each // row (in original file each row was unique) s = wb.GetSheetAt(0); Assert.AreEqual(1,s.GetRow(0).PhysicalNumberOfCells); ConfirmEmptyRow(s, 1); Assert.AreEqual(2, s.GetRow(2).PhysicalNumberOfCells); Assert.AreEqual(4,s.GetRow(3).PhysicalNumberOfCells); Assert.AreEqual(5,s.GetRow(4).PhysicalNumberOfCells); // Shift rows 1-3 down 3 in the current one. This Tests when // 1 row is blank. Write to a another temp file s.ShiftRows(0, 2, 3); wb = HSSFTestDataSamples.WriteOutAndReadBack(wb); // Read and ensure things are where they should be s = wb.GetSheetAt(0); ConfirmEmptyRow(s, 0); ConfirmEmptyRow(s, 1); ConfirmEmptyRow(s, 2); Assert.AreEqual(1,s.GetRow(3).PhysicalNumberOfCells); ConfirmEmptyRow(s, 4); Assert.AreEqual(2,s.GetRow(5).PhysicalNumberOfCells); // Read the first file again wb = HSSFTestDataSamples.OpenSampleWorkbook("SimpleMultiCell.xls"); s = wb.GetSheetAt(0); // Shift rows 3 and 4 up and Write to temp file s.ShiftRows(2, 3, -2); wb = HSSFTestDataSamples.WriteOutAndReadBack(wb); s = wb.GetSheetAt(0); Assert.AreEqual(s.GetRow(0).PhysicalNumberOfCells, 3); Assert.AreEqual(s.GetRow(1).PhysicalNumberOfCells, 4); ConfirmEmptyRow(s, 2); ConfirmEmptyRow(s, 3); Assert.AreEqual(s.GetRow(4).PhysicalNumberOfCells, 5); } private static void ConfirmEmptyRow(NPOI.SS.UserModel.ISheet s, int rowIx) { IRow row = s.GetRow(rowIx); Assert.IsTrue(row == null || row.PhysicalNumberOfCells == 0); } /** * Tests when rows are null. * * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) */ [Test] public void TestShiftRow() { HSSFWorkbook b = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet s = b.CreateSheet(); s.CreateRow(0).CreateCell(0).SetCellValue("TEST1"); s.CreateRow(3).CreateCell(0).SetCellValue("TEST2"); s.ShiftRows(0, 4, 1); } /** * Tests when shifting the first row. * * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) */ [Test] public void TestShiftRow0() { HSSFWorkbook b = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet s = b.CreateSheet(); s.CreateRow(0).CreateCell(0).SetCellValue("TEST1"); s.CreateRow(3).CreateCell(0).SetCellValue("TEST2"); s.ShiftRows(0, 4, 1); } /** * When shifting rows, the page breaks should go with it * */ [Test] public void TestShiftRowBreaks() { HSSFWorkbook b = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet s = b.CreateSheet(); IRow row = s.CreateRow(4); row.CreateCell(0).SetCellValue("Test"); s.SetRowBreak(4); s.ShiftRows(4, 4, 2); Assert.IsTrue(s.IsRowBroken(6), "Row number 6 should have a pagebreak"); } [Test] public void TestShiftWithComments() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("comments.xls"); NPOI.SS.UserModel.ISheet sheet = wb.GetSheet("Sheet1"); Assert.AreEqual(3, sheet.LastRowNum); // Verify comments are in the position expected Assert.IsNotNull(sheet.GetCellComment(0, 0)); Assert.IsNull(sheet.GetCellComment(1, 0)); Assert.IsNotNull(sheet.GetCellComment(2, 0)); Assert.IsNotNull(sheet.GetCellComment(3, 0)); String comment1 = sheet.GetCellComment(0, 0).String.String; Assert.AreEqual(comment1, "comment top row1 (index0)\n"); String comment3 = sheet.GetCellComment(2, 0).String.String; Assert.AreEqual(comment3, "comment top row3 (index2)\n"); String comment4 = sheet.GetCellComment(3, 0).String.String; Assert.AreEqual(comment4, "comment top row4 (index3)\n"); // Shifting all but first line down to Test comments shifting sheet.ShiftRows(1, sheet.LastRowNum, 1, true, true); MemoryStream outputStream = new MemoryStream(); wb.Write(outputStream); // Test that comments were shifted as expected Assert.AreEqual(4, sheet.LastRowNum); Assert.IsNotNull(sheet.GetCellComment(0, 0)); Assert.IsNull(sheet.GetCellComment(1, 0)); Assert.IsNull(sheet.GetCellComment(2, 0)); Assert.IsNotNull(sheet.GetCellComment(3, 0)); Assert.IsNotNull(sheet.GetCellComment(4, 0)); String comment1_shifted = sheet.GetCellComment(0, 0).String.String; Assert.AreEqual(comment1, comment1_shifted); String comment3_shifted = sheet.GetCellComment(3, 0).String.String; Assert.AreEqual(comment3, comment3_shifted); String comment4_shifted = sheet.GetCellComment(4, 0).String.String; Assert.AreEqual(comment4, comment4_shifted); // Write out and read back in again // Ensure that the changes were persisted wb = new HSSFWorkbook(new MemoryStream(outputStream.ToArray())); sheet = wb.GetSheet("Sheet1"); Assert.AreEqual(4, sheet.LastRowNum); // Verify comments are in the position expected after the shift Assert.IsNotNull(sheet.GetCellComment(0, 0)); Assert.IsNull(sheet.GetCellComment(1, 0)); Assert.IsNull(sheet.GetCellComment(2, 0)); Assert.IsNotNull(sheet.GetCellComment(3, 0)); Assert.IsNotNull(sheet.GetCellComment(4, 0)); comment1_shifted = sheet.GetCellComment(0, 0).String.String; Assert.AreEqual(comment1, comment1_shifted); comment3_shifted = sheet.GetCellComment(3, 0).String.String; Assert.AreEqual(comment3, comment3_shifted); comment4_shifted = sheet.GetCellComment(4, 0).String.String; Assert.AreEqual(comment4, comment4_shifted); } /** * See bug #34023 */ [Test] public void TestShiftWithFormulas() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("ForShifting.xls"); NPOI.SS.UserModel.ISheet sheet = wb.GetSheet("Sheet1"); Assert.AreEqual(20, sheet.LastRowNum); ConfirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)"); ConfirmRow(sheet, 1, 2, 172, 1, "ROW(D2)", "100+B2", "COUNT(D2:E2)"); ConfirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)"); ConfirmCell(sheet, 6, 1, 271, "200+B1"); ConfirmCell(sheet, 7, 1, 272, "200+B2"); ConfirmCell(sheet, 8, 1, 273, "200+B3"); ConfirmCell(sheet, 14, 0, 0.0, "A12"); // the cell referred to by this formula will be replaced // ----------- // Row index 1 -> 11 (row "2" -> row "12") sheet.ShiftRows(1, 1, 10); // Now Check what sheet looks like after move // no changes on row "1" ConfirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)"); // row "2" is now empty Assert.AreEqual(0, sheet.GetRow(1).PhysicalNumberOfCells); // Row "2" moved to row "12", and the formula has been updated. // note however that the cached formula result (2) has not been updated. (POI differs from Excel here) ConfirmRow(sheet, 11, 2, 172, 1, "ROW(D12)", "100+B12", "COUNT(D12:E12)"); // no changes on row "3" ConfirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)"); ConfirmCell(sheet, 14, 0, 0.0, "#REF!"); // Formulas on rows that weren't shifted: ConfirmCell(sheet, 6, 1, 271, "200+B1"); ConfirmCell(sheet, 7, 1, 272, "200+B12"); // this one moved ConfirmCell(sheet, 8, 1, 273, "200+B3"); // Check formulas on other sheets NPOI.SS.UserModel.ISheet sheet2 = wb.GetSheet("Sheet2"); ConfirmCell(sheet2, 0, 0, 371, "300+Sheet1!B1"); ConfirmCell(sheet2, 1, 0, 372, "300+Sheet1!B12"); ConfirmCell(sheet2, 2, 0, 373, "300+Sheet1!B3"); ConfirmCell(sheet2, 11, 0, 300, "300+Sheet1!#REF!"); // Note - named ranges formulas have not been updated } private static void ConfirmRow(NPOI.SS.UserModel.ISheet sheet, int rowIx, double valA, double valB, double valC, String formulaA, String formulaB, String formulaC) { ConfirmCell(sheet, rowIx, 4, valA, formulaA); ConfirmCell(sheet, rowIx, 5, valB, formulaB); ConfirmCell(sheet, rowIx, 6, valC, formulaC); } private static void ConfirmCell(NPOI.SS.UserModel.ISheet sheet, int rowIx, int colIx, double expectedValue, String expectedFormula) { ICell cell = sheet.GetRow(rowIx).GetCell(colIx); Assert.AreEqual(expectedValue, cell.NumericCellValue, 0.0); Assert.AreEqual(expectedFormula, cell.CellFormula); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal sealed class OpenSslX509ChainProcessor : IChainPal { // Constructed (0x20) | Sequence (0x10) => 0x30. private const uint ConstructedSequenceTagId = 0x30; public void Dispose() { } public bool? Verify(X509VerificationFlags flags, out Exception exception) { exception = null; return ChainVerifier.Verify(ChainElements, flags); } public X509ChainElement[] ChainElements { get; private set; } public X509ChainStatus[] ChainStatus { get; private set; } public SafeX509ChainHandle SafeHandle { get { return null; } } public static IChainPal BuildChain( X509Certificate2 leaf, HashSet<X509Certificate2> candidates, HashSet<X509Certificate2> downloaded, HashSet<X509Certificate2> systemTrusted, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, ref TimeSpan remainingDownloadTime) { X509ChainElement[] elements; List<X509ChainStatus> overallStatus = new List<X509ChainStatus>(); WorkingChain workingChain = new WorkingChain(); Interop.Crypto.X509StoreVerifyCallback workingCallback = workingChain.VerifyCallback; // An X509_STORE is more comparable to Cryptography.X509Certificate2Collection than to // Cryptography.X509Store. So read this with OpenSSL eyes, not CAPI/CNG eyes. // // (If you need to think of it as an X509Store, it's a volatile memory store) using (SafeX509StoreHandle store = Interop.Crypto.X509StoreCreate()) using (SafeX509StoreCtxHandle storeCtx = Interop.Crypto.X509StoreCtxCreate()) { Interop.Crypto.CheckValidOpenSslHandle(store); Interop.Crypto.CheckValidOpenSslHandle(storeCtx); bool lookupCrl = revocationMode != X509RevocationMode.NoCheck; foreach (X509Certificate2 cert in candidates) { OpenSslX509CertificateReader pal = (OpenSslX509CertificateReader)cert.Pal; if (!Interop.Crypto.X509StoreAddCert(store, pal.SafeHandle)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } if (lookupCrl) { CrlCache.AddCrlForCertificate( cert, store, revocationMode, verificationTime, ref remainingDownloadTime); // If we only wanted the end-entity certificate CRL then don't look up // any more of them. lookupCrl = revocationFlag != X509RevocationFlag.EndCertificateOnly; } } if (revocationMode != X509RevocationMode.NoCheck) { if (!Interop.Crypto.X509StoreSetRevocationFlag(store, revocationFlag)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } } SafeX509Handle leafHandle = ((OpenSslX509CertificateReader)leaf.Pal).SafeHandle; if (!Interop.Crypto.X509StoreCtxInit(storeCtx, store, leafHandle)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } Interop.Crypto.X509StoreCtxSetVerifyCallback(storeCtx, workingCallback); Interop.Crypto.SetX509ChainVerifyTime(storeCtx, verificationTime); int verify = Interop.Crypto.X509VerifyCert(storeCtx); if (verify < 0) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } // Because our callback tells OpenSSL that every problem is ignorable, it should tell us that the // chain is just fine (unless it returned a negative code for an exception) Debug.Assert(verify == 1, "verify == 1"); using (SafeX509StackHandle chainStack = Interop.Crypto.X509StoreCtxGetChain(storeCtx)) { int chainSize = Interop.Crypto.GetX509StackFieldCount(chainStack); elements = new X509ChainElement[chainSize]; int maybeRootDepth = chainSize - 1; // The leaf cert is 0, up to (maybe) the root at chainSize - 1 for (int i = 0; i < chainSize; i++) { List<X509ChainStatus> status = new List<X509ChainStatus>(); List<Interop.Crypto.X509VerifyStatusCode> elementErrors = i < workingChain.Errors.Count ? workingChain.Errors[i] : null; if (elementErrors != null) { AddElementStatus(elementErrors, status, overallStatus); } IntPtr elementCertPtr = Interop.Crypto.GetX509StackField(chainStack, i); if (elementCertPtr == IntPtr.Zero) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } // Duplicate the certificate handle X509Certificate2 elementCert = new X509Certificate2(elementCertPtr); // If the last cert is self signed then it's the root cert, do any extra checks. if (i == maybeRootDepth && IsSelfSigned(elementCert)) { // If the root certificate was downloaded or the system // doesn't trust it, it's untrusted. if (downloaded.Contains(elementCert) || !systemTrusted.Contains(elementCert)) { AddElementStatus( Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_UNTRUSTED, status, overallStatus); } } elements[i] = new X509ChainElement(elementCert, status.ToArray(), ""); } } } GC.KeepAlive(workingCallback); if ((certificatePolicy != null && certificatePolicy.Count > 0) || (applicationPolicy != null && applicationPolicy.Count > 0)) { List<X509Certificate2> certsToRead = new List<X509Certificate2>(); foreach (X509ChainElement element in elements) { certsToRead.Add(element.Certificate); } CertificatePolicyChain policyChain = new CertificatePolicyChain(certsToRead); bool failsPolicyChecks = false; if (certificatePolicy != null) { if (!policyChain.MatchesCertificatePolicies(certificatePolicy)) { failsPolicyChecks = true; } } if (applicationPolicy != null) { if (!policyChain.MatchesApplicationPolicies(applicationPolicy)) { failsPolicyChecks = true; } } if (failsPolicyChecks) { X509ChainElement leafElement = elements[0]; X509ChainStatus chainStatus = new X509ChainStatus { Status = X509ChainStatusFlags.NotValidForUsage, StatusInformation = SR.Chain_NoPolicyMatch, }; var elementStatus = new List<X509ChainStatus>(leafElement.ChainElementStatus.Length + 1); elementStatus.AddRange(leafElement.ChainElementStatus); AddUniqueStatus(elementStatus, ref chainStatus); AddUniqueStatus(overallStatus, ref chainStatus); elements[0] = new X509ChainElement( leafElement.Certificate, elementStatus.ToArray(), leafElement.Information); } } return new OpenSslX509ChainProcessor { ChainStatus = overallStatus.ToArray(), ChainElements = elements, }; } private static void AddElementStatus( List<Interop.Crypto.X509VerifyStatusCode> errorCodes, List<X509ChainStatus> elementStatus, List<X509ChainStatus> overallStatus) { foreach (var errorCode in errorCodes) { AddElementStatus(errorCode, elementStatus, overallStatus); } } private static void AddElementStatus( Interop.Crypto.X509VerifyStatusCode errorCode, List<X509ChainStatus> elementStatus, List<X509ChainStatus> overallStatus) { X509ChainStatusFlags statusFlag = MapVerifyErrorToChainStatus(errorCode); Debug.Assert( (statusFlag & (statusFlag - 1)) == 0, "Status flag has more than one bit set", "More than one bit is set in status '{0}' for error code '{1}'", statusFlag, errorCode); foreach (X509ChainStatus currentStatus in elementStatus) { if ((currentStatus.Status & statusFlag) != 0) { return; } } X509ChainStatus chainStatus = new X509ChainStatus { Status = statusFlag, StatusInformation = Interop.Crypto.GetX509VerifyCertErrorString(errorCode), }; elementStatus.Add(chainStatus); AddUniqueStatus(overallStatus, ref chainStatus); } private static void AddUniqueStatus(IList<X509ChainStatus> list, ref X509ChainStatus status) { X509ChainStatusFlags statusCode = status.Status; for (int i = 0; i < list.Count; i++) { if (list[i].Status == statusCode) { return; } } list.Add(status); } private static X509ChainStatusFlags MapVerifyErrorToChainStatus(Interop.Crypto.X509VerifyStatusCode code) { switch (code) { case Interop.Crypto.X509VerifyStatusCode.X509_V_OK: return X509ChainStatusFlags.NoError; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_NOT_YET_VALID: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_HAS_EXPIRED: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: return X509ChainStatusFlags.NotTimeValid; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REVOKED: return X509ChainStatusFlags.Revoked; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_SIGNATURE_FAILURE: return X509ChainStatusFlags.NotSignatureValid; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_UNTRUSTED: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: return X509ChainStatusFlags.UntrustedRoot; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_HAS_EXPIRED: return X509ChainStatusFlags.OfflineRevocation; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_NOT_YET_VALID: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_SIGNATURE_FAILURE: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: return X509ChainStatusFlags.RevocationStatusUnknown; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_EXTENSION: return X509ChainStatusFlags.InvalidExtension; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: return X509ChainStatusFlags.PartialChain; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_PURPOSE: return X509ChainStatusFlags.NotValidForUsage; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_CA: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_NON_CA: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_PATH_LENGTH_EXCEEDED: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CERTSIGN: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: return X509ChainStatusFlags.InvalidBasicConstraints; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_POLICY_EXTENSION: case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_NO_EXPLICIT_POLICY: return X509ChainStatusFlags.InvalidPolicyConstraints; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REJECTED: return X509ChainStatusFlags.ExplicitDistrust; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: return X509ChainStatusFlags.HasNotSupportedCriticalExtension; case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_CHAIN_TOO_LONG: throw new CryptographicException(); case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_OUT_OF_MEM: throw new OutOfMemoryException(); default: Debug.Fail("Unrecognized X509VerifyStatusCode:" + code); throw new CryptographicException(); } } internal static HashSet<X509Certificate2> FindCandidates( X509Certificate2 leaf, X509Certificate2Collection extraStore, HashSet<X509Certificate2> downloaded, HashSet<X509Certificate2> systemTrusted, ref TimeSpan remainingDownloadTime) { var candidates = new HashSet<X509Certificate2>(); var toProcess = new Queue<X509Certificate2>(); toProcess.Enqueue(leaf); using (var systemRootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) using (var systemIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine)) using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser)) using (var userIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser)) { systemRootStore.Open(OpenFlags.ReadOnly); systemIntermediateStore.Open(OpenFlags.ReadOnly); userRootStore.Open(OpenFlags.ReadOnly); userIntermediateStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection systemRootCerts = systemRootStore.Certificates; X509Certificate2Collection systemIntermediateCerts = systemIntermediateStore.Certificates; X509Certificate2Collection userRootCerts = userRootStore.Certificates; X509Certificate2Collection userIntermediateCerts = userIntermediateStore.Certificates; // fill the system trusted collection foreach (X509Certificate2 userRootCert in userRootCerts) { if (!systemTrusted.Add(userRootCert)) { // If we have already (effectively) added another instance of this certificate, // then this one provides no value. A Disposed cert won't harm the matching logic. userRootCert.Dispose(); } } foreach (X509Certificate2 systemRootCert in systemRootCerts) { if (!systemTrusted.Add(systemRootCert)) { // If we have already (effectively) added another instance of this certificate, // (for example, because another copy of it was in the user store) // then this one provides no value. A Disposed cert won't harm the matching logic. systemRootCert.Dispose(); } } X509Certificate2Collection[] storesToCheck = { extraStore, userIntermediateCerts, systemIntermediateCerts, userRootCerts, systemRootCerts, }; while (toProcess.Count > 0) { X509Certificate2 current = toProcess.Dequeue(); candidates.Add(current); HashSet<X509Certificate2> results = FindIssuer( current, storesToCheck, downloaded, ref remainingDownloadTime); if (results != null) { foreach (X509Certificate2 result in results) { if (!candidates.Contains(result)) { toProcess.Enqueue(result); } } } } // Avoid sending unused certs into the finalizer queue by doing only a ref check var candidatesByReference = new HashSet<X509Certificate2>( candidates, ReferenceEqualityComparer<X509Certificate2>.Instance); // Certificates come from 5 sources: // 1) extraStore. // These are cert objects that are provided by the user, we shouldn't dispose them. // 2) the machine root store // These certs are moving on to the "was I a system trust?" test, and we shouldn't dispose them. // 3) the user root store // These certs are moving on to the "was I a system trust?" test, and we shouldn't dispose them. // 4) the machine intermediate store // These certs were either path candidates, or not. If they were, don't dispose them. Otherwise do. // 5) the user intermediate store // These certs were either path candidates, or not. If they were, don't dispose them. Otherwise do. DisposeUnreferenced(candidatesByReference, systemIntermediateCerts); DisposeUnreferenced(candidatesByReference, userIntermediateCerts); } return candidates; } private static void DisposeUnreferenced( ISet<X509Certificate2> referencedSet, X509Certificate2Collection storeCerts) { foreach (X509Certificate2 cert in storeCerts) { if (!referencedSet.Contains(cert)) { cert.Dispose(); } } } private static HashSet<X509Certificate2> FindIssuer( X509Certificate2 cert, X509Certificate2Collection[] stores, HashSet<X509Certificate2> downloadedCerts, ref TimeSpan remainingDownloadTime) { if (IsSelfSigned(cert)) { // It's a root cert, we won't make any progress. return null; } SafeX509Handle certHandle = ((OpenSslX509CertificateReader)cert.Pal).SafeHandle; foreach (X509Certificate2Collection store in stores) { HashSet<X509Certificate2> fromStore = null; foreach (X509Certificate2 candidate in store) { var certPal = (OpenSslX509CertificateReader)candidate.Pal; if (certPal == null) { continue; } SafeX509Handle candidateHandle = certPal.SafeHandle; int issuerError = Interop.Crypto.X509CheckIssued(candidateHandle, certHandle); if (issuerError == 0) { if (fromStore == null) { fromStore = new HashSet<X509Certificate2>(); } fromStore.Add(candidate); } } if (fromStore != null) { return fromStore; } } byte[] authorityInformationAccess = null; foreach (X509Extension extension in cert.Extensions) { if (StringComparer.Ordinal.Equals(extension.Oid.Value, Oids.AuthorityInformationAccess)) { // If there's an Authority Information Access extension, it might be used for // looking up additional certificates for the chain. authorityInformationAccess = extension.RawData; break; } } if (authorityInformationAccess != null) { X509Certificate2 downloaded = DownloadCertificate( authorityInformationAccess, ref remainingDownloadTime); if (downloaded != null) { downloadedCerts.Add(downloaded); return new HashSet<X509Certificate2>() { downloaded }; } } return null; } private static bool IsSelfSigned(X509Certificate2 cert) { return StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer); } private static X509Certificate2 DownloadCertificate( byte[] authorityInformationAccess, ref TimeSpan remainingDownloadTime) { // Don't do any work if we're over limit. if (remainingDownloadTime <= TimeSpan.Zero) { return null; } string uri = FindHttpAiaRecord(authorityInformationAccess, Oids.CertificateAuthorityIssuers); if (uri == null) { return null; } return CertificateAssetDownloader.DownloadCertificate(uri, ref remainingDownloadTime); } internal static string FindHttpAiaRecord(byte[] authorityInformationAccess, string recordTypeOid) { DerSequenceReader reader = new DerSequenceReader(authorityInformationAccess); while (reader.HasData) { DerSequenceReader innerReader = reader.ReadSequence(); // If the sequence's first element is a sequence, unwrap it. if (innerReader.PeekTag() == ConstructedSequenceTagId) { innerReader = innerReader.ReadSequence(); } Oid oid = innerReader.ReadOid(); if (StringComparer.Ordinal.Equals(oid.Value, recordTypeOid)) { string uri = innerReader.ReadIA5String(); Uri parsedUri; if (!Uri.TryCreate(uri, UriKind.Absolute, out parsedUri)) { continue; } if (!StringComparer.Ordinal.Equals(parsedUri.Scheme, "http")) { continue; } return uri; } } return null; } private class WorkingChain { internal readonly List<List<Interop.Crypto.X509VerifyStatusCode>> Errors = new List<List<Interop.Crypto.X509VerifyStatusCode>>(); internal int VerifyCallback(int ok, IntPtr ctx) { if (ok < 0) { return ok; } try { using (var storeCtx = new SafeX509StoreCtxHandle(ctx, ownsHandle: false)) { Interop.Crypto.X509VerifyStatusCode errorCode = Interop.Crypto.X509StoreCtxGetError(storeCtx); int errorDepth = Interop.Crypto.X509StoreCtxGetErrorDepth(storeCtx); // We don't report "OK" as an error. // For compatibility with Windows / .NET Framework, do not report X509_V_CRL_NOT_YET_VALID. if (errorCode != Interop.Crypto.X509VerifyStatusCode.X509_V_OK && errorCode != Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_NOT_YET_VALID) { while (Errors.Count <= errorDepth) { Errors.Add(null); } if (Errors[errorDepth] == null) { Errors[errorDepth] = new List<Interop.Crypto.X509VerifyStatusCode>(); } Errors[errorDepth].Add(errorCode); } } return 1; } catch { return -1; } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Orleans; using Orleans.CodeGeneration; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using Orleans.Versions.Compatibility; using Orleans.Versions.Selector; using TestVersionGrainInterfaces; using Xunit; namespace Tester.HeterogeneousSilosTests.UpgradeTests { public abstract class UpgradeTestsBase : IDisposable { private readonly TimeSpan refreshInterval = TimeSpan.FromMilliseconds(200); private TimeSpan waitDelay; protected IClusterClient Client { get; private set; } protected IManagementGrain ManagementGrain { get; private set; } #if DEBUG private const string BuildConfiguration = "Debug"; #else private const string BuildConfiguration = "Release"; #endif private const string AssemblyGrainsV1Build = "TestVersionGrainsV1"; private const string AssemblyGrainsV2Build = "TestVersionGrainsV2"; private const string CommonParentDirectory = "test"; private const string BinDirectory = "bin"; private const string VersionsProjectDirectory = "Versions"; private const string GrainsV1ProjectName = "TestVersionGrains"; private const string GrainsV2ProjectName = "TestVersionGrains2"; private const string VersionTestBinaryName = "TestVersionGrains.dll"; private readonly DirectoryInfo assemblyGrainsV1Dir; private readonly DirectoryInfo assemblyGrainsV2Dir; private TestClusterOptions options; private readonly List<SiloHandle> deployedSilos = new List<SiloHandle>(); private int siloIdx = 0; protected abstract VersionSelectorStrategy VersionSelectorStrategy { get; } protected abstract CompatibilityStrategy CompatibilityStrategy { get; } protected virtual short SiloCount => 2; protected UpgradeTestsBase() { // Setup dll references // If test run from old master cmd line with single output directory if (Directory.Exists(AssemblyGrainsV1Build)) { assemblyGrainsV1Dir = new DirectoryInfo(AssemblyGrainsV1Build); assemblyGrainsV2Dir = new DirectoryInfo(AssemblyGrainsV2Build); } else { var testDirectory = new DirectoryInfo(GetType().Assembly.Location); while (String.Compare(testDirectory.Name, CommonParentDirectory, StringComparison.OrdinalIgnoreCase) != 0 || testDirectory.Parent == null) { testDirectory = testDirectory.Parent; } if (testDirectory.Parent == null) { throw new InvalidOperationException($"Cannot locate 'test' directory starting from '{GetType().Assembly.Location}'"); } assemblyGrainsV1Dir = GetVersionTestDirectory(testDirectory, GrainsV1ProjectName); assemblyGrainsV2Dir = GetVersionTestDirectory(testDirectory, GrainsV2ProjectName); } } private DirectoryInfo GetVersionTestDirectory(DirectoryInfo testDirectory, string directoryName) { var projectDirectory = Path.Combine(testDirectory.FullName, VersionsProjectDirectory, directoryName, BinDirectory); var directories = Directory.GetDirectories(projectDirectory, BuildConfiguration, SearchOption.AllDirectories); if (directories.Length != 1) { throw new InvalidOperationException($"Number of directories found for pattern: '{BuildConfiguration}' under {testDirectory.FullName}: {directories.Length}"); } var files = Directory.GetFiles(directories[0], VersionTestBinaryName, SearchOption.AllDirectories); if (files.Length != 1) { throw new InvalidOperationException($"Number of files found for pattern: '{VersionTestBinaryName}' under {testDirectory.FullName}: {files.Length}"); } return new DirectoryInfo(Path.GetDirectoryName(files[0])); } protected async Task Step1_StartV1Silo_Step2_StartV2Silo_Step3_StopV2Silo(int step2Version) { const int numberOfGrains = 100; await StartSiloV1(); // Only V1 exist for now for (var i = 0; i < numberOfGrains; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(1, await grain.GetVersion()); } // Start a new silo with V2 var siloV2 = await StartSiloV2(); for (var i = 0; i < numberOfGrains; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(1, await grain.GetVersion()); } for (var i = numberOfGrains; i < numberOfGrains * 2; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(step2Version, await grain.GetVersion()); } // Stop the V2 silo await StopSilo(siloV2); // Now all activation should be V1 for (var i = 0; i < numberOfGrains * 3; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(1, await grain.GetVersion()); } } protected async Task ProxyCallNoPendingRequest(int expectedVersion) { await StartSiloV1(); // Only V1 exist for now var grain0 = Client.GetGrain<IVersionUpgradeTestGrain>(0); Assert.Equal(1, await grain0.GetVersion()); await StartSiloV2(); // New activation should be V2 var grain1 = Client.GetGrain<IVersionUpgradeTestGrain>(1); Assert.Equal(2, await grain1.GetVersion()); Assert.Equal(expectedVersion, await grain1.ProxyGetVersion(grain0)); Assert.Equal(expectedVersion, await grain0.GetVersion()); } protected async Task ProxyCallWithPendingRequest(int expectedVersion) { await StartSiloV1(); // Only V1 exist for now var grain0 = Client.GetGrain<IVersionUpgradeTestGrain>(0); Assert.Equal(1, await grain0.GetVersion()); // Start a new silo with V2 await StartSiloV2(); // New activation should be V2 var grain1 = Client.GetGrain<IVersionUpgradeTestGrain>(1); Assert.Equal(2, await grain1.GetVersion()); var waitingTask = grain0.LongRunningTask(TimeSpan.FromSeconds(5)); var callBeforeUpgrade = grain0.GetVersion(); await Task.Delay(100); // Make sure requests are not sent out of order var callProvokingUpgrade = grain1.ProxyGetVersion(grain0); await waitingTask; Assert.Equal(1, await callBeforeUpgrade); Assert.Equal(expectedVersion, await callProvokingUpgrade); } protected async Task<SiloHandle> StartSiloV1() { var handle = await StartSilo(assemblyGrainsV1Dir); await Task.Delay(waitDelay); return handle; } protected async Task<SiloHandle> StartSiloV2() { var handle = await StartSilo(assemblyGrainsV2Dir); await Task.Delay(waitDelay); return handle; } private async Task<SiloHandle> StartSilo(DirectoryInfo rootDir) { string siloName; Silo.SiloType siloType; if (this.siloIdx == 0) { // First silo siloName = Silo.PrimarySiloName; siloType = Silo.SiloType.Primary; // Setup configuration this.options = new TestClusterOptions(SiloCount); options.ClusterConfiguration.Globals.AssumeHomogenousSilosForTesting = false; options.ClusterConfiguration.Globals.TypeMapRefreshInterval = refreshInterval; options.ClusterConfiguration.Globals.DefaultVersionSelectorStrategy = VersionSelectorStrategy; options.ClusterConfiguration.Globals.DefaultCompatibilityStrategy = CompatibilityStrategy; options.ClientConfiguration.Gateways = options.ClientConfiguration.Gateways.Take(1).ToList(); // Only use primary gw options.ClusterConfiguration.AddMemoryStorageProvider("Default"); waitDelay = TestCluster.GetLivenessStabilizationTime(options.ClusterConfiguration.Globals, false); } else { // Secondary Silo siloName = $"Secondary_{siloIdx}"; siloType = Silo.SiloType.Secondary; } var silo = AppDomainSiloHandle.Create( siloName, siloType, typeof(TestVersionGrains.VersionGrainsSiloBuilderFactory), this.options.ClusterConfiguration, this.options.ClusterConfiguration.Overrides[siloName], applicationBase: rootDir.FullName); if (this.siloIdx == 0) { // If it was the first silo, setup the client Client = new ClientBuilder() .AddApplicationPartsFromAppDomain() .UseConfiguration(options.ClientConfiguration) .Build(); await Client.Connect(); ManagementGrain = Client.GetGrain<IManagementGrain>(0); } this.deployedSilos.Add(silo); this.siloIdx++; return silo; } protected async Task StopSilo(SiloHandle handle) { handle?.StopSilo(true); this.deployedSilos.Remove(handle); await Task.Delay(waitDelay); } public void Dispose() { if (!deployedSilos.Any()) return; var primarySilo = this.deployedSilos[0]; foreach (var silo in this.deployedSilos.Skip(1)) { silo.Dispose(); } primarySilo.Dispose(); this.Client?.Dispose(); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // EncryptedType.cs // // This object implements the abstract type from which EncryptedData and EncrytpedKey derive. // // 04/01/2002 // namespace System.Security.Cryptography.Xml { using System; using System.Collections; using System.Xml; [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public abstract class EncryptedType { private string m_id; private string m_type; private string m_mimeType; private string m_encoding; private EncryptionMethod m_encryptionMethod; private CipherData m_cipherData; private EncryptionPropertyCollection m_props; private KeyInfo m_keyInfo; internal XmlElement m_cachedXml = null; internal bool CacheValid { get { return (m_cachedXml != null); } } public virtual string Id { get { return m_id; } set { m_id = value; m_cachedXml = null; } } public virtual string Type { get { return m_type; } set { m_type = value; m_cachedXml = null; } } public virtual string MimeType { get { return m_mimeType; } set { m_mimeType = value; m_cachedXml = null; } } public virtual string Encoding { get { return m_encoding; } set { m_encoding = value; m_cachedXml = null; } } public KeyInfo KeyInfo { get { if (m_keyInfo == null) m_keyInfo = new KeyInfo(); return m_keyInfo; } set { m_keyInfo = value; } } public virtual EncryptionMethod EncryptionMethod { get { return m_encryptionMethod; } set { m_encryptionMethod = value; m_cachedXml = null; } } public virtual EncryptionPropertyCollection EncryptionProperties { get { if (m_props == null) m_props = new EncryptionPropertyCollection(); return m_props; } } public void AddProperty(EncryptionProperty ep) { this.EncryptionProperties.Add(ep); } public virtual CipherData CipherData { get { if (m_cipherData == null) m_cipherData = new CipherData(); return m_cipherData; } set { if (value == null) throw new ArgumentNullException("value"); m_cipherData = value; m_cachedXml = null; } } public abstract void LoadXml (XmlElement value); public abstract XmlElement GetXml(); } [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public class EncryptionMethod { private XmlElement m_cachedXml = null; private int m_keySize = 0; private string m_algorithm; public EncryptionMethod () { m_cachedXml = null; } public EncryptionMethod (string algorithm) { m_algorithm = algorithm; m_cachedXml = null; } private bool CacheValid { get { return (m_cachedXml != null); } } public int KeySize { get { return m_keySize; } set { if (value <= 0) throw new ArgumentOutOfRangeException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidKeySize")); m_keySize = value; m_cachedXml = null; } } public string KeyAlgorithm { get { return m_algorithm; } set { m_algorithm = value; m_cachedXml = null; } } public XmlElement GetXml() { if (CacheValid) return(m_cachedXml); XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; return GetXml(document); } internal XmlElement GetXml (XmlDocument document) { // Create the EncryptionMethod element XmlElement encryptionMethodElement = (XmlElement) document.CreateElement("EncryptionMethod", EncryptedXml.XmlEncNamespaceUrl); if (!String.IsNullOrEmpty(m_algorithm)) encryptionMethodElement.SetAttribute("Algorithm", m_algorithm); if (m_keySize > 0) { // Construct a KeySize element XmlElement keySizeElement = document.CreateElement("KeySize", EncryptedXml.XmlEncNamespaceUrl); keySizeElement.AppendChild(document.CreateTextNode(m_keySize.ToString(null, null))); encryptionMethodElement.AppendChild(keySizeElement); } return encryptionMethodElement; } public void LoadXml(XmlElement value) { if (value == null) throw new ArgumentNullException("value"); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); XmlElement encryptionMethodElement = value; m_algorithm = Utils.GetAttribute(encryptionMethodElement, "Algorithm", EncryptedXml.XmlEncNamespaceUrl); XmlNode keySizeNode = value.SelectSingleNode("enc:KeySize", nsm); if (keySizeNode != null) { KeySize = Convert.ToInt32(Utils.DiscardWhiteSpaces(keySizeNode.InnerText), null); } // Save away the cached value m_cachedXml = value; } } [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class EncryptionProperty { private string m_target; private string m_id; private XmlElement m_elemProp; private XmlElement m_cachedXml = null; // We are being lax here as per the spec public EncryptionProperty() {} public EncryptionProperty(XmlElement elementProperty) { if (elementProperty == null) throw new ArgumentNullException("elementProperty"); if (elementProperty.LocalName != "EncryptionProperty" || elementProperty.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidEncryptionProperty")); m_elemProp = elementProperty; m_cachedXml = null; } public string Id { get { return m_id; } } public string Target { get { return m_target; } } public XmlElement PropertyElement { get { return m_elemProp; } set { if (value == null) throw new ArgumentNullException("value"); if (value.LocalName != "EncryptionProperty" || value.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidEncryptionProperty")); m_elemProp = value; m_cachedXml = null; } } private bool CacheValid { get { return (m_cachedXml != null); } } public XmlElement GetXml() { if (CacheValid) return m_cachedXml; XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; return GetXml(document); } internal XmlElement GetXml (XmlDocument document) { return document.ImportNode(m_elemProp, true) as XmlElement; } public void LoadXml(XmlElement value) { if (value == null) throw new ArgumentNullException("value"); if (value.LocalName != "EncryptionProperty" || value.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidEncryptionProperty")); // cache the Xml m_cachedXml = value; m_id = Utils.GetAttribute(value, "Id", EncryptedXml.XmlEncNamespaceUrl); m_target = Utils.GetAttribute(value, "Target", EncryptedXml.XmlEncNamespaceUrl); m_elemProp = value; } } [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class EncryptionPropertyCollection : IList { private ArrayList m_props; public EncryptionPropertyCollection() { m_props = new ArrayList(); } public IEnumerator GetEnumerator() { return m_props.GetEnumerator(); } public int Count { get { return m_props.Count; } } /// <internalonly/> int IList.Add(Object value) { if (!(value is EncryptionProperty)) throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_Xml_IncorrectObjectType"), "value"); return m_props.Add(value); } public int Add(EncryptionProperty value) { return m_props.Add(value); } public void Clear() { m_props.Clear(); } /// <internalonly/> bool IList.Contains(Object value) { if (!(value is EncryptionProperty)) throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_Xml_IncorrectObjectType"), "value"); return m_props.Contains(value); } public bool Contains(EncryptionProperty value) { return m_props.Contains(value); } /// <internalonly/> int IList.IndexOf(Object value) { if (!(value is EncryptionProperty)) throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_Xml_IncorrectObjectType"), "value"); return m_props.IndexOf(value); } public int IndexOf(EncryptionProperty value) { return m_props.IndexOf(value); } /// <internalonly/> void IList.Insert(int index, Object value) { if (!(value is EncryptionProperty)) throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_Xml_IncorrectObjectType"), "value"); m_props.Insert(index, value); } public void Insert(int index, EncryptionProperty value) { m_props.Insert(index, value); } /// <internalonly/> void IList.Remove(Object value) { if (!(value is EncryptionProperty)) throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_Xml_IncorrectObjectType"), "value"); m_props.Remove(value); } public void Remove(EncryptionProperty value) { m_props.Remove(value); } public void RemoveAt(int index) { m_props.RemoveAt(index); } public Boolean IsFixedSize { get { return m_props.IsFixedSize; } } public Boolean IsReadOnly { get { return m_props.IsReadOnly; } } public EncryptionProperty Item(int index) { return (EncryptionProperty) m_props[index]; } [System.Runtime.CompilerServices.IndexerName ("ItemOf")] public EncryptionProperty this[int index] { get { return (EncryptionProperty) ((IList) this)[index]; } set { ((IList) this)[index] = value; } } /// <internalonly/> Object IList.this[int index] { get { return m_props[index]; } set { if (!(value is EncryptionProperty)) throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_Xml_IncorrectObjectType"), "value"); m_props[index] = value; } } /// <internalonly/> public void CopyTo(Array array, int index) { m_props.CopyTo(array, index); } public void CopyTo(EncryptionProperty[] array, int index) { m_props.CopyTo(array, index); } public Object SyncRoot { get { return m_props.SyncRoot; } } public bool IsSynchronized { get { return m_props.IsSynchronized; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // Don't entity encode high chars (160 to 256) #define ENTITY_ENCODE_HIGH_ASCII_CHARS using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Net.Configuration; using System.Runtime.Versioning; using System.Text; namespace System.Net { public static class WebUtility { // some consts copied from Char / CharUnicodeInfo since we don't have friend access to those types private const char HIGH_SURROGATE_START = '\uD800'; private const char LOW_SURROGATE_START = '\uDC00'; private const char LOW_SURROGATE_END = '\uDFFF'; private const int UNICODE_PLANE00_END = 0x00FFFF; private const int UNICODE_PLANE01_START = 0x10000; private const int UNICODE_PLANE16_END = 0x10FFFF; private const int UnicodeReplacementChar = '\uFFFD'; private static readonly UnicodeDecodingConformance s_htmlDecodeConformance; private static readonly UnicodeEncodingConformance s_htmlEncodeConformance; static WebUtility() { s_htmlDecodeConformance = UnicodeDecodingConformance.Strict; s_htmlEncodeConformance = UnicodeEncodingConformance.Strict; } #region HtmlEncode / HtmlDecode methods private static readonly char[] s_htmlEntityEndingChars = new char[] { ';', '&' }; public static string HtmlEncode(string value) { if (String.IsNullOrEmpty(value)) { return value; } // Don't create string writer if we don't have nothing to encode int index = IndexOfHtmlEncodingChars(value, 0); if (index == -1) { return value; } LowLevelStringWriter writer = new LowLevelStringWriter(); HtmlEncode(value, writer); return writer.ToString(); } private static unsafe void HtmlEncode(string value, LowLevelTextWriter output) { if (value == null) { return; } if (output == null) { throw new ArgumentNullException("output"); } int index = IndexOfHtmlEncodingChars(value, 0); if (index == -1) { output.Write(value); return; } Debug.Assert(0 <= index && index <= value.Length, "0 <= index && index <= value.Length"); int cch = value.Length - index; fixed (char* str = value) { char* pch = str; while (index-- > 0) { output.Write(*pch++); } for (; cch > 0; cch--, pch++) { char ch = *pch; if (ch <= '>') { switch (ch) { case '<': output.Write("&lt;"); break; case '>': output.Write("&gt;"); break; case '"': output.Write("&quot;"); break; case '\'': output.Write("&#39;"); break; case '&': output.Write("&amp;"); break; default: output.Write(ch); break; } } else { int valueToEncode = -1; // set to >= 0 if needs to be encoded #if ENTITY_ENCODE_HIGH_ASCII_CHARS if (ch >= 160 && ch < 256) { // The seemingly arbitrary 160 comes from RFC valueToEncode = ch; } else #endif // ENTITY_ENCODE_HIGH_ASCII_CHARS if (s_htmlEncodeConformance == UnicodeEncodingConformance.Strict && Char.IsSurrogate(ch)) { int scalarValue = GetNextUnicodeScalarValueFromUtf16Surrogate(ref pch, ref cch); if (scalarValue >= UNICODE_PLANE01_START) { valueToEncode = scalarValue; } else { // Don't encode BMP characters (like U+FFFD) since they wouldn't have // been encoded if explicitly present in the string anyway. ch = (char)scalarValue; } } if (valueToEncode >= 0) { // value needs to be encoded output.Write("&#"); output.Write(valueToEncode.ToString(CultureInfo.InvariantCulture)); output.Write(';'); } else { // write out the character directly output.Write(ch); } } } } } public static string HtmlDecode(string value) { if (String.IsNullOrEmpty(value)) { return value; } // Don't create string writer if we don't have nothing to encode if (!StringRequiresHtmlDecoding(value)) { return value; } LowLevelStringWriter writer = new LowLevelStringWriter(); HtmlDecode(value, writer); return writer.ToString(); } [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.UInt16.TryParse(System.String,System.Globalization.NumberStyles,System.IFormatProvider,System.UInt16@)", Justification = "UInt16.TryParse guarantees that result is zero if the parse fails.")] private static void HtmlDecode(string value, LowLevelTextWriter output) { if (value == null) { return; } if (output == null) { throw new ArgumentNullException("output"); } if (!StringRequiresHtmlDecoding(value)) { output.Write(value); // good as is return; } int l = value.Length; for (int i = 0; i < l; i++) { char ch = value[i]; if (ch == '&') { // We found a '&'. Now look for the next ';' or '&'. The idea is that // if we find another '&' before finding a ';', then this is not an entity, // and the next '&' might start a real entity (VSWhidbey 275184) int index = value.IndexOfAny(s_htmlEntityEndingChars, i + 1); if (index > 0 && value[index] == ';') { string entity = value.Substring(i + 1, index - i - 1); if (entity.Length > 1 && entity[0] == '#') { // The # syntax can be in decimal or hex, e.g. // &#229; --> decimal // &#xE5; --> same char in hex // See http://www.w3.org/TR/REC-html40/charset.html#entities bool parsedSuccessfully; uint parsedValue; if (entity[1] == 'x' || entity[1] == 'X') { parsedSuccessfully = UInt32.TryParse(entity.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out parsedValue); } else { parsedSuccessfully = UInt32.TryParse(entity.Substring(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedValue); } if (parsedSuccessfully) { switch (s_htmlDecodeConformance) { case UnicodeDecodingConformance.Strict: // decoded character must be U+0000 .. U+10FFFF, excluding surrogates parsedSuccessfully = ((parsedValue < HIGH_SURROGATE_START) || (LOW_SURROGATE_END < parsedValue && parsedValue <= UNICODE_PLANE16_END)); break; case UnicodeDecodingConformance.Compat: // decoded character must be U+0001 .. U+FFFF // null chars disallowed for compat with 4.0 parsedSuccessfully = (0 < parsedValue && parsedValue <= UNICODE_PLANE00_END); break; case UnicodeDecodingConformance.Loose: // decoded character must be U+0000 .. U+10FFFF parsedSuccessfully = (parsedValue <= UNICODE_PLANE16_END); break; default: Debug.Assert(false, "Should never get here!"); parsedSuccessfully = false; break; } } if (parsedSuccessfully) { if (parsedValue <= UNICODE_PLANE00_END) { // single character output.Write((char)parsedValue); } else { // multi-character char leadingSurrogate, trailingSurrogate; ConvertSmpToUtf16(parsedValue, out leadingSurrogate, out trailingSurrogate); output.Write(leadingSurrogate); output.Write(trailingSurrogate); } i = index; // already looked at everything until semicolon continue; } } else { i = index; // already looked at everything until semicolon char entityChar = HtmlEntities.Lookup(entity); if (entityChar != (char)0) { ch = entityChar; } else { output.Write('&'); output.Write(entity); output.Write(';'); continue; } } } } output.Write(ch); } } private static unsafe int IndexOfHtmlEncodingChars(string s, int startPos) { Debug.Assert(0 <= startPos && startPos <= s.Length, "0 <= startPos && startPos <= s.Length"); int cch = s.Length - startPos; fixed (char* str = s) { for (char* pch = &str[startPos]; cch > 0; pch++, cch--) { char ch = *pch; if (ch <= '>') { switch (ch) { case '<': case '>': case '"': case '\'': case '&': return s.Length - cch; } } #if ENTITY_ENCODE_HIGH_ASCII_CHARS else if (ch >= 160 && ch < 256) { return s.Length - cch; } #endif // ENTITY_ENCODE_HIGH_ASCII_CHARS else if (s_htmlEncodeConformance == UnicodeEncodingConformance.Strict && Char.IsSurrogate(ch)) { return s.Length - cch; } } } return -1; } #endregion #region UrlEncode implementation // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. private static byte[] UrlEncode(byte[] bytes, int offset, int count, bool alwaysCreateNewReturnValue) { byte[] encoded = UrlEncode(bytes, offset, count); return (alwaysCreateNewReturnValue && (encoded != null) && (encoded == bytes)) ? (byte[])encoded.Clone() : encoded; } private static byte[] UrlEncode(byte[] bytes, int offset, int count) { if (!ValidateUrlEncodingParameters(bytes, offset, count)) { return null; } int cSpaces = 0; int cUnsafe = 0; // count them first for (int i = 0; i < count; i++) { char ch = (char)bytes[offset + i]; if (ch == ' ') cSpaces++; else if (!IsUrlSafeChar(ch)) cUnsafe++; } // nothing to expand? if (cSpaces == 0 && cUnsafe == 0) return bytes; // expand not 'safe' characters into %XX, spaces to +s byte[] expandedBytes = new byte[count + cUnsafe * 2]; int pos = 0; for (int i = 0; i < count; i++) { byte b = bytes[offset + i]; char ch = (char)b; if (IsUrlSafeChar(ch)) { expandedBytes[pos++] = b; } else if (ch == ' ') { expandedBytes[pos++] = (byte)'+'; } else { expandedBytes[pos++] = (byte)'%'; expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf); expandedBytes[pos++] = (byte)IntToHex(b & 0x0f); } } return expandedBytes; } #endregion #region UrlEncode public methods [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Already shipped public API; code moved here as part of API consolidation")] public static string UrlEncode(string value) { if (value == null) return null; byte[] bytes = Encoding.UTF8.GetBytes(value); byte[] encodedBytes = UrlEncode(bytes, 0, bytes.Length, false /* alwaysCreateNewReturnValue */); return Encoding.UTF8.GetString(encodedBytes, 0, encodedBytes.Length); } public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count) { return UrlEncode(value, offset, count, true /* alwaysCreateNewReturnValue */); } #endregion #region UrlDecode implementation // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. // Changes done - Removed the logic to handle %Uxxxx as it is not standards compliant. private static string UrlDecodeInternal(string value, Encoding encoding) { if (value == null) { return null; } int count = value.Length; UrlDecoder helper = new UrlDecoder(count, encoding); // go through the string's chars collapsing %XX and // appending each char as char, with exception of %XX constructs // that are appended as bytes for (int pos = 0; pos < count; pos++) { char ch = value[pos]; if (ch == '+') { ch = ' '; } else if (ch == '%' && pos < count - 2) { int h1 = HexToInt(value[pos + 1]); int h2 = HexToInt(value[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars byte b = (byte)((h1 << 4) | h2); pos += 2; // don't add as char helper.AddByte(b); continue; } } if ((ch & 0xFF80) == 0) helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode else helper.AddChar(ch); } return helper.GetString(); } private static byte[] UrlDecodeInternal(byte[] bytes, int offset, int count) { if (!ValidateUrlEncodingParameters(bytes, offset, count)) { return null; } int decodedBytesCount = 0; byte[] decodedBytes = new byte[count]; for (int i = 0; i < count; i++) { int pos = offset + i; byte b = bytes[pos]; if (b == '+') { b = (byte)' '; } else if (b == '%' && i < count - 2) { int h1 = HexToInt((char)bytes[pos + 1]); int h2 = HexToInt((char)bytes[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars b = (byte)((h1 << 4) | h2); i += 2; } } decodedBytes[decodedBytesCount++] = b; } if (decodedBytesCount < decodedBytes.Length) { Array.Resize(ref decodedBytes, decodedBytesCount); } return decodedBytes; } #endregion #region UrlDecode public methods [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Already shipped public API; code moved here as part of API consolidation")] public static string UrlDecode(string encodedValue) { if (encodedValue == null) return null; return UrlDecodeInternal(encodedValue, Encoding.UTF8); } public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count) { return UrlDecodeInternal(encodedValue, offset, count); } #endregion #region Helper methods // similar to Char.ConvertFromUtf32, but doesn't check arguments or generate strings // input is assumed to be an SMP character private static void ConvertSmpToUtf16(uint smpChar, out char leadingSurrogate, out char trailingSurrogate) { Debug.Assert(UNICODE_PLANE01_START <= smpChar && smpChar <= UNICODE_PLANE16_END); int utf32 = (int)(smpChar - UNICODE_PLANE01_START); leadingSurrogate = (char)((utf32 / 0x400) + HIGH_SURROGATE_START); trailingSurrogate = (char)((utf32 % 0x400) + LOW_SURROGATE_START); } private static unsafe int GetNextUnicodeScalarValueFromUtf16Surrogate(ref char* pch, ref int charsRemaining) { // invariants Debug.Assert(charsRemaining >= 1); Debug.Assert(Char.IsSurrogate(*pch)); if (charsRemaining <= 1) { // not enough characters remaining to resurrect the original scalar value return UnicodeReplacementChar; } char leadingSurrogate = pch[0]; char trailingSurrogate = pch[1]; if (Char.IsSurrogatePair(leadingSurrogate, trailingSurrogate)) { // we're going to consume an extra char pch++; charsRemaining--; // below code is from Char.ConvertToUtf32, but without the checks (since we just performed them) return (((leadingSurrogate - HIGH_SURROGATE_START) * 0x400) + (trailingSurrogate - LOW_SURROGATE_START) + UNICODE_PLANE01_START); } else { // unmatched surrogate return UnicodeReplacementChar; } } private static int HexToInt(char h) { return (h >= '0' && h <= '9') ? h - '0' : (h >= 'a' && h <= 'f') ? h - 'a' + 10 : (h >= 'A' && h <= 'F') ? h - 'A' + 10 : -1; } private static char IntToHex(int n) { Debug.Assert(n < 0x10); if (n <= 9) return (char)(n + (int)'0'); else return (char)(n - 10 + (int)'A'); } // Set of safe chars, from RFC 1738.4 minus '+' private static bool IsUrlSafeChar(char ch) { if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') return true; switch (ch) { case '-': case '_': case '.': case '!': case '*': case '(': case ')': return true; } return false; } private static bool ValidateUrlEncodingParameters(byte[] bytes, int offset, int count) { if (bytes == null && count == 0) return false; if (bytes == null) { throw new ArgumentNullException("bytes"); } if (offset < 0 || offset > bytes.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || offset + count > bytes.Length) { throw new ArgumentOutOfRangeException("count"); } return true; } private static bool StringRequiresHtmlDecoding(string s) { if (s_htmlDecodeConformance == UnicodeDecodingConformance.Compat) { // this string requires html decoding only if it contains '&' return (s.IndexOf('&') >= 0); } else { // this string requires html decoding if it contains '&' or a surrogate character for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c == '&' || Char.IsSurrogate(c)) { return true; } } return false; } } #endregion #region UrlDecoder nested class // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. // Internal class to facilitate URL decoding -- keeps char buffer and byte buffer, allows appending of either chars or bytes private class UrlDecoder { private int _bufferSize; // Accumulate characters in a special array private int _numChars; private char[] _charBuffer; // Accumulate bytes for decoding into characters in a special array private int _numBytes; private byte[] _byteBuffer; // Encoding to convert chars to bytes private Encoding _encoding; private void FlushBytes() { if (_numBytes > 0) { _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; } } internal UrlDecoder(int bufferSize, Encoding encoding) { _bufferSize = bufferSize; _encoding = encoding; _charBuffer = new char[bufferSize]; // byte buffer created on demand } internal void AddChar(char ch) { if (_numBytes > 0) FlushBytes(); _charBuffer[_numChars++] = ch; } internal void AddByte(byte b) { if (_byteBuffer == null) _byteBuffer = new byte[_bufferSize]; _byteBuffer[_numBytes++] = b; } internal String GetString() { if (_numBytes > 0) FlushBytes(); if (_numChars > 0) return new String(_charBuffer, 0, _numChars); else return String.Empty; } } #endregion #region HtmlEntities nested class // helper class for lookup of HTML encoding entities private static class HtmlEntities { // The list is from http://www.w3.org/TR/REC-html40/sgml/entities.html, except for &apos;, which // is defined in http://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent. private static String[] s_entitiesList = new String[] { "\x0022-quot", "\x0026-amp", "\x0027-apos", "\x003c-lt", "\x003e-gt", "\x00a0-nbsp", "\x00a1-iexcl", "\x00a2-cent", "\x00a3-pound", "\x00a4-curren", "\x00a5-yen", "\x00a6-brvbar", "\x00a7-sect", "\x00a8-uml", "\x00a9-copy", "\x00aa-ordf", "\x00ab-laquo", "\x00ac-not", "\x00ad-shy", "\x00ae-reg", "\x00af-macr", "\x00b0-deg", "\x00b1-plusmn", "\x00b2-sup2", "\x00b3-sup3", "\x00b4-acute", "\x00b5-micro", "\x00b6-para", "\x00b7-middot", "\x00b8-cedil", "\x00b9-sup1", "\x00ba-ordm", "\x00bb-raquo", "\x00bc-frac14", "\x00bd-frac12", "\x00be-frac34", "\x00bf-iquest", "\x00c0-Agrave", "\x00c1-Aacute", "\x00c2-Acirc", "\x00c3-Atilde", "\x00c4-Auml", "\x00c5-Aring", "\x00c6-AElig", "\x00c7-Ccedil", "\x00c8-Egrave", "\x00c9-Eacute", "\x00ca-Ecirc", "\x00cb-Euml", "\x00cc-Igrave", "\x00cd-Iacute", "\x00ce-Icirc", "\x00cf-Iuml", "\x00d0-ETH", "\x00d1-Ntilde", "\x00d2-Ograve", "\x00d3-Oacute", "\x00d4-Ocirc", "\x00d5-Otilde", "\x00d6-Ouml", "\x00d7-times", "\x00d8-Oslash", "\x00d9-Ugrave", "\x00da-Uacute", "\x00db-Ucirc", "\x00dc-Uuml", "\x00dd-Yacute", "\x00de-THORN", "\x00df-szlig", "\x00e0-agrave", "\x00e1-aacute", "\x00e2-acirc", "\x00e3-atilde", "\x00e4-auml", "\x00e5-aring", "\x00e6-aelig", "\x00e7-ccedil", "\x00e8-egrave", "\x00e9-eacute", "\x00ea-ecirc", "\x00eb-euml", "\x00ec-igrave", "\x00ed-iacute", "\x00ee-icirc", "\x00ef-iuml", "\x00f0-eth", "\x00f1-ntilde", "\x00f2-ograve", "\x00f3-oacute", "\x00f4-ocirc", "\x00f5-otilde", "\x00f6-ouml", "\x00f7-divide", "\x00f8-oslash", "\x00f9-ugrave", "\x00fa-uacute", "\x00fb-ucirc", "\x00fc-uuml", "\x00fd-yacute", "\x00fe-thorn", "\x00ff-yuml", "\x0152-OElig", "\x0153-oelig", "\x0160-Scaron", "\x0161-scaron", "\x0178-Yuml", "\x0192-fnof", "\x02c6-circ", "\x02dc-tilde", "\x0391-Alpha", "\x0392-Beta", "\x0393-Gamma", "\x0394-Delta", "\x0395-Epsilon", "\x0396-Zeta", "\x0397-Eta", "\x0398-Theta", "\x0399-Iota", "\x039a-Kappa", "\x039b-Lambda", "\x039c-Mu", "\x039d-Nu", "\x039e-Xi", "\x039f-Omicron", "\x03a0-Pi", "\x03a1-Rho", "\x03a3-Sigma", "\x03a4-Tau", "\x03a5-Upsilon", "\x03a6-Phi", "\x03a7-Chi", "\x03a8-Psi", "\x03a9-Omega", "\x03b1-alpha", "\x03b2-beta", "\x03b3-gamma", "\x03b4-delta", "\x03b5-epsilon", "\x03b6-zeta", "\x03b7-eta", "\x03b8-theta", "\x03b9-iota", "\x03ba-kappa", "\x03bb-lambda", "\x03bc-mu", "\x03bd-nu", "\x03be-xi", "\x03bf-omicron", "\x03c0-pi", "\x03c1-rho", "\x03c2-sigmaf", "\x03c3-sigma", "\x03c4-tau", "\x03c5-upsilon", "\x03c6-phi", "\x03c7-chi", "\x03c8-psi", "\x03c9-omega", "\x03d1-thetasym", "\x03d2-upsih", "\x03d6-piv", "\x2002-ensp", "\x2003-emsp", "\x2009-thinsp", "\x200c-zwnj", "\x200d-zwj", "\x200e-lrm", "\x200f-rlm", "\x2013-ndash", "\x2014-mdash", "\x2018-lsquo", "\x2019-rsquo", "\x201a-sbquo", "\x201c-ldquo", "\x201d-rdquo", "\x201e-bdquo", "\x2020-dagger", "\x2021-Dagger", "\x2022-bull", "\x2026-hellip", "\x2030-permil", "\x2032-prime", "\x2033-Prime", "\x2039-lsaquo", "\x203a-rsaquo", "\x203e-oline", "\x2044-frasl", "\x20ac-euro", "\x2111-image", "\x2118-weierp", "\x211c-real", "\x2122-trade", "\x2135-alefsym", "\x2190-larr", "\x2191-uarr", "\x2192-rarr", "\x2193-darr", "\x2194-harr", "\x21b5-crarr", "\x21d0-lArr", "\x21d1-uArr", "\x21d2-rArr", "\x21d3-dArr", "\x21d4-hArr", "\x2200-forall", "\x2202-part", "\x2203-exist", "\x2205-empty", "\x2207-nabla", "\x2208-isin", "\x2209-notin", "\x220b-ni", "\x220f-prod", "\x2211-sum", "\x2212-minus", "\x2217-lowast", "\x221a-radic", "\x221d-prop", "\x221e-infin", "\x2220-ang", "\x2227-and", "\x2228-or", "\x2229-cap", "\x222a-cup", "\x222b-int", "\x2234-there4", "\x223c-sim", "\x2245-cong", "\x2248-asymp", "\x2260-ne", "\x2261-equiv", "\x2264-le", "\x2265-ge", "\x2282-sub", "\x2283-sup", "\x2284-nsub", "\x2286-sube", "\x2287-supe", "\x2295-oplus", "\x2297-otimes", "\x22a5-perp", "\x22c5-sdot", "\x2308-lceil", "\x2309-rceil", "\x230a-lfloor", "\x230b-rfloor", "\x2329-lang", "\x232a-rang", "\x25ca-loz", "\x2660-spades", "\x2663-clubs", "\x2665-hearts", "\x2666-diams", }; private static LowLevelDictionary<string, char> s_lookupTable = GenerateLookupTable(); private static LowLevelDictionary<string, char> GenerateLookupTable() { // e[0] is unicode char, e[1] is '-', e[2+] is entity string LowLevelDictionary<string, char> lookupTable = new LowLevelDictionary<string, char>(StringComparer.Ordinal); foreach (string e in s_entitiesList) { lookupTable.Add(e.Substring(2), e[0]); } return lookupTable; } public static char Lookup(string entity) { char theChar; s_lookupTable.TryGetValue(entity, out theChar); return theChar; } } #endregion } }
using sly.buildresult; using sly.lexer; using Xunit; namespace ParserTests.comments { public enum CommentsToken { [Lexeme(GenericToken.Int)] INT, [Lexeme(GenericToken.Double)] DOUBLE, [Lexeme(GenericToken.Identifier)] ID, [Comment("//", "/*", "*/")] COMMENT } public class CommentsTestGeneric { [Fact] public void NotEndingMultiComment() { var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsToken>>()); Assert.False(lexerRes.IsError); var lexer = lexerRes.Result as GenericLexer<CommentsToken>; var dump = lexer.ToString(); var code = @"1 2 /* not ending comment"; var r = lexer.Tokenize(code); Assert.True(r.IsOk); var tokens = r.Tokens; Assert.Equal(4, tokens.Count); var token1 = tokens[0]; var token2 = tokens[1]; var token3 = tokens[2]; Assert.Equal(CommentsToken.INT, token1.TokenID); Assert.Equal("1", token1.Value); Assert.Equal(0, token1.Position.Line); Assert.Equal(0, token1.Position.Column); Assert.Equal(CommentsToken.INT, token2.TokenID); Assert.Equal("2", token2.Value); Assert.Equal(1, token2.Position.Line); Assert.Equal(0, token2.Position.Column); Assert.Equal(CommentsToken.COMMENT, token3.TokenID); Assert.Equal(@" not ending comment", token3.Value); Assert.Equal(1, token3.Position.Line); Assert.Equal(2, token3.Position.Column); } [Fact] public void TestGenericMultiLineComment() { var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsToken>>()); Assert.False(lexerRes.IsError); var lexer = lexerRes.Result as GenericLexer<CommentsToken>; var dump = lexer.ToString(); var code = @"1 2 /* multi line comment on 2 lines */ 3.0"; var r = lexer.Tokenize(code); Assert.True(r.IsOk); var tokens = r.Tokens; Assert.Equal(5, tokens.Count); var intToken1 = tokens[0]; var intToken2 = tokens[1]; var multiLineCommentToken = tokens[2]; var doubleToken = tokens[3]; Assert.Equal(CommentsToken.INT, intToken1.TokenID); Assert.Equal("1", intToken1.Value); Assert.Equal(0, intToken1.Position.Line); Assert.Equal(0, intToken1.Position.Column); Assert.Equal(CommentsToken.INT, intToken2.TokenID); Assert.Equal("2", intToken2.Value); Assert.Equal(1, intToken2.Position.Line); Assert.Equal(0, intToken2.Position.Column); Assert.Equal(CommentsToken.COMMENT, multiLineCommentToken.TokenID); Assert.Equal(@" multi line comment on 2 lines ", multiLineCommentToken.Value); Assert.Equal(1, multiLineCommentToken.Position.Line); Assert.Equal(2, multiLineCommentToken.Position.Column); Assert.Equal(CommentsToken.DOUBLE, doubleToken.TokenID); Assert.Equal("3.0", doubleToken.Value); Assert.Equal(2, doubleToken.Position.Line); Assert.Equal(22, doubleToken.Position.Column); } [Fact] public void TestGenericSingleLineComment() { var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsToken>>()); Assert.False(lexerRes.IsError); var lexer = lexerRes.Result as GenericLexer<CommentsToken>; var dump = lexer.ToString(); var r = lexer.Tokenize(@"1 2 // single line comment 3.0"); Assert.True(r.IsOk); var tokens = r.Tokens; Assert.Equal(5, tokens.Count); var token1 = tokens[0]; var token2 = tokens[1]; var token3 = tokens[2]; var token4 = tokens[3]; Assert.Equal(CommentsToken.INT, token1.TokenID); Assert.Equal("1", token1.Value); Assert.Equal(0, token1.Position.Line); Assert.Equal(0, token1.Position.Column); Assert.Equal(CommentsToken.INT, token2.TokenID); Assert.Equal("2", token2.Value); Assert.Equal(1, token2.Position.Line); Assert.Equal(0, token2.Position.Column); Assert.Equal(CommentsToken.COMMENT, token3.TokenID); Assert.Equal(" single line comment", token3.Value.Replace("\r","").Replace("\n","")); Assert.Equal(1, token3.Position.Line); Assert.Equal(2, token3.Position.Column); Assert.Equal(CommentsToken.DOUBLE, token4.TokenID); Assert.Equal("3.0", token4.Value); Assert.Equal(2, token4.Position.Line); Assert.Equal(0, token4.Position.Column); } [Fact] public void TestInnerMultiComment() { var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsToken>>()); Assert.False(lexerRes.IsError); var lexer = lexerRes.Result as GenericLexer<CommentsToken>; var dump = lexer.ToString(); var code = @"1 2 /* inner */ 3 4 "; var r = lexer.Tokenize(code); Assert.True(r.IsOk); var tokens = r.Tokens; Assert.Equal(6, tokens.Count); var token1 = tokens[0]; var token2 = tokens[1]; var token3 = tokens[2]; var token4 = tokens[3]; var token5 = tokens[4]; Assert.Equal(CommentsToken.INT, token1.TokenID); Assert.Equal("1", token1.Value); Assert.Equal(0, token1.Position.Line); Assert.Equal(0, token1.Position.Column); Assert.Equal(CommentsToken.INT, token2.TokenID); Assert.Equal("2", token2.Value); Assert.Equal(1, token2.Position.Line); Assert.Equal(0, token2.Position.Column); Assert.Equal(CommentsToken.COMMENT, token3.TokenID); Assert.Equal(@" inner ", token3.Value); Assert.Equal(1, token3.Position.Line); Assert.Equal(2, token3.Position.Column); Assert.Equal(CommentsToken.INT, token4.TokenID); Assert.Equal("3", token4.Value); Assert.Equal(1, token4.Position.Line); Assert.Equal(14, token4.Position.Column); Assert.Equal(CommentsToken.INT, token5.TokenID); Assert.Equal("4", token5.Value); Assert.Equal(2, token5.Position.Line); Assert.Equal(0, token5.Position.Column); } [Fact] public void TestMixedEOLComment() { var lexerRes = LexerBuilder.BuildLexer(new BuildResult<ILexer<CommentsToken>>()); Assert.False(lexerRes.IsError); var lexer = lexerRes.Result as GenericLexer<CommentsToken>; var dump = lexer.ToString(); var code = "1\n2\r\n/* multi line \rcomment on 2 lines */ 3.0"; var r = lexer.Tokenize(code); Assert.True(r.IsOk); var tokens = r.Tokens; Assert.Equal(5, tokens.Count); var token1 = tokens[0]; var token2 = tokens[1]; var token3 = tokens[2]; var token4 = tokens[3]; Assert.Equal(CommentsToken.INT, token1.TokenID); Assert.Equal("1", token1.Value); Assert.Equal(0, token1.Position.Line); Assert.Equal(0, token1.Position.Column); Assert.Equal(CommentsToken.INT, token2.TokenID); Assert.Equal("2", token2.Value); Assert.Equal(1, token2.Position.Line); Assert.Equal(0, token2.Position.Column); Assert.Equal(CommentsToken.COMMENT, token3.TokenID); Assert.Equal(" multi line \rcomment on 2 lines ", token3.Value); Assert.Equal(2, token3.Position.Line); Assert.Equal(0, token3.Position.Column); Assert.Equal(CommentsToken.DOUBLE, token4.TokenID); Assert.Equal("3.0", token4.Value); Assert.Equal(3, token4.Position.Line); Assert.Equal(22, token4.Position.Column); } } }
using System.Globalization; using System.Web.Mvc; using Candor.Configuration.Provider; using CandorMvcApplication.Models.Account; using Candor.Security; using Candor; using Candor.Web.Mvc; namespace CandorMvcApplication.Controllers { public partial class AccountController : Controller { // GET: /Account/Login [AllowAnonymous] public virtual ActionResult Login(string returnUrl) { var model = new LoginViewModel(); ViewBag.ReturnUrl = returnUrl; return View(model); } // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public virtual ActionResult Login(LoginViewModel model, string returnUrl) { if (ModelState.IsValid) { var result = new ExecutionResults(); var id = UserManager.AuthenticateUser(model.UserName, model.Password, model.RememberMe ? UserSessionDurationType.Extended : UserSessionDurationType.PublicComputer, Request.UserHostAddress, result); if (id.IsAuthenticated && result.Success) { //login successful SecurityContextManager.CurrentUser = new UserPrincipal(id); return RedirectToLocal(returnUrl); } //failed business layer validations for (var e = result.Messages.Count - 1; e >= 0; e--) { ModelState.AddModelError(e.ToString(CultureInfo.InvariantCulture), result.Messages[e].Message); } } // failed data annotation validations return View(model); } // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public virtual ActionResult LogOff() { SecurityContextManager.CurrentUser = new UserPrincipal(); //anonymous return RedirectToAction(MVC.Home.Index()); } // GET: /Account/Register [AllowAnonymous] public virtual ActionResult Register() { var model = new RegisterViewModel(); model.Load(); return View(model); } [AcceptVerbs(HttpVerbs.Post)] public virtual ActionResult CheckAliasIsAvailable(string alias) { if (alias == SecurityContextManager.CurrentIdentity.Name) return Json(new { success = true, message = "This is your current sign in alias." }); var result = new ExecutionResults(); if (!UserManager.ValidateName(alias, result)) return Json(new { success = false, message = result.ToHtmlString() }); var user = UserManager.GetUserByName(alias); return Json(new { success = (user == null), message = (User == null) ? "This name is available" : "This name is not available. Choose another name." }); } // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public virtual ActionResult Register(RegisterViewModel model, string returnUrl) { if (ModelState.IsValid) { var results = new ExecutionResults(); var user = model.ToUser(); var identity = UserManager.RegisterUser(user, UserSessionDurationType.Extended, Request.UserHostAddress, results); if (results.Success) { //successful registration SecurityContextManager.CurrentUser = new UserPrincipal(identity); return RedirectToLocal(returnUrl); } //failed business layer results.AppendError("Failed to complete registration."); for (var e = 0; e < results.Messages.Count; e++) { ModelState.AddModelError(e.ToString(CultureInfo.InvariantCulture), results.Messages[e].Message); } } //failed data annotation validations model.Load(); return View(model); } // GET: /Account/ChangePassword public virtual ActionResult ChangePassword() { var model = new ChangePasswordViewModel { UserName = SecurityContextManager.CurrentIdentity.Name }; return View(model); } // POST: /Account/ChangePassword [HttpPost] public virtual ActionResult ChangePassword(ChangePasswordViewModel model) { if (ModelState.IsValid) { var result = new ExecutionResults(); var user = new User { UserID = SecurityContextManager.CurrentIdentity.Ticket.UserSession.UserID, Name = model.UserName, PasswordHash = model.ConfirmPassword }; if (UserManager.UpdateUser(user, model.OldPassword, Request.UserHostAddress, result)) { //success if (this.IsJsonRequest()) return Json(new { success = true }); return RedirectToAction(MVC.Account.ChangePasswordSuccess()); } //failed business layer rules if (this.IsJsonRequest()) return Json(new { success = false, message = result.ToHtmlString() }); for (int e = 0; e < result.Messages.Count; e++) { ModelState.AddModelError(e.ToString(CultureInfo.InvariantCulture), result.Messages[e].Message); } return View(model); } if (this.IsJsonRequest()) return Json(new { success = false, errors = ModelState.ToJson() }); return View(model); //modelstate already populated } // GET: /Account/ChangePasswordSuccess public virtual ActionResult ChangePasswordSuccess() { return View(); } // GET: /Account/ForgotPassword public virtual ActionResult ForgotPassword() { return View(); } [HttpPost] public virtual ActionResult ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var result = new ExecutionResults(); ProviderResolver<UserNotificationProvider>.Get.Provider.NotifyPasswordReset(model.UserName, result); if (this.IsJsonRequest()) return Json(new { success = result.Success, message = result.ToHtmlString() }); if (result.Success) return RedirectToAction(MVC.Account.Login()); for (var e = 0; e < result.Messages.Count; e++) { ModelState.AddModelError(e.ToString(CultureInfo.InvariantCulture), result.Messages[e].Message); } return View(model); } if (this.IsJsonRequest()) return Json(new { success = false, errors = ModelState.ToJson() }); return View(model); //modelstate already populated } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) return Redirect(returnUrl); //redirect to the main landing page for an authenticated user return RedirectToAction(MVC.Home.Index()); } } }
using System; using System.Text; using System.Collections.Generic; using System.Threading.Tasks; #if __UNIFIED__ using UIKit; using Foundation; using AVFoundation; using CoreGraphics; #else using MonoTouch.UIKit; using MonoTouch.Foundation; using MonoTouch.AVFoundation; using MonoTouch.CoreGraphics; using System.Drawing; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif using ZXing; namespace ZXing.Mobile { public class ZXingScannerViewController : UIViewController, IScannerViewController { ZXingScannerView scannerView; public event Action<ZXing.Result> OnScannedResult; public MobileBarcodeScanningOptions ScanningOptions { get;set; } public MobileBarcodeScanner Scanner { get;set; } public bool ContinuousScanning { get;set; } UIActivityIndicatorView loadingView; UIView loadingBg; public UIView CustomLoadingView { get; set; } public ZXingScannerViewController(MobileBarcodeScanningOptions options, MobileBarcodeScanner scanner) { this.ScanningOptions = options; this.Scanner = scanner; var appFrame = UIScreen.MainScreen.ApplicationFrame; this.View.Frame = new CGRect(0, 0, appFrame.Width, appFrame.Height); this.View.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; } public UIViewController AsViewController() { return this; } public void Cancel() { this.InvokeOnMainThread (scannerView.StopScanning); } UIStatusBarStyle originalStatusBarStyle = UIStatusBarStyle.Default; public override void ViewDidLoad () { loadingBg = new UIView (this.View.Frame) { BackgroundColor = UIColor.Black, AutoresizingMask = UIViewAutoresizing.FlexibleDimensions }; loadingView = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.WhiteLarge) { AutoresizingMask = UIViewAutoresizing.FlexibleMargins }; loadingView.Frame = new CGRect ((this.View.Frame.Width - loadingView.Frame.Width) / 2, (this.View.Frame.Height - loadingView.Frame.Height) / 2, loadingView.Frame.Width, loadingView.Frame.Height); loadingBg.AddSubview (loadingView); View.AddSubview (loadingBg); loadingView.StartAnimating (); scannerView = new ZXingScannerView(new CGRect(0, 0, View.Frame.Width, View.Frame.Height)); scannerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; scannerView.UseCustomOverlayView = this.Scanner.UseCustomOverlay; scannerView.CustomOverlayView = this.Scanner.CustomOverlay; scannerView.TopText = this.Scanner.TopText; scannerView.BottomText = this.Scanner.BottomText; scannerView.CancelButtonText = this.Scanner.CancelButtonText; scannerView.FlashButtonText = this.Scanner.FlashButtonText; scannerView.OnCancelButtonPressed += delegate { Scanner.Cancel (); }; //this.View.AddSubview(scannerView); this.View.InsertSubviewBelow (scannerView, loadingView); this.View.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; } public void Torch(bool on) { if (scannerView != null) scannerView.Torch (on); } public void ToggleTorch() { if (scannerView != null) scannerView.ToggleTorch (); } public void PauseAnalysis () { scannerView.PauseAnalysis (); } public void ResumeAnalysis () { scannerView.ResumeAnalysis (); } public bool IsTorchOn { get { return scannerView.IsTorchOn; } } public override void ViewDidAppear (bool animated) { scannerView.OnScannerSetupComplete += HandleOnScannerSetupComplete; originalStatusBarStyle = UIApplication.SharedApplication.StatusBarStyle; if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) { UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.Default; SetNeedsStatusBarAppearanceUpdate (); } else UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.BlackTranslucent, false); Console.WriteLine("Starting to scan..."); Task.Factory.StartNew (() => { BeginInvokeOnMainThread(() => scannerView.StartScanning (result => { if (!ContinuousScanning) { Console.WriteLine ("Stopping scan..."); scannerView.StopScanning (); } var evt = this.OnScannedResult; if (evt != null) evt (result); },this.ScanningOptions)); }); } public override void ViewDidDisappear (bool animated) { if (scannerView != null) scannerView.StopScanning(); scannerView.OnScannerSetupComplete -= HandleOnScannerSetupComplete; } public override void ViewWillDisappear(bool animated) { UIApplication.SharedApplication.SetStatusBarStyle(originalStatusBarStyle, false); } public override void DidRotate (UIInterfaceOrientation fromInterfaceOrientation) { if (scannerView != null) scannerView.DidRotate (this.InterfaceOrientation); //overlayView.LayoutSubviews(); } public override bool ShouldAutorotate () { return true; } public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations () { return UIInterfaceOrientationMask.All; } [Obsolete ("Deprecated in iOS6. Replace it with both GetSupportedInterfaceOrientations and PreferredInterfaceOrientationForPresentation")] public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { return true; } void HandleOnScannerSetupComplete () { BeginInvokeOnMainThread (() => { if (loadingView != null && loadingBg != null && loadingView.IsAnimating) { loadingView.StopAnimating (); UIView.BeginAnimations("zoomout"); UIView.SetAnimationDuration(2.0f); UIView.SetAnimationCurve(UIViewAnimationCurve.EaseOut); loadingBg.Transform = CGAffineTransform.MakeScale(2.0f, 2.0f); loadingBg.Alpha = 0.0f; UIView.CommitAnimations(); loadingBg.RemoveFromSuperview(); } }); } } }
// Copyright (C) 2014 dot42 // // Original filename: FormatHelper.cs // // 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.Globalization; using System.Text; namespace Dot42.Internal { internal sealed class FormatHelper { private readonly StringBuilder result; private readonly IFormatProvider provider; private readonly string format; private readonly int numberOfArguments; private int ptr; int n, width; bool left_align; string arg_format; private readonly object[] args; private readonly object arg0, arg1, arg2; internal FormatHelper(StringBuilder result, IFormatProvider provider, string format, object[] args) { if (format == null) throw new ArgumentNullException("format"); if (args == null) throw new ArgumentNullException("args"); this.result = result; this.provider = provider; this.format = format; this.args = args; this.numberOfArguments = args.Length; if (result == null) { // Try to approximate the size of result to avoid reallocations int i, len; len = 0; var argLength = args.Length; for (i = 0; i < argLength; ++i) { string s = GetArg(i) as string; if (s != null) len += s.Length; else break; } this.result = new StringBuilder(len + format.Length); } } internal FormatHelper(StringBuilder result, IFormatProvider provider, string format, object arg0) { if (format == null) throw new ArgumentNullException("format"); this.result = result; this.provider = provider; this.format = format; this.arg0 = arg0; this.numberOfArguments = 1 ; if (result == null) { // Try to approximate the size of result to avoid reallocations int len = format.Length; if (arg0 is string) len += ((string) arg0).Length; this.result = new StringBuilder(len + format.Length); } } internal FormatHelper(StringBuilder result, IFormatProvider provider, string format, object arg0, object arg1) { if (format == null) throw new ArgumentNullException("format"); this.result = result; this.provider = provider; this.format = format; this.arg0 = arg0; this.arg1 = arg1; this.numberOfArguments = 2; if (result == null) { // Try to approximate the size of result to avoid reallocations int len = format.Length; if (arg0 is string) len += ((string)arg0).Length; if (arg1 is string) len += ((string)arg1).Length; this.result = new StringBuilder(len + format.Length); } } internal FormatHelper(StringBuilder result, IFormatProvider provider, string format, object arg0, object arg1, object arg2) { if (format == null) throw new ArgumentNullException("format"); this.result = result; this.provider = provider; this.format = format; this.arg0 = arg0; this.arg1 = arg1; this.arg2 = arg2; this.numberOfArguments = 3; if (result == null) { // Try to approximate the size of result to avoid reallocations int len = format.Length; if (arg0 is string) len += ((string)arg0).Length; if (arg1 is string) len += ((string)arg1).Length; if (arg2 is string) len += ((string)arg2).Length; this.result = new StringBuilder(len + format.Length); } } [Inline] public object GetArg(int idx) { if (args != null) return args[idx]; return idx == 0 ? arg0 : idx == 1 ? arg1 : arg2 ; } /// <summary> /// Perform the actual formatting. /// </summary> internal StringBuilder Format() { ptr = 0; int start = ptr; var formatter = provider != null ? provider.GetFormat(typeof(ICustomFormatter)) as ICustomFormatter : null; var formatLength = format.Length; while (ptr < formatLength) { char c = format[ptr++]; if (c == '{') { result.Append(format, start, ptr - start - 1); // check for escaped open bracket if (format[ptr] == '{') { start = ptr++; continue; } // parse specifier ParseFormatSpecifier(format); if (n >= numberOfArguments) throw new FormatException("Index (zero based) must be greater than or equal to zero and less than the size of the argument list."); // format argument object arg = GetArg(n); string str; if (arg == null) { str = string.Empty; } else if (formatter != null) { str = formatter.Format(arg_format, arg, provider); } else { if (provider == null) { // take the allocation reducing shortcut. str = CultureInfo.DefaultCustomFormatter.Format(arg_format, arg, provider); } else { var formattable = arg as IFormattable; str = formattable != null ? formattable.ToString(arg_format, provider) : arg.ToString(); } } if (str == null) { str = String.Empty; } // pad formatted string and append to result if (width > str.Length) { const char padchar = ' '; int padlen = width - str.Length; if (left_align) { result.Append(str); result.Append(padchar, padlen); } else { result.Append(padchar, padlen); result.Append(str); } } else { result.Append(str); } start = ptr; } else if (c == '}' && ptr < format.Length && format[ptr] == '}') { result.Append(format, start, ptr - start - 1); start = ptr++; } else if (c == '}') { throw new FormatException("Input string was not in a correct format."); } } if (start < formatLength) result.Append(format, start, format.Length - start); return result; } private void ParseFormatSpecifier(string str) { int max = str.Length; // parses format specifier of form: // N,[\ +[-]M][:F]} // // where: // N = argument number (non-negative integer) n = ParseDecimal(str); if (n < 0) throw new FormatException("Input string was not in a correct format."); // M = width (non-negative integer) if (ptr < max && str[ptr] == ',') { // White space between ',' and number or sign. ++ptr; while (ptr < max && Char.IsWhiteSpace(str[ptr])) ++ptr; int start = ptr; arg_format = str.Substring(start, ptr - start); left_align = (ptr < max && str[ptr] == '-'); if (left_align) ++ptr; width = ParseDecimal(str); if (width < 0) throw new FormatException("Input string was not in a correct format."); } else { width = 0; left_align = false; arg_format = string.Empty; } // F = argument format (string) if (ptr < max && str[ptr] == ':') { int start = ++ptr; while (ptr < max && str[ptr] != '}') ++ptr; arg_format += str.Substring(start, ptr - start); } else arg_format = null; if ((ptr >= max) || str[ptr++] != '}') throw new FormatException("Input string was not in a correct format."); } private int ParseDecimal(string str) { int p = ptr; int n = 0; int max = str.Length; while (p < max) { char c = str[p]; if (c < '0' || '9' < c) break; n = n * 10 + c - '0'; ++p; } if (p == ptr || p == max) return -1; ptr = p; return n; } internal static int ParseDecimal(string str, int startIndex, int notIncludedEndIndex) { if (startIndex == notIncludedEndIndex) return -1; int n = 0; while (startIndex < notIncludedEndIndex) { char c = str[startIndex]; if (c < '0' || c > '9') return -1; n = n * 10 + c - '0'; ++startIndex; } return n; } internal static void Append(StringBuilder sb, int number, int minDigits) { switch (minDigits) { case 0: case 1: break; case 2: if (number < 10) goto pad1; break; case 3: if (number < 10) goto pad2; if (number < 100) goto pad1; break; case 4: if (number < 10) goto pad3; if (number < 100) goto pad2; if (number < 1000) goto pad1; break; case 5: if (number < 10) goto pad4; if (number < 100) goto pad3; if (number < 1000) goto pad2; if (number < 10000) goto pad1; break; case 6: if (number < 10) goto pad5; if (number < 100) goto pad4; if (number < 1000) goto pad3; if (number < 10000) goto pad2; if (number < 100000) goto pad1; break; case 7: if (number < 10) goto pad6; if (number < 100) goto pad5; if (number < 1000) goto pad4; if (number < 10000) goto pad3; if (number < 100000) goto pad2; if (number < 1000000) goto pad1; break; default: // fallback: append number first int sbLength = sb.Length; sb.Append(number); int numDigits = sb.Length - sbLength; // now insert padding zeroes, if required. int add = minDigits - numDigits; if (add > 0) { string zeros = new string('0', add); sb.Insert(sbLength, zeros); } return; } sb.Append(number); return; pad1: sb.Append('0'); sb.Append(number); return; pad2: sb.Append("00"); sb.Append(number); return; pad3: sb.Append("000"); sb.Append(number); return; pad4: sb.Append("0000"); sb.Append(number); return; pad5: sb.Append("00000"); sb.Append(number); return; pad6: sb.Append("000000"); sb.Append(number); return; //pad7: //sb.Append("0000000"); //sb.Append(number); //return; } } }
#pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective #region Using using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; #endregion // ReSharper disable StringLiteralTypo // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer // ReSharper disable InvalidXmlDocComment // ReSharper disable CommentTypo namespace OpenGL { public partial class Gl { /// <summary> /// [GL] Value of GL_PIXEL_PACK_BUFFER symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_ARB_pixel_buffer_object", Api = "gl|glcore")] [RequiredByFeature("GL_EXT_pixel_buffer_object")] [RequiredByFeature("GL_NV_pixel_buffer_object", Api = "gles2")] public const int PIXEL_PACK_BUFFER = 0x88EB; /// <summary> /// [GL] Value of GL_PIXEL_UNPACK_BUFFER symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_ARB_pixel_buffer_object", Api = "gl|glcore")] [RequiredByFeature("GL_EXT_pixel_buffer_object")] [RequiredByFeature("GL_NV_pixel_buffer_object", Api = "gles2")] public const int PIXEL_UNPACK_BUFFER = 0x88EC; /// <summary> /// [GL4|GLES3.2] Gl.Get: data returns a single value, the name of the buffer object currently bound to the target /// Gl.PIXEL_PACK_BUFFER. If no buffer object is bound to this target, 0 is returned. The initial value is 0. See /// Gl.BindBuffer. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_ARB_pixel_buffer_object", Api = "gl|glcore")] [RequiredByFeature("GL_EXT_pixel_buffer_object")] [RequiredByFeature("GL_NV_pixel_buffer_object", Api = "gles2")] public const int PIXEL_PACK_BUFFER_BINDING = 0x88ED; /// <summary> /// [GL4|GLES3.2] Gl.Get: data returns a single value, the name of the buffer object currently bound to the target /// Gl.PIXEL_UNPACK_BUFFER. If no buffer object is bound to this target, 0 is returned. The initial value is 0. See /// Gl.BindBuffer. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_ARB_pixel_buffer_object", Api = "gl|glcore")] [RequiredByFeature("GL_EXT_pixel_buffer_object")] [RequiredByFeature("GL_NV_pixel_buffer_object", Api = "gles2")] public const int PIXEL_UNPACK_BUFFER_BINDING = 0x88EF; /// <summary> /// [GL] Value of GL_FLOAT_MAT2x3 symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public const int FLOAT_MAT2x3 = 0x8B65; /// <summary> /// [GL] Value of GL_FLOAT_MAT2x4 symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public const int FLOAT_MAT2x4 = 0x8B66; /// <summary> /// [GL] Value of GL_FLOAT_MAT3x2 symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public const int FLOAT_MAT3x2 = 0x8B67; /// <summary> /// [GL] Value of GL_FLOAT_MAT3x4 symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public const int FLOAT_MAT3x4 = 0x8B68; /// <summary> /// [GL] Value of GL_FLOAT_MAT4x2 symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public const int FLOAT_MAT4x2 = 0x8B69; /// <summary> /// [GL] Value of GL_FLOAT_MAT4x3 symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public const int FLOAT_MAT4x3 = 0x8B6A; /// <summary> /// [GL] Value of GL_SRGB symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_EXT_sRGB", Api = "gles1|gles2")] [RequiredByFeature("GL_EXT_texture_sRGB")] public const int SRGB = 0x8C40; /// <summary> /// [GL] Value of GL_SRGB8 symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_EXT_texture_sRGB")] [RequiredByFeature("GL_NV_sRGB_formats", Api = "gles2")] public const int SRGB8 = 0x8C41; /// <summary> /// [GL] Value of GL_SRGB_ALPHA symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_EXT_sRGB", Api = "gles1|gles2")] [RequiredByFeature("GL_EXT_texture_sRGB")] public const int SRGB_ALPHA = 0x8C42; /// <summary> /// [GL] Value of GL_SRGB8_ALPHA8 symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_EXT_sRGB", Api = "gles1|gles2")] [RequiredByFeature("GL_EXT_texture_sRGB")] public const int SRGB8_ALPHA8 = 0x8C43; /// <summary> /// [GL] Value of GL_COMPRESSED_SRGB symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_EXT_texture_sRGB")] public const int COMPRESSED_SRGB = 0x8C48; /// <summary> /// [GL] Value of GL_COMPRESSED_SRGB_ALPHA symbol. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_EXT_texture_sRGB")] public const int COMPRESSED_SRGB_ALPHA = 0x8C49; /// <summary> /// [GL2.1] Gl.Get: params returns four values: the red, green, blue, and alpha secondary color values of the current /// raster /// position. Integer values, if requested, are linearly mapped from the internal floating-point representation such that /// 1.0 returns the most positive representable integer value, and -1.0 returns the most negative representable integer /// value. The initial value is (1, 1, 1, 1). See Gl.RasterPos. /// </summary> [RequiredByFeature("GL_VERSION_2_1")] [RemovedByFeature("GL_VERSION_3_2")] public const int CURRENT_RASTER_SECONDARY_COLOR = 0x845F; /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix2x3fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix2x3(int location, bool transpose, float[] value) { Debug.Assert(value.Length > 0 && value.Length % 6 == 0, "empty or not multiple of 6"); unsafe { fixed (float* p_value = value) { Debug.Assert(Delegates.pglUniformMatrix2x3fv != null, "pglUniformMatrix2x3fv not implemented"); Delegates.pglUniformMatrix2x3fv(location, value.Length / 6, transpose, p_value); } } DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix2x3fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static unsafe void UniformMatrix2x3(int location, int count, bool transpose, float* value) { Debug.Assert(Delegates.pglUniformMatrix2x3fv != null, "pglUniformMatrix2x3fv not implemented"); Delegates.pglUniformMatrix2x3fv(location, count, transpose, value); DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix2x3fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix2x3f<T>(int location, int count, bool transpose, T value) where T : struct { Debug.Assert(Delegates.pglUniformMatrix2x3fv != null, "pglUniformMatrix2x3fv not implemented"); #if NETCOREAPP1_1 GCHandle valueHandle = GCHandle.Alloc(value); try { unsafe { Delegates.pglUniformMatrix2x3fv(location, count, transpose, (float*)valueHandle.AddrOfPinnedObject().ToPointer()); } } finally { valueHandle.Free(); } #else unsafe { TypedReference refValue = __makeref(value); IntPtr refValuePtr = *(IntPtr*) (&refValue); Delegates.pglUniformMatrix2x3fv(location, count, transpose, (float*) refValuePtr.ToPointer()); } #endif DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix3x2fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix3x2(int location, bool transpose, float[] value) { Debug.Assert(value.Length > 0 && value.Length % 6 == 0, "empty or not multiple of 6"); unsafe { fixed (float* p_value = value) { Debug.Assert(Delegates.pglUniformMatrix3x2fv != null, "pglUniformMatrix3x2fv not implemented"); Delegates.pglUniformMatrix3x2fv(location, value.Length / 6, transpose, p_value); } } DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix3x2fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static unsafe void UniformMatrix3x2(int location, int count, bool transpose, float* value) { Debug.Assert(Delegates.pglUniformMatrix3x2fv != null, "pglUniformMatrix3x2fv not implemented"); Delegates.pglUniformMatrix3x2fv(location, count, transpose, value); DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix3x2fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix3x2f<T>(int location, int count, bool transpose, T value) where T : struct { Debug.Assert(Delegates.pglUniformMatrix3x2fv != null, "pglUniformMatrix3x2fv not implemented"); #if NETCOREAPP1_1 GCHandle valueHandle = GCHandle.Alloc(value); try { unsafe { Delegates.pglUniformMatrix3x2fv(location, count, transpose, (float*)valueHandle.AddrOfPinnedObject().ToPointer()); } } finally { valueHandle.Free(); } #else unsafe { TypedReference refValue = __makeref(value); IntPtr refValuePtr = *(IntPtr*) (&refValue); Delegates.pglUniformMatrix3x2fv(location, count, transpose, (float*) refValuePtr.ToPointer()); } #endif DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix2x4fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix2x4(int location, bool transpose, float[] value) { Debug.Assert(value.Length > 0 && value.Length % 8 == 0, "empty or not multiple of 8"); unsafe { fixed (float* p_value = value) { Debug.Assert(Delegates.pglUniformMatrix2x4fv != null, "pglUniformMatrix2x4fv not implemented"); Delegates.pglUniformMatrix2x4fv(location, value.Length / 8, transpose, p_value); } } DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix2x4fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static unsafe void UniformMatrix2x4(int location, int count, bool transpose, float* value) { Debug.Assert(Delegates.pglUniformMatrix2x4fv != null, "pglUniformMatrix2x4fv not implemented"); Delegates.pglUniformMatrix2x4fv(location, count, transpose, value); DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix2x4fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix2x4f<T>(int location, int count, bool transpose, T value) where T : struct { Debug.Assert(Delegates.pglUniformMatrix2x4fv != null, "pglUniformMatrix2x4fv not implemented"); #if NETCOREAPP1_1 GCHandle valueHandle = GCHandle.Alloc(value); try { unsafe { Delegates.pglUniformMatrix2x4fv(location, count, transpose, (float*)valueHandle.AddrOfPinnedObject().ToPointer()); } } finally { valueHandle.Free(); } #else unsafe { TypedReference refValue = __makeref(value); IntPtr refValuePtr = *(IntPtr*) (&refValue); Delegates.pglUniformMatrix2x4fv(location, count, transpose, (float*) refValuePtr.ToPointer()); } #endif DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix4x2fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix4x2(int location, bool transpose, float[] value) { Debug.Assert(value.Length > 0 && value.Length % 8 == 0, "empty or not multiple of 8"); unsafe { fixed (float* p_value = value) { Debug.Assert(Delegates.pglUniformMatrix4x2fv != null, "pglUniformMatrix4x2fv not implemented"); Delegates.pglUniformMatrix4x2fv(location, value.Length / 8, transpose, p_value); } } DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix4x2fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static unsafe void UniformMatrix4x2(int location, int count, bool transpose, float* value) { Debug.Assert(Delegates.pglUniformMatrix4x2fv != null, "pglUniformMatrix4x2fv not implemented"); Delegates.pglUniformMatrix4x2fv(location, count, transpose, value); DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix4x2fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix4x2f<T>(int location, int count, bool transpose, T value) where T : struct { Debug.Assert(Delegates.pglUniformMatrix4x2fv != null, "pglUniformMatrix4x2fv not implemented"); #if NETCOREAPP1_1 GCHandle valueHandle = GCHandle.Alloc(value); try { unsafe { Delegates.pglUniformMatrix4x2fv(location, count, transpose, (float*)valueHandle.AddrOfPinnedObject().ToPointer()); } } finally { valueHandle.Free(); } #else unsafe { TypedReference refValue = __makeref(value); IntPtr refValuePtr = *(IntPtr*) (&refValue); Delegates.pglUniformMatrix4x2fv(location, count, transpose, (float*) refValuePtr.ToPointer()); } #endif DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix3x4fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix3x4(int location, bool transpose, float[] value) { Debug.Assert(value.Length > 0 && value.Length % 12 == 0, "empty or not multiple of 12"); unsafe { fixed (float* p_value = value) { Debug.Assert(Delegates.pglUniformMatrix3x4fv != null, "pglUniformMatrix3x4fv not implemented"); Delegates.pglUniformMatrix3x4fv(location, value.Length / 12, transpose, p_value); } } DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix3x4fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static unsafe void UniformMatrix3x4(int location, int count, bool transpose, float* value) { Debug.Assert(Delegates.pglUniformMatrix3x4fv != null, "pglUniformMatrix3x4fv not implemented"); Delegates.pglUniformMatrix3x4fv(location, count, transpose, value); DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix3x4fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix3x4f<T>(int location, int count, bool transpose, T value) where T : struct { Debug.Assert(Delegates.pglUniformMatrix3x4fv != null, "pglUniformMatrix3x4fv not implemented"); #if NETCOREAPP1_1 GCHandle valueHandle = GCHandle.Alloc(value); try { unsafe { Delegates.pglUniformMatrix3x4fv(location, count, transpose, (float*)valueHandle.AddrOfPinnedObject().ToPointer()); } } finally { valueHandle.Free(); } #else unsafe { TypedReference refValue = __makeref(value); IntPtr refValuePtr = *(IntPtr*) (&refValue); Delegates.pglUniformMatrix3x4fv(location, count, transpose, (float*) refValuePtr.ToPointer()); } #endif DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix4x3fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix4x3(int location, bool transpose, float[] value) { Debug.Assert(value.Length > 0 && value.Length % 12 == 0, "empty or not multiple of 12"); unsafe { fixed (float* p_value = value) { Debug.Assert(Delegates.pglUniformMatrix4x3fv != null, "pglUniformMatrix4x3fv not implemented"); Delegates.pglUniformMatrix4x3fv(location, value.Length / 12, transpose, p_value); } } DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix4x3fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static unsafe void UniformMatrix4x3(int location, int count, bool transpose, float* value) { Debug.Assert(Delegates.pglUniformMatrix4x3fv != null, "pglUniformMatrix4x3fv not implemented"); Delegates.pglUniformMatrix4x3fv(location, count, transpose, value); DebugCheckErrors(null); } /// <summary> /// <para> /// [GL4|GLES3.2] glUniformMatrix4x3fv: Specify the value of a uniform variable for the current program object /// </para> /// </summary> /// <param name="location"> /// Specifies the location of the uniform variable to be modified. /// </param> /// <param name="count"> /// For the vector (Gl.Uniform*v) commands, specifies the number of elements that are to be modified. This should be 1 if /// the targeted uniform variable is not an array, and 1 or more if it is an array. /// </param> /// <param name="transpose"> /// For the matrix commands, specifies whether to transpose the matrix as the values are loaded into the uniform variable. /// </param> /// <param name="value"> /// For the vector and matrix commands, specifies a pointer to an array of <paramref name="count" /> values that will be /// used /// to update the specified uniform variable. /// </param> [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] public static void UniformMatrix4x3f<T>(int location, int count, bool transpose, T value) where T : struct { Debug.Assert(Delegates.pglUniformMatrix4x3fv != null, "pglUniformMatrix4x3fv not implemented"); unsafe { TypedReference refValue = __makeref(value); IntPtr refValuePtr = *(IntPtr*) (&refValue); Delegates.pglUniformMatrix4x3fv(location, count, transpose, (float*) refValuePtr.ToPointer()); } DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glUniformMatrix2x3fv(int location, int count, [MarshalAs(UnmanagedType.I1)] bool transpose, float* value); [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2", EntryPoint = "glUniformMatrix2x3fvNV")] [ThreadStatic] internal static glUniformMatrix2x3fv pglUniformMatrix2x3fv; [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glUniformMatrix3x2fv(int location, int count, [MarshalAs(UnmanagedType.I1)] bool transpose, float* value); [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2", EntryPoint = "glUniformMatrix3x2fvNV")] [ThreadStatic] internal static glUniformMatrix3x2fv pglUniformMatrix3x2fv; [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glUniformMatrix2x4fv(int location, int count, [MarshalAs(UnmanagedType.I1)] bool transpose, float* value); [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2", EntryPoint = "glUniformMatrix2x4fvNV")] [ThreadStatic] internal static glUniformMatrix2x4fv pglUniformMatrix2x4fv; [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glUniformMatrix4x2fv(int location, int count, [MarshalAs(UnmanagedType.I1)] bool transpose, float* value); [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2", EntryPoint = "glUniformMatrix4x2fvNV")] [ThreadStatic] internal static glUniformMatrix4x2fv pglUniformMatrix4x2fv; [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glUniformMatrix3x4fv(int location, int count, [MarshalAs(UnmanagedType.I1)] bool transpose, float* value); [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2", EntryPoint = "glUniformMatrix3x4fvNV")] [ThreadStatic] internal static glUniformMatrix3x4fv pglUniformMatrix3x4fv; [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2")] [SuppressUnmanagedCodeSecurity] internal delegate void glUniformMatrix4x3fv(int location, int count, [MarshalAs(UnmanagedType.I1)] bool transpose, float* value); [RequiredByFeature("GL_VERSION_2_1")] [RequiredByFeature("GL_ES_VERSION_3_0", Api = "gles2")] [RequiredByFeature("GL_NV_non_square_matrices", Api = "gles2", EntryPoint = "glUniformMatrix4x3fvNV")] [ThreadStatic] internal static glUniformMatrix4x3fv pglUniformMatrix4x3fv; } } }
// 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. /*============================================================ ** ** ** ** ** ** Purpose: Searches for resources in Assembly manifest, used ** for assembly-based resource lookup. ** ** ===========================================================*/ namespace System.Resources { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Diagnostics.Contracts; using Microsoft.Win32; #if !FEATURE_CORECLR using System.Diagnostics.Tracing; #endif // // Note: this type is integral to the construction of exception objects, // and sometimes this has to be done in low memory situtations (OOM) or // to create TypeInitializationExceptions due to failure of a static class // constructor. This type needs to be extremely careful and assume that // any type it references may have previously failed to construct, so statics // belonging to that type may not be initialized. FrameworkEventSource.Log // is one such example. // internal class ManifestBasedResourceGroveler : IResourceGroveler { private ResourceManager.ResourceManagerMediator _mediator; public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator) { // here and below: convert asserts to preconditions where appropriate when we get // contracts story in place. Contract.Requires(mediator != null, "mediator shouldn't be null; check caller"); _mediator = mediator; } [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark) { Contract.Assert(culture != null, "culture shouldn't be null; check caller"); Contract.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller"); ResourceSet rs = null; Stream stream = null; RuntimeAssembly satellite = null; // 1. Fixups for ultimate fallbacks CultureInfo lookForCulture = UltimateFallbackFixup(culture); // 2. Look for satellite assembly or main assembly, as appropriate if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { // don't bother looking in satellites in this case satellite = _mediator.MainAssembly; } #if RESOURCE_SATELLITE_CONFIG // If our config file says the satellite isn't here, don't ask for it. else if (!lookForCulture.HasInvariantCultureName && !_mediator.TryLookingForSatellite(lookForCulture)) { satellite = null; } #endif else { satellite = GetSatelliteAssembly(lookForCulture, ref stackMark); if (satellite == null) { bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)); // didn't find satellite, give error if necessary if (raiseException) { HandleSatelliteMissing(); } } } // get resource file name we'll search for. Note, be careful if you're moving this statement // around because lookForCulture may be modified from originally requested culture above. String fileName = _mediator.GetResourceFileName(lookForCulture); // 3. If we identified an assembly to search; look in manifest resource stream for resource file if (satellite != null) { // Handle case in here where someone added a callback for assembly load events. // While no other threads have called into GetResourceSet, our own thread can! // At that point, we could already have an RS in our hash table, and we don't // want to add it twice. lock (localResourceSets) { if (localResourceSets.TryGetValue(culture.Name, out rs)) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCacheUnexpected(_mediator.BaseName, _mediator.MainAssembly, culture.Name); } #endif } } stream = GetManifestResourceStream(satellite, fileName, ref stackMark); } #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { if (stream != null) { FrameworkEventSource.Log.ResourceManagerStreamFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName); } else { FrameworkEventSource.Log.ResourceManagerStreamNotFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName); } } #endif // 4a. Found a stream; create a ResourceSet if possible if (createIfNotExists && stream != null && rs == null) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name, fileName); } #endif rs = CreateResourceSet(stream, satellite); } else if (stream == null && tryParents) { // 4b. Didn't find stream; give error if necessary bool raiseException = culture.HasInvariantCultureName; if (raiseException) { HandleResourceStreamMissing(fileName); } } #if !FEATURE_CORECLR if (!createIfNotExists && stream != null && rs == null) { if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerNotCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name); } } #endif return rs; } #if !FEATURE_CORECLR // Returns whether or not the main assembly contains a particular resource // file in it's assembly manifest. Used to verify that the neutral // Culture's .resources file is present in the main assembly public bool HasNeutralResources(CultureInfo culture, String defaultResName) { String resName = defaultResName; if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null) resName = _mediator.LocationInfo.Namespace + Type.Delimiter + defaultResName; String[] resourceFiles = _mediator.MainAssembly.GetManifestResourceNames(); foreach(String s in resourceFiles) if (s.Equals(resName)) return true; return false; } #endif private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture) { CultureInfo returnCulture = lookForCulture; // If our neutral resources were written in this culture AND we know the main assembly // does NOT contain neutral resources, don't probe for this satellite. if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerNeutralResourcesSufficient(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name); } #endif returnCulture = CultureInfo.InvariantCulture; } else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite) { returnCulture = _mediator.NeutralResourcesCulture; } return returnCulture; } [System.Security.SecurityCritical] internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation) { Contract.Assert(a != null, "assembly != null"); string cultureName = null; short fallback = 0; if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref cultureName), out fallback)) { if ((UltimateResourceFallbackLocation)fallback < UltimateResourceFallbackLocation.MainAssembly || (UltimateResourceFallbackLocation)fallback > UltimateResourceFallbackLocation.Satellite) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc", fallback)); } fallbackLocation = (UltimateResourceFallbackLocation)fallback; } else { #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerNeutralResourceAttributeMissing(a); } #endif fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; return CultureInfo.InvariantCulture; } try { CultureInfo c = CultureInfo.GetCultureInfo(cultureName); return c; } catch (ArgumentException e) { // we should catch ArgumentException only. // Note we could go into infinite loops if mscorlib's // NeutralResourcesLanguageAttribute is mangled. If this assert // fires, please fix the build process for the BCL directory. if (a == typeof(Object).Assembly) { Contract.Assert(false, System.CoreLib.Name+"'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e); return CultureInfo.InvariantCulture; } throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_Asm_Culture", a.ToString(), cultureName), e); } } // Constructs a new ResourceSet for a given file name. The logic in // here avoids a ReflectionPermission check for our RuntimeResourceSet // for perf and working set reasons. // Use the assembly to resolve assembly manifest resource references. // Note that is can be null, but probably shouldn't be. // This method could use some refactoring. One thing at a time. [System.Security.SecurityCritical] internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) { Contract.Assert(store != null, "I need a Stream!"); // Check to see if this is a Stream the ResourceManager understands, // and check for the correct resource reader type. if (store.CanSeek && store.Length > 4) { long startPos = store.Position; // not disposing because we want to leave stream open BinaryReader br = new BinaryReader(store); // Look for our magic number as a little endian Int32. int bytes = br.ReadInt32(); if (bytes == ResourceManager.MagicNumber) { int resMgrHeaderVersion = br.ReadInt32(); String readerTypeName = null, resSetTypeName = null; if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber) { br.ReadInt32(); // We don't want the number of bytes to skip. readerTypeName = System.CoreLib.FixupCoreLibName(br.ReadString()); resSetTypeName = System.CoreLib.FixupCoreLibName(br.ReadString()); } else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber) { // Assume that the future ResourceManager headers will // have two strings for us - the reader type name and // resource set type name. Read those, then use the num // bytes to skip field to correct our position. int numBytesToSkip = br.ReadInt32(); long endPosition = br.BaseStream.Position + numBytesToSkip; readerTypeName = System.CoreLib.FixupCoreLibName(br.ReadString()); resSetTypeName = System.CoreLib.FixupCoreLibName(br.ReadString()); br.BaseStream.Seek(endPosition, SeekOrigin.Begin); } else { // resMgrHeaderVersion is older than this ResMgr version. // We should add in backwards compatibility support here. throw new NotSupportedException(Environment.GetResourceString("NotSupported_ObsoleteResourcesFile", _mediator.MainAssembly.GetSimpleName())); } store.Position = startPos; // Perf optimization - Don't use Reflection for our defaults. // Note there are two different sets of strings here - the // assembly qualified strings emitted by ResourceWriter, and // the abbreviated ones emitted by InternalResGen. if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName)) { RuntimeResourceSet rs; #if LOOSELY_LINKED_RESOURCE_REFERENCE rs = new RuntimeResourceSet(store, assembly); #else rs = new RuntimeResourceSet(store); #endif // LOOSELY_LINKED_RESOURCE_REFERENCE return rs; } else { // we do not want to use partial binding here. Type readerType = Type.GetType(readerTypeName, true); Object[] args = new Object[1]; args[0] = store; IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args); Object[] resourceSetArgs = #if LOOSELY_LINKED_RESOURCE_REFERENCE new Object[2]; #else new Object[1]; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE resourceSetArgs[0] = reader; #if LOOSELY_LINKED_RESOURCE_REFERENCE resourceSetArgs[1] = assembly; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE Type resSetType; if (_mediator.UserResourceSet == null) { Contract.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here."); resSetType = Type.GetType(resSetTypeName, true, false); } else resSetType = _mediator.UserResourceSet; ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, resourceSetArgs, null, null); return rs; } } else { store.Position = startPos; } } if (_mediator.UserResourceSet == null) { // Explicitly avoid CreateInstance if possible, because it // requires ReflectionPermission to call private & protected // constructors. #if LOOSELY_LINKED_RESOURCE_REFERENCE return new RuntimeResourceSet(store, assembly); #else return new RuntimeResourceSet(store); #endif // LOOSELY_LINKED_RESOURCE_REFERENCE } else { Object[] args = new Object[2]; args[0] = store; args[1] = assembly; try { ResourceSet rs = null; // Add in a check for a constructor taking in an assembly first. try { rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); return rs; } catch (MissingMethodException) { } args = new Object[1]; args[0] = store; rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); #if LOOSELY_LINKED_RESOURCE_REFERENCE rs.Assembly = assembly; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE return rs; } catch (MissingMethodException e) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResMgrBadResSet_Type", _mediator.UserResourceSet.AssemblyQualifiedName), e); } } } [System.Security.SecurityCritical] private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileName, ref StackCrawlMark stackMark) { Contract.Requires(satellite != null, "satellite shouldn't be null; check caller"); Contract.Requires(fileName != null, "fileName shouldn't be null; check caller"); // If we're looking in the main assembly AND if the main assembly was the person who // created the ResourceManager, skip a security check for private manifest resources. bool canSkipSecurityCheck = (_mediator.MainAssembly == satellite) && (_mediator.CallingAssembly == _mediator.MainAssembly); Stream stream = satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName, canSkipSecurityCheck, ref stackMark); if (stream == null) { stream = CaseInsensitiveManifestResourceStreamLookup(satellite, fileName); } return stream; } // Looks up a .resources file in the assembly manifest using // case-insensitive lookup rules. Yes, this is slow. The metadata // dev lead refuses to make all assembly manifest resource lookups case-insensitive, // even optionally case-insensitive. [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name) { Contract.Requires(satellite != null, "satellite shouldn't be null; check caller"); Contract.Requires(name != null, "name shouldn't be null; check caller"); StringBuilder sb = new StringBuilder(); if (_mediator.LocationInfo != null) { String nameSpace = _mediator.LocationInfo.Namespace; if (nameSpace != null) { sb.Append(nameSpace); if (name != null) sb.Append(Type.Delimiter); } } sb.Append(name); String givenName = sb.ToString(); CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo; String canonicalName = null; foreach (String existingName in satellite.GetManifestResourceNames()) { if (comparer.Compare(existingName, givenName, CompareOptions.IgnoreCase) == 0) { if (canonicalName == null) { canonicalName = existingName; } else { throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_MultipleBlobs", givenName, satellite.ToString())); } } } #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { if (canonicalName != null) { FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName); } else { FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupFailed(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName); } } #endif if (canonicalName == null) { return null; } // If we're looking in the main assembly AND if the main // assembly was the person who created the ResourceManager, // skip a security check for private manifest resources. bool canSkipSecurityCheck = _mediator.MainAssembly == satellite && _mediator.CallingAssembly == _mediator.MainAssembly; StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; Stream s = satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck); // GetManifestResourceStream will return null if we don't have // permission to read this stream from the assembly. For example, // if the stream is private and we're trying to access it from another // assembly (ie, ResMgr in mscorlib accessing anything else), we // require Reflection TypeInformation permission to be able to read // this. #if !FEATURE_CORECLR if (s!=null) { if (FrameworkEventSource.IsInitialized) { FrameworkEventSource.Log.ResourceManagerManifestResourceAccessDenied(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), canonicalName); } } #endif return s; } [System.Security.SecurityCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark) { if (!_mediator.LookedForSatelliteContractVersion) { _mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly); _mediator.LookedForSatelliteContractVersion = true; } RuntimeAssembly satellite = null; String satAssemblyName = GetSatelliteAssemblyName(); // Look up the satellite assembly, but don't let problems // like a partially signed satellite assembly stop us from // doing fallback and displaying something to the user. // Yet also somehow log this error for a developer. try { satellite = _mediator.MainAssembly.InternalGetSatelliteAssembly(satAssemblyName, lookForCulture, _mediator.SatelliteContractVersion, false, ref stackMark); } // Jun 08: for cases other than ACCESS_DENIED, we'll assert instead of throw to give release builds more opportunity to fallback. catch (FileLoadException fle) { // Ignore cases where the loader gets an access // denied back from the OS. This showed up for // href-run exe's at one point. int hr = fle._HResult; if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED)) { Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle); } } // Don't throw for zero-length satellite assemblies, for compat with v1 catch (BadImageFormatException bife) { Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife); } #if !FEATURE_CORECLR if (FrameworkEventSource.IsInitialized) { if (satellite != null) { FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblySucceeded(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName); } else { FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblyFailed(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName); } } #endif return satellite; } // Perf optimization - Don't use Reflection for most cases with // our .resources files. This makes our code run faster and we can // creating a ResourceReader via Reflection. This would incur // a security check (since the link-time check on the constructor that // takes a String is turned into a full demand with a stack walk) // and causes partially trusted localized apps to fail. private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName) { Contract.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller"); Contract.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller"); if (_mediator.UserResourceSet != null) return false; // Ignore the actual version of the ResourceReader and // RuntimeResourceSet classes. Let those classes deal with // versioning themselves. AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName); if (readerTypeName != null) { if (!ResourceManager.CompareNames(readerTypeName, ResourceManager.ResReaderTypeName, mscorlib)) return false; } if (resSetTypeName != null) { if (!ResourceManager.CompareNames(resSetTypeName, ResourceManager.ResSetTypeName, mscorlib)) return false; } return true; } [System.Security.SecurityCritical] private String GetSatelliteAssemblyName() { String satAssemblyName = _mediator.MainAssembly.GetSimpleName(); satAssemblyName += ".resources"; return satAssemblyName; } [System.Security.SecurityCritical] private void HandleSatelliteMissing() { String satAssemName = _mediator.MainAssembly.GetSimpleName() + ".resources.dll"; if (_mediator.SatelliteContractVersion != null) { satAssemName += ", Version=" + _mediator.SatelliteContractVersion.ToString(); } AssemblyName an = new AssemblyName(); an.SetPublicKey(_mediator.MainAssembly.GetPublicKey()); byte[] token = an.GetPublicKeyToken(); int iLen = token.Length; StringBuilder publicKeyTok = new StringBuilder(iLen * 2); for (int i = 0; i < iLen; i++) { publicKeyTok.Append(token[i].ToString("x", CultureInfo.InvariantCulture)); } satAssemName += ", PublicKeyToken=" + publicKeyTok; String missingCultureName = _mediator.NeutralResourcesCulture.Name; if (missingCultureName.Length == 0) { missingCultureName = "<invariant>"; } throw new MissingSatelliteAssemblyException(Environment.GetResourceString("MissingSatelliteAssembly_Culture_Name", _mediator.NeutralResourcesCulture, satAssemName), missingCultureName); } [System.Security.SecurityCritical] // auto-generated private void HandleResourceStreamMissing(String fileName) { // Keep people from bothering me about resources problems if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name)) { // This would break CultureInfo & all our exceptions. Contract.Assert(false, "Couldn't get " + System.CoreLib.Name+ResourceManager.ResFileExtension + " from "+System.CoreLib.Name+"'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug."); // We cannot continue further - simply FailFast. string mesgFailFast = System.CoreLib.Name + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!"; System.Environment.FailFast(mesgFailFast); } // We really don't think this should happen - we always // expect the neutral locale's resources to be present. String resName = String.Empty; if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null) resName = _mediator.LocationInfo.Namespace + Type.Delimiter; resName += fileName; throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoNeutralAsm", resName, _mediator.MainAssembly.GetSimpleName())); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [System.Security.SecurityCritical] // Our security team doesn't yet allow safe-critical P/Invoke methods. [System.Security.SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation); } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Utils; using NUnit.Framework; namespace Grpc.Core.Tests { /// <summary> /// Allows setting up a mock service in the client-server tests easily. /// </summary> public class MockServiceHelper { public const string ServiceName = "tests.Test"; readonly string host; readonly ServerServiceDefinition serviceDefinition; readonly IEnumerable<ChannelOption> channelOptions; readonly Method<string, string> unaryMethod; readonly Method<string, string> clientStreamingMethod; readonly Method<string, string> serverStreamingMethod; readonly Method<string, string> duplexStreamingMethod; UnaryServerMethod<string, string> unaryHandler; ClientStreamingServerMethod<string, string> clientStreamingHandler; ServerStreamingServerMethod<string, string> serverStreamingHandler; DuplexStreamingServerMethod<string, string> duplexStreamingHandler; Server server; Channel channel; public MockServiceHelper(string host = null, Marshaller<string> marshaller = null, IEnumerable<ChannelOption> channelOptions = null) { this.host = host ?? "localhost"; this.channelOptions = channelOptions; marshaller = marshaller ?? Marshallers.StringMarshaller; unaryMethod = new Method<string, string>( MethodType.Unary, ServiceName, "Unary", marshaller, marshaller); clientStreamingMethod = new Method<string, string>( MethodType.ClientStreaming, ServiceName, "ClientStreaming", marshaller, marshaller); serverStreamingMethod = new Method<string, string>( MethodType.ServerStreaming, ServiceName, "ServerStreaming", marshaller, marshaller); duplexStreamingMethod = new Method<string, string>( MethodType.DuplexStreaming, ServiceName, "DuplexStreaming", marshaller, marshaller); serviceDefinition = ServerServiceDefinition.CreateBuilder() .AddMethod(unaryMethod, (request, context) => unaryHandler(request, context)) .AddMethod(clientStreamingMethod, (requestStream, context) => clientStreamingHandler(requestStream, context)) .AddMethod(serverStreamingMethod, (request, responseStream, context) => serverStreamingHandler(request, responseStream, context)) .AddMethod(duplexStreamingMethod, (requestStream, responseStream, context) => duplexStreamingHandler(requestStream, responseStream, context)) .Build(); var defaultStatus = new Status(StatusCode.Unknown, "Default mock implementation. Please provide your own."); unaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = defaultStatus; return ""; }); clientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { context.Status = defaultStatus; return ""; }); serverStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { context.Status = defaultStatus; }); duplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) => { context.Status = defaultStatus; }); } /// <summary> /// Returns the default server for this service and creates one if not yet created. /// </summary> public Server GetServer() { if (server == null) { // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755 server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) }) { Services = { serviceDefinition }, Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } } }; } return server; } /// <summary> /// Returns the default channel for this service and creates one if not yet created. /// </summary> public Channel GetChannel() { if (channel == null) { channel = new Channel(Host, GetServer().Ports.Single().BoundPort, ChannelCredentials.Insecure, channelOptions); } return channel; } public CallInvocationDetails<string, string> CreateUnaryCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, unaryMethod, options); } public CallInvocationDetails<string, string> CreateClientStreamingCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, clientStreamingMethod, options); } public CallInvocationDetails<string, string> CreateServerStreamingCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, serverStreamingMethod, options); } public CallInvocationDetails<string, string> CreateDuplexStreamingCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, duplexStreamingMethod, options); } public string Host { get { return this.host; } } public ServerServiceDefinition ServiceDefinition { get { return this.serviceDefinition; } } public UnaryServerMethod<string, string> UnaryHandler { get { return this.unaryHandler; } set { unaryHandler = value; } } public ClientStreamingServerMethod<string, string> ClientStreamingHandler { get { return this.clientStreamingHandler; } set { clientStreamingHandler = value; } } public ServerStreamingServerMethod<string, string> ServerStreamingHandler { get { return this.serverStreamingHandler; } set { serverStreamingHandler = value; } } public DuplexStreamingServerMethod<string, string> DuplexStreamingHandler { get { return this.duplexStreamingHandler; } set { duplexStreamingHandler = value; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Windows.Forms; namespace Cyotek.RegistryComparer.Client { internal sealed partial class MainForm : BaseForm { #region Constructors public MainForm() { this.InitializeComponent(); } #endregion #region Methods /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Form.Shown"/> event. /// </summary> /// <param name="e">A <see cref="T:System.EventArgs"/> that contains the event data. </param> protected override void OnShown(EventArgs e) { base.OnShown(e); hiveRadioButton.Checked = true; keysTextBox.Bounds = hivesListBox.Bounds; this.LoadRootHives(); this.LoadCustomKeys(); outputFolderTextBox.Text = Environment.CurrentDirectory; } private void aboutButton_Click(object sender, EventArgs e) { using (AboutDialog dialog = new AboutDialog()) { dialog.ShowDialog(this); } } private void AddCustomKey(string key) { keysTextBox.AppendText(key + Environment.NewLine); } private void AddHive(string name, bool select) { RegistryKeySnapshot item; item = new RegistryKeySnapshot(name); hivesListBox.Items.Add(item); if (select) { hivesListBox.SetItemChecked(hivesListBox.Items.Count - 1, true); } } private void AddSnapshot(RegistrySnapshot snapshot) { this.AddSnapshot(snapshot.FileName); } private void AddSnapshot(string fileName) { FileInfo info; info = new FileInfo(fileName); snapshotsListBox.Items.Add(info); firstComboBox.Items.Add(info); secondComboBox.Items.Add(info); } private void compareBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { TaskOptions options; RegistrySnapshot lhs; RegistrySnapshot rhs; RegistrySnapshotComparer comparer; options = (TaskOptions)e.Argument; lhs = RegistrySnapshot.LoadFromFile(options.FileName1); rhs = RegistrySnapshot.LoadFromFile(options.FileName2); comparer = new RegistrySnapshotComparer(lhs, rhs); e.Result = comparer.Compare(); } private void compareBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { this.SetStatus(null); if (e.Error != null) { MessageBox.Show(e.Error.GetBaseException(). Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { this.HandleCompareResults((ChangeResult[])e.Result); } } private void compareButton_Click(object sender, EventArgs e) { if (firstComboBox.SelectedItem == null || secondComboBox.SelectedItem == null) { MessageBox.Show("Please select two snapshots to compare.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { TaskOptions options; this.SetStatus("Comparing snapshots..."); options = new TaskOptions { FileName1 = ((FileInfo)firstComboBox.SelectedItem).FullPath, FileName2 = ((FileInfo)secondComboBox.SelectedItem).FullPath }; compareBackgroundWorker.RunWorkerAsync(options); } } private void deleteButton_Click(object sender, EventArgs e) { if (snapshotsListBox.SelectedItems.Count == 0) { MessageBox.Show("Please select the snapshot files to delete.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } else if ( MessageBox.Show("Are you sure you want to delete the selected snapshots?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { List<FileInfo> filesToDelete; filesToDelete = snapshotsListBox.SelectedItems.Cast<FileInfo>(). ToList(); foreach (FileInfo file in filesToDelete) { try { File.Delete(file.FullPath); this.RemoveSnapshot(file); } catch (Exception ex) { MessageBox.Show($"Failed to delete file. {ex.GetBaseException().Message}", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } private void exitButton_Click(object sender, EventArgs e) { this.Close(); } private void firstComboBox_SelectedIndexChanged(object sender, EventArgs e) { this.SetToolTip(firstComboBox); } private string[] GetKeysToScan() { List<string> keys; keys = new List<string>(); if (hiveRadioButton.Checked) { // ReSharper disable once LoopCanBeConvertedToQuery foreach (object item in hivesListBox.CheckedItems) { keys.Add(((RegistryKeySnapshot)item).Name); } } else { foreach (string rawKey in keysTextBox.Lines) { string key; key = rawKey.Trim(); if (!string.IsNullOrEmpty(key) && !keys.Contains(key)) { keys.Add(key); } } } return keys.ToArray(); } private void HandleCompareResults(ChangeResult[] results) { if (results.Length == 0) { MessageBox.Show("No differences found.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { using (ViewCompareResultsDialog dialog = new ViewCompareResultsDialog(results)) { dialog.ShowDialog(this); } } } private void hiveRadioButton_CheckedChanged(object sender, EventArgs e) { bool useHives; useHives = hiveRadioButton.Checked; hivesListBox.Visible = useHives; keysTextBox.Visible = !useHives; } private void LoadCustomKeys() { keysTextBox.Clear(); this.AddCustomKey("HKEY_CURRENT_USER\\SOFTWARE"); this.AddCustomKey("HKEY_LOCAL_MACHINE\\SOFTWARE"); //this.AddCustomKey(@"HKEY_CURRENT_USER\SOFTWARE\Cyotek"); } private void loadFileListDelayTimer_Tick(object sender, EventArgs e) { string path; loadFileListDelayTimer.Stop(); path = outputFolderTextBox.Text; if (!string.IsNullOrEmpty(path) && Directory.Exists(path)) { snapshotsListBox.BeginUpdate(); snapshotsListBox.Items.Clear(); firstComboBox.Items.Clear(); secondComboBox.Items.Clear(); foreach (string fileName in Directory.GetFiles(path, "*.rge")) { this.AddSnapshot(fileName); } snapshotsListBox.EndUpdate(); } } private void LoadRootHives() { hivesListBox.BeginUpdate(); this.AddHive("HKEY_CLASSES_ROOT", false); this.AddHive("HKEY_CURRENT_USER", true); this.AddHive("HKEY_LOCAL_MACHINE", true); this.AddHive("HKEY_USERS", false); this.AddHive("HKEY_CURRENT_CONFIG", false); // this.AddHive("HKEY_PERFORMANCE_DATA", false); // this.AddHive("HKEY_DYN_DATA", false); hivesListBox.EndUpdate(); } private void outputFolderBrowseButton_Click(object sender, EventArgs e) { using (FolderBrowserDialog dialog = new FolderBrowserDialog { Description = "Select the &folder to store snapshots", ShowNewFolderButton = true, SelectedPath = outputFolderTextBox.Text }) { if (dialog.ShowDialog(this) == DialogResult.OK) { outputFolderTextBox.Text = dialog.SelectedPath; } } } private void outputFolderTextBox_TextChanged(object sender, EventArgs e) { loadFileListDelayTimer.Stop(); loadFileListDelayTimer.Start(); } private void RemoveSnapshot(FileInfo file) { snapshotsListBox.Items.Remove(file); firstComboBox.Items.Remove(file); secondComboBox.Items.Remove(file); } private void secondComboBox_SelectedIndexChanged(object sender, EventArgs e) { this.SetToolTip(secondComboBox); } private void SetStatus(string message) { statusToolStripStatusLabel.Text = message; this.SetControls(string.IsNullOrEmpty(message)); this.UseWaitCursor = !string.IsNullOrEmpty(message); } private void SetControls(bool enabled) { foreach (Control control in this.Controls) { if (!object.ReferenceEquals(control, exitButton)) { control.Enabled = enabled; } } } private void SetToolTip(ComboBox comboBox) { FileInfo info; info = comboBox.SelectedItem as FileInfo; toolTip.SetToolTip(comboBox, info?.FullPath); } private void snapshotBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { TaskOptions options; RegistrySnapshot snapshot; string fileName; string name; options = (TaskOptions)e.Argument; name = DateTime.Now.ToString("yyyyMMdd HHmm"); fileName = PathHelpers.GetUniqueFileName(name, options.OutputPath); snapshot = RegistrySnapshot.TakeSnapshot(options.Keys); snapshot.Name = name; snapshot.Save(fileName); e.Result = snapshot; } private void snapshotBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { this.SetStatus(null); if (e.Error != null) { MessageBox.Show(e.Error.GetBaseException(). Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { RegistrySnapshot snapshot; snapshot = (RegistrySnapshot)e.Result; this.AddSnapshot(snapshot); MessageBox.Show(string.Format("Snapshot created.\n\nFile saved to '{0}'.", snapshot.FileName), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void takeSnapshotButton_Click(object sender, EventArgs e) { TaskOptions options; string[] keys; string path; keys = this.GetKeysToScan(); path = PathHelpers.GetFullPath(outputFolderTextBox.Text); this.SetStatus("Taking snapshot..."); options = new TaskOptions { Keys = keys, OutputPath = path }; snapshotBackgroundWorker.RunWorkerAsync(options); } private void viewButton_Click(object sender, EventArgs e) { if (snapshotsListBox.SelectedItem == null) { MessageBox.Show("Please select the snapshot to view.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { RegistrySnapshot snapshot; string fileName; this.SetStatus("Loading snapshot..."); fileName = ((FileInfo)snapshotsListBox.SelectedItem).FullPath; snapshot = RegistrySnapshot.LoadFromFile(fileName); this.SetStatus(null); using (ViewDialog dialog = new ViewDialog(snapshot)) { dialog.ShowDialog(this); } } } #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 System; using System.Globalization; using System.Management.Automation; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.WindowsAzure.Commands.SqlDatabase.Properties; using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Common; using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Server; using Microsoft.WindowsAzure.Commands.Utilities.Common; using Microsoft.Azure.Commands.Common.Authentication; using Microsoft.Azure.Commands.Common.Authentication.Abstractions; namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet { /// <summary> /// Update settings for an existing Microsoft Azure SQL Database in the given server context. /// </summary> [Cmdlet(VerbsCommon.Remove, "AzureSqlDatabase", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)] public class RemoveAzureSqlDatabase : AzureSMCmdlet { #region Parameter sets /// <summary> /// The name of the parameter set for removing a database by name with a connection context /// </summary> internal const string ByNameWithConnectionContext = "ByNameWithConnectionContext"; /// <summary> /// The name of the parameter set for removing a database by name using azure subscription /// </summary> internal const string ByNameWithServerName = "ByNameWithServerName"; /// <summary> /// The name of the parameter set for removing a database by input /// object with a connection context /// </summary> internal const string ByObjectWithConnectionContext = "ByObjectWithConnectionContext"; /// <summary> /// The name of the parameter set for removing a database by input /// object using azure subscription /// </summary> internal const string ByObjectWithServerName = "ByObjectWithServerName"; #endregion #region Parameters /// <summary> /// Gets or sets the server connection context. /// </summary> [Alias("Context")] [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ByNameWithConnectionContext, HelpMessage = "The connection context to the specified server.")] [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ByObjectWithConnectionContext, HelpMessage = "The connection context to the specified server.")] [ValidateNotNull] public IServerDataServiceContext ConnectionContext { get; set; } /// <summary> /// Gets or sets the name of the server to connect to /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ByNameWithServerName, HelpMessage = "The name of the server to connect to")] [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ByObjectWithServerName, HelpMessage = "The name of the server to connect to")] [ValidateNotNullOrEmpty] public string ServerName { get; set; } /// <summary> /// Gets or sets the database. /// </summary> [Alias("InputObject")] [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true, ParameterSetName = ByObjectWithConnectionContext, HelpMessage = "The database object you want to remove")] [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true, ParameterSetName = ByObjectWithServerName, HelpMessage = "The database object you want to remove")] [ValidateNotNull] public Services.Server.Database Database { get; set; } /// <summary> /// Gets or sets the database name. /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByNameWithConnectionContext, HelpMessage = "The name of the database to remove")] [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByNameWithServerName, HelpMessage = "The name of the database to remove")] [ValidateNotNullOrEmpty] public string DatabaseName { get; set; } /// <summary> /// Gets or sets the switch to not confirm on the removal of the database. /// </summary> [Parameter(HelpMessage = "Do not confirm on the removal of the database")] public SwitchParameter Force { get; set; } #endregion /// <summary> /// Process the command. /// </summary> public override void ExecuteCmdlet() { // Obtain the database name from the given parameters. string databaseName = null; if (this.MyInvocation.BoundParameters.ContainsKey("Database")) { databaseName = this.Database.Name; } else if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseName")) { databaseName = this.DatabaseName; } // Determine the name of the server we are connecting to string serverName = null; if (this.MyInvocation.BoundParameters.ContainsKey("ServerName")) { serverName = this.ServerName; } else { serverName = this.ConnectionContext.ServerName; } string actionDescription = string.Format( CultureInfo.InvariantCulture, Resources.RemoveAzureSqlDatabaseDescription, serverName, databaseName); string actionWarning = string.Format( CultureInfo.InvariantCulture, Resources.RemoveAzureSqlDatabaseWarning, serverName, databaseName); this.WriteVerbose(actionDescription); // Do nothing if force is not specified and user cancelled the operation if (!this.Force.IsPresent && !this.ShouldProcess( actionDescription, actionWarning, Resources.ShouldProcessCaption)) { return; } switch (this.ParameterSetName) { case ByNameWithConnectionContext: case ByObjectWithConnectionContext: this.ProcessWithConnectionContext(databaseName); break; case ByNameWithServerName: case ByObjectWithServerName: this.ProcessWithServerName(databaseName); break; } } /// <summary> /// Process the request using a temporary connection context. /// </summary> /// <param name="databaseName">The name of the database to remove</param> private void ProcessWithServerName(string databaseName) { Func<string> GetClientRequestId = () => string.Empty; try { // Get the current subscription data. IAzureSubscription subscription = Profile.Context.Subscription; // Create a temporary context ServerDataServiceCertAuth context = ServerDataServiceCertAuth.Create(this.ServerName, Profile, subscription); GetClientRequestId = () => context.ClientRequestId; // Remove the database with the specified name context.RemoveDatabase(databaseName); } catch (Exception ex) { SqlDatabaseExceptionHandler.WriteErrorDetails( this, GetClientRequestId(), ex); } } /// <summary> /// Process the request with the connection context /// </summary> /// <param name="databaseName">The name of the database to remove</param> private void ProcessWithConnectionContext(string databaseName) { try { // Remove the database with the specified name this.ConnectionContext.RemoveDatabase(databaseName); } catch (Exception ex) { SqlDatabaseExceptionHandler.WriteErrorDetails( this, this.ConnectionContext.ClientRequestId, ex); } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using ASC.Common.Data.Sql.Expressions; using ASC.Core; using ASC.Files.Core; using ASC.Web.Core.Files; using ASC.Web.Studio.Core; using DriveFile = Google.Apis.Drive.v3.Data.File; using File = ASC.Files.Core.File; namespace ASC.Files.Thirdparty.GoogleDrive { internal class GoogleDriveFileDao : GoogleDriveDaoBase, IFileDao { public GoogleDriveFileDao(GoogleDriveDaoSelector.GoogleDriveInfo providerInfo, GoogleDriveDaoSelector googleDriveDaoSelector) : base(providerInfo, googleDriveDaoSelector) { } public void InvalidateCache(object fileId) { var driveId = MakeDriveId(fileId); GoogleDriveProviderInfo.CacheReset(driveId, true); var driveFile = GetDriveEntry(fileId); var parentDriveId = GetParentDriveId(driveFile); if (parentDriveId != null) GoogleDriveProviderInfo.CacheReset(parentDriveId); } public File GetFile(object fileId) { return GetFile(fileId, 1); } public File GetFile(object fileId, int fileVersion) { return ToFile(GetDriveEntry(fileId)); } public File GetFile(object parentId, string title) { return ToFile(GetDriveEntries(parentId, false) .FirstOrDefault(file => file.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase))); } public File GetFileStable(object fileId, int fileVersion) { return ToFile(GetDriveEntry(fileId)); } public List<File> GetFileHistory(object fileId) { return new List<File> { GetFile(fileId) }; } public List<File> GetFiles(IEnumerable<object> fileIds) { if (fileIds == null || !fileIds.Any()) return new List<File>(); return fileIds.Select(GetDriveEntry).Select(ToFile).ToList(); } public List<File> GetFilesFiltered(IEnumerable<object> fileIds, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool searchInContent) { if (fileIds == null || !fileIds.Any() || filterType == FilterType.FoldersOnly) return new List<File>(); var files = GetFiles(fileIds).AsEnumerable(); //Filter if (subjectID != Guid.Empty) { files = files.Where(x => subjectGroup ? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID) : x.CreateBy == subjectID); } switch (filterType) { case FilterType.FoldersOnly: return new List<File>(); case FilterType.DocumentsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Document); break; case FilterType.PresentationsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Presentation); break; case FilterType.SpreadsheetsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Spreadsheet); break; case FilterType.ImagesOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Image); break; case FilterType.ArchiveOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Archive); break; case FilterType.MediaOnly: files = files.Where(x => { FileType fileType; return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: if (!string.IsNullOrEmpty(searchText)) { searchText = searchText.Trim().ToLower(); files = files.Where(x => FileUtility.GetFileExtension(x.Title).Equals(searchText)); } break; } if (!string.IsNullOrEmpty(searchText)) files = files.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1); return files.ToList(); } public List<object> GetFiles(object parentId) { return GetDriveEntries(parentId, false).Select(entry => (object)MakeId(entry.Id)).ToList(); } public List<File> GetFiles(object parentId, OrderBy orderBy, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool searchInContent, bool withSubfolders = false) { if (filterType == FilterType.FoldersOnly) return new List<File>(); //Get only files var files = GetDriveEntries(parentId, false).Select(ToFile); //Filter if (subjectID != Guid.Empty) { files = files.Where(x => subjectGroup ? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID) : x.CreateBy == subjectID); } switch (filterType) { case FilterType.FoldersOnly: return new List<File>(); case FilterType.DocumentsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Document); break; case FilterType.PresentationsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Presentation); break; case FilterType.SpreadsheetsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Spreadsheet); break; case FilterType.ImagesOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Image); break; case FilterType.ArchiveOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Archive); break; case FilterType.MediaOnly: files = files.Where(x => { FileType fileType; return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: if (!string.IsNullOrEmpty(searchText)) { searchText = searchText.Trim().ToLower(); files = files.Where(x => FileUtility.GetFileExtension(x.Title).Equals(searchText)); } break; } if (!string.IsNullOrEmpty(searchText)) files = files.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1); if (orderBy == null) orderBy = new OrderBy(SortedByType.DateAndTime, false); switch (orderBy.SortedBy) { case SortedByType.Author: files = orderBy.IsAsc ? files.OrderBy(x => x.CreateBy) : files.OrderByDescending(x => x.CreateBy); break; case SortedByType.AZ: files = orderBy.IsAsc ? files.OrderBy(x => x.Title) : files.OrderByDescending(x => x.Title); break; case SortedByType.DateAndTime: files = orderBy.IsAsc ? files.OrderBy(x => x.ModifiedOn) : files.OrderByDescending(x => x.ModifiedOn); break; case SortedByType.DateAndTimeCreation: files = orderBy.IsAsc ? files.OrderBy(x => x.CreateOn) : files.OrderByDescending(x => x.CreateOn); break; default: files = orderBy.IsAsc ? files.OrderBy(x => x.Title) : files.OrderByDescending(x => x.Title); break; } return files.ToList(); } public Stream GetFileStream(File file) { return GetFileStream(file, 0); } public Stream GetFileStream(File file, long offset) { var driveId = MakeDriveId(file.ID); GoogleDriveProviderInfo.CacheReset(driveId, true); var driveFile = GetDriveEntry(file.ID); if (driveFile == null) throw new ArgumentNullException("file", Web.Files.Resources.FilesCommonResource.ErrorMassage_FileNotFound); if (driveFile is ErrorDriveEntry) throw new Exception(((ErrorDriveEntry)driveFile).Error); var fileStream = GoogleDriveProviderInfo.Storage.DownloadStream(driveFile, (int)offset); if (!driveFile.Size.HasValue && fileStream != null && fileStream.CanSeek) { file.ContentLength = fileStream.Length; // hack for google drive } return fileStream; } public Uri GetPreSignedUri(File file, TimeSpan expires) { throw new NotSupportedException(); } public bool IsSupportedPreSignedUri(File file) { return false; } public File SaveFile(File file, Stream fileStream) { if (file == null) throw new ArgumentNullException("file"); if (fileStream == null) throw new ArgumentNullException("fileStream"); DriveFile newDriveFile = null; if (file.ID != null) { newDriveFile = GoogleDriveProviderInfo.Storage.SaveStream(MakeDriveId(file.ID), fileStream, file.Title); } else if (file.FolderID != null) { newDriveFile = GoogleDriveProviderInfo.Storage.InsertEntry(fileStream, file.Title, MakeDriveId(file.FolderID)); } GoogleDriveProviderInfo.CacheReset(newDriveFile); var parentDriveId = GetParentDriveId(newDriveFile); if (parentDriveId != null) GoogleDriveProviderInfo.CacheReset(parentDriveId, false); return ToFile(newDriveFile); } public File ReplaceFileVersion(File file, Stream fileStream) { return SaveFile(file, fileStream); } public void DeleteFile(object fileId) { var driveFile = GetDriveEntry(fileId); if (driveFile == null) return; var id = MakeId(driveFile.Id); using (var db = GetDb()) using (var tx = db.BeginTransaction()) { var hashIDs = db.ExecuteList(Query("files_thirdparty_id_mapping") .Select("hash_id") .Where(Exp.Like("id", id, SqlLike.StartWith))) .ConvertAll(x => x[0]); db.ExecuteNonQuery(Delete("files_tag_link").Where(Exp.In("entry_id", hashIDs))); db.ExecuteNonQuery(Delete("files_security").Where(Exp.In("entry_id", hashIDs))); db.ExecuteNonQuery(Delete("files_thirdparty_id_mapping").Where(Exp.In("hash_id", hashIDs))); var tagsToRemove = db.ExecuteList( Query("files_tag tbl_ft ") .Select("tbl_ft.id") .LeftOuterJoin("files_tag_link tbl_ftl", Exp.EqColumns("tbl_ft.tenant_id", "tbl_ftl.tenant_id") & Exp.EqColumns("tbl_ft.id", "tbl_ftl.tag_id")) .Where("tbl_ftl.tag_id is null")) .ConvertAll(r => Convert.ToInt32(r[0])); db.ExecuteNonQuery(Delete("files_tag").Where(Exp.In("id", tagsToRemove))); tx.Commit(); } if (!(driveFile is ErrorDriveEntry)) GoogleDriveProviderInfo.Storage.DeleteEntry(driveFile.Id); GoogleDriveProviderInfo.CacheReset(driveFile.Id); var parentDriveId = GetParentDriveId(driveFile); if (parentDriveId != null) GoogleDriveProviderInfo.CacheReset(parentDriveId, false); } public bool IsExist(string title, object folderId) { return GetDriveEntries(folderId, false) .Any(file => file.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase)); } public object MoveFile(object fileId, object toFolderId) { var driveFile = GetDriveEntry(fileId); if (driveFile is ErrorDriveEntry) throw new Exception(((ErrorDriveEntry)driveFile).Error); var toDriveFolder = GetDriveEntry(toFolderId); if (toDriveFolder is ErrorDriveEntry) throw new Exception(((ErrorDriveEntry)toDriveFolder).Error); var fromFolderDriveId = GetParentDriveId(driveFile); driveFile = GoogleDriveProviderInfo.Storage.InsertEntryIntoFolder(driveFile, toDriveFolder.Id); if (fromFolderDriveId != null) { GoogleDriveProviderInfo.Storage.RemoveEntryFromFolder(driveFile, fromFolderDriveId); } GoogleDriveProviderInfo.CacheReset(driveFile.Id); GoogleDriveProviderInfo.CacheReset(fromFolderDriveId, false); GoogleDriveProviderInfo.CacheReset(toDriveFolder.Id, false); return MakeId(driveFile.Id); } public File CopyFile(object fileId, object toFolderId) { var driveFile = GetDriveEntry(fileId); if (driveFile is ErrorDriveEntry) throw new Exception(((ErrorDriveEntry)driveFile).Error); var toDriveFolder = GetDriveEntry(toFolderId); if (toDriveFolder is ErrorDriveEntry) throw new Exception(((ErrorDriveEntry)toDriveFolder).Error); var newDriveFile = GoogleDriveProviderInfo.Storage.CopyEntry(toDriveFolder.Id, driveFile.Id); GoogleDriveProviderInfo.CacheReset(newDriveFile); GoogleDriveProviderInfo.CacheReset(toDriveFolder.Id, false); return ToFile(newDriveFile); } public object FileRename(File file, string newTitle) { var driveFile = GetDriveEntry(file.ID); driveFile.Name = newTitle; driveFile = GoogleDriveProviderInfo.Storage.RenameEntry(driveFile.Id, driveFile.Name); GoogleDriveProviderInfo.CacheReset(driveFile); var parentDriveId = GetParentDriveId(driveFile); if (parentDriveId != null) GoogleDriveProviderInfo.CacheReset(parentDriveId, false); return MakeId(driveFile.Id); } public string UpdateComment(object fileId, int fileVersion, string comment) { return string.Empty; } public void CompleteVersion(object fileId, int fileVersion) { } public void ContinueVersion(object fileId, int fileVersion) { } public bool UseTrashForRemove(File file) { return false; } #region chunking private File RestoreIds(File file) { if (file == null) return null; if (file.ID != null) file.ID = MakeId(file.ID.ToString()); if (file.FolderID != null) file.FolderID = MakeId(file.FolderID.ToString()); return file; } public ChunkedUploadSession CreateUploadSession(File file, long contentLength) { if (SetupInfo.ChunkUploadSize > contentLength) return new ChunkedUploadSession(RestoreIds(file), contentLength) { UseChunks = false }; var uploadSession = new ChunkedUploadSession(file, contentLength); DriveFile driveFile; if (file.ID != null) { driveFile = GetDriveEntry(file.ID); } else { var folder = GetDriveEntry(file.FolderID); driveFile = GoogleDriveProviderInfo.Storage.FileConstructor(file.Title, null, folder.Id); } var googleDriveSession = GoogleDriveProviderInfo.Storage.CreateResumableSession(driveFile, contentLength); if (googleDriveSession != null) { uploadSession.Items["GoogleDriveSession"] = googleDriveSession; } else { uploadSession.Items["TempPath"] = TempPath.GetTempFileName(); } uploadSession.File = RestoreIds(uploadSession.File); return uploadSession; } public File UploadChunk(ChunkedUploadSession uploadSession, Stream stream, long chunkLength) { if (!uploadSession.UseChunks) { if (uploadSession.BytesTotal == 0) uploadSession.BytesTotal = chunkLength; uploadSession.File = SaveFile(uploadSession.File, stream); uploadSession.BytesUploaded = chunkLength; return uploadSession.File; } if (uploadSession.Items.ContainsKey("GoogleDriveSession")) { var googleDriveSession = uploadSession.GetItemOrDefault<ResumableUploadSession>("GoogleDriveSession"); GoogleDriveProviderInfo.Storage.Transfer(googleDriveSession, stream, chunkLength); } else { var tempPath = uploadSession.GetItemOrDefault<string>("TempPath"); using (var fs = new FileStream(tempPath, FileMode.Append)) { stream.CopyTo(fs); } } uploadSession.BytesUploaded += chunkLength; if (uploadSession.BytesUploaded == uploadSession.BytesTotal) { uploadSession.File = FinalizeUploadSession(uploadSession); } else { uploadSession.File = RestoreIds(uploadSession.File); } return uploadSession.File; } public File FinalizeUploadSession(ChunkedUploadSession uploadSession) { if (uploadSession.Items.ContainsKey("GoogleDriveSession")) { var googleDriveSession = uploadSession.GetItemOrDefault<ResumableUploadSession>("GoogleDriveSession"); GoogleDriveProviderInfo.CacheReset(googleDriveSession.FileId); var parentDriveId = googleDriveSession.FolderId; if (parentDriveId != null) GoogleDriveProviderInfo.CacheReset(parentDriveId, false); return ToFile(GetDriveEntry(googleDriveSession.FileId)); } using (var fs = new FileStream(uploadSession.GetItemOrDefault<string>("TempPath"), FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose)) { return SaveFile(uploadSession.File, fs); } } public void AbortUploadSession(ChunkedUploadSession uploadSession) { if (uploadSession.Items.ContainsKey("GoogleDriveSession")) { var googleDriveSession = uploadSession.GetItemOrDefault<ResumableUploadSession>("GoogleDriveSession"); if (googleDriveSession.Status != ResumableUploadSessionStatus.Completed) { googleDriveSession.Status = ResumableUploadSessionStatus.Aborted; } } else if (uploadSession.Items.ContainsKey("TempPath")) { System.IO.File.Delete(uploadSession.GetItemOrDefault<string>("TempPath")); } } #endregion #region Only in TMFileDao public void ReassignFiles(IEnumerable<object> fileIds, Guid newOwnerId) { } public List<File> GetFiles(IEnumerable<object> parentIds, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool searchInContent) { return new List<File>(); } public IEnumerable<File> Search(string text, bool bunch) { return null; } public bool IsExistOnStorage(File file) { return true; } public void SaveEditHistory(File file, string changes, Stream differenceStream) { //Do nothing } public List<EditHistory> GetEditHistory(object fileId, int fileVersion) { return null; } public Stream GetDifferenceStream(File file) { return null; } public bool ContainChanges(object fileId, int fileVersion) { return false; } public void SaveThumbnail(File file, Stream thumbnail) { //Do nothing } public Stream GetThumbnail(File file) { return null; } public Task<Stream> GetFileStreamAsync(File file) { return Task.FromResult(GetFileStream(file)); } public Task<bool> IsExistOnStorageAsync(File file) { return Task.FromResult(IsExistOnStorage(file)); } #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// CommandResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Supersim.V1 { public class CommandResource : Resource { public sealed class StatusEnum : StringEnum { private StatusEnum(string value) : base(value) {} public StatusEnum() {} public static implicit operator StatusEnum(string value) { return new StatusEnum(value); } public static readonly StatusEnum Queued = new StatusEnum("queued"); public static readonly StatusEnum Sent = new StatusEnum("sent"); public static readonly StatusEnum Delivered = new StatusEnum("delivered"); public static readonly StatusEnum Received = new StatusEnum("received"); public static readonly StatusEnum Failed = new StatusEnum("failed"); } public sealed class DirectionEnum : StringEnum { private DirectionEnum(string value) : base(value) {} public DirectionEnum() {} public static implicit operator DirectionEnum(string value) { return new DirectionEnum(value); } public static readonly DirectionEnum ToSim = new DirectionEnum("to_sim"); public static readonly DirectionEnum FromSim = new DirectionEnum("from_sim"); } private static Request BuildCreateRequest(CreateCommandOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Supersim, "/v1/Commands", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Send a Command to a Sim. /// </summary> /// <param name="options"> Create Command parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Command </returns> public static CommandResource Create(CreateCommandOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Send a Command to a Sim. /// </summary> /// <param name="options"> Create Command parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Command </returns> public static async System.Threading.Tasks.Task<CommandResource> CreateAsync(CreateCommandOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Send a Command to a Sim. /// </summary> /// <param name="sim"> The sid or unique_name of the SIM to send the Command to </param> /// <param name="command"> The message body of the command </param> /// <param name="callbackMethod"> The HTTP method we should use to call callback_url </param> /// <param name="callbackUrl"> The URL we should call after we have sent the command </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Command </returns> public static CommandResource Create(string sim, string command, Twilio.Http.HttpMethod callbackMethod = null, Uri callbackUrl = null, ITwilioRestClient client = null) { var options = new CreateCommandOptions(sim, command){CallbackMethod = callbackMethod, CallbackUrl = callbackUrl}; return Create(options, client); } #if !NET35 /// <summary> /// Send a Command to a Sim. /// </summary> /// <param name="sim"> The sid or unique_name of the SIM to send the Command to </param> /// <param name="command"> The message body of the command </param> /// <param name="callbackMethod"> The HTTP method we should use to call callback_url </param> /// <param name="callbackUrl"> The URL we should call after we have sent the command </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Command </returns> public static async System.Threading.Tasks.Task<CommandResource> CreateAsync(string sim, string command, Twilio.Http.HttpMethod callbackMethod = null, Uri callbackUrl = null, ITwilioRestClient client = null) { var options = new CreateCommandOptions(sim, command){CallbackMethod = callbackMethod, CallbackUrl = callbackUrl}; return await CreateAsync(options, client); } #endif private static Request BuildFetchRequest(FetchCommandOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Supersim, "/v1/Commands/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch a Command instance from your account. /// </summary> /// <param name="options"> Fetch Command parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Command </returns> public static CommandResource Fetch(FetchCommandOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch a Command instance from your account. /// </summary> /// <param name="options"> Fetch Command parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Command </returns> public static async System.Threading.Tasks.Task<CommandResource> FetchAsync(FetchCommandOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch a Command instance from your account. /// </summary> /// <param name="pathSid"> The SID that identifies the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Command </returns> public static CommandResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchCommandOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch a Command instance from your account. /// </summary> /// <param name="pathSid"> The SID that identifies the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Command </returns> public static async System.Threading.Tasks.Task<CommandResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchCommandOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadCommandOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Supersim, "/v1/Commands", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of Commands from your account. /// </summary> /// <param name="options"> Read Command parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Command </returns> public static ResourceSet<CommandResource> Read(ReadCommandOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<CommandResource>.FromJson("commands", response.Content); return new ResourceSet<CommandResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of Commands from your account. /// </summary> /// <param name="options"> Read Command parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Command </returns> public static async System.Threading.Tasks.Task<ResourceSet<CommandResource>> ReadAsync(ReadCommandOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<CommandResource>.FromJson("commands", response.Content); return new ResourceSet<CommandResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of Commands from your account. /// </summary> /// <param name="sim"> The SID or unique name of the Sim that Command was sent to or from. </param> /// <param name="status"> The status of the Command </param> /// <param name="direction"> The direction of the Command </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Command </returns> public static ResourceSet<CommandResource> Read(string sim = null, CommandResource.StatusEnum status = null, CommandResource.DirectionEnum direction = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadCommandOptions(){Sim = sim, Status = status, Direction = direction, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of Commands from your account. /// </summary> /// <param name="sim"> The SID or unique name of the Sim that Command was sent to or from. </param> /// <param name="status"> The status of the Command </param> /// <param name="direction"> The direction of the Command </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Command </returns> public static async System.Threading.Tasks.Task<ResourceSet<CommandResource>> ReadAsync(string sim = null, CommandResource.StatusEnum status = null, CommandResource.DirectionEnum direction = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadCommandOptions(){Sim = sim, Status = status, Direction = direction, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<CommandResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<CommandResource>.FromJson("commands", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<CommandResource> NextPage(Page<CommandResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Supersim) ); var response = client.Request(request); return Page<CommandResource>.FromJson("commands", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<CommandResource> PreviousPage(Page<CommandResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Supersim) ); var response = client.Request(request); return Page<CommandResource>.FromJson("commands", response.Content); } /// <summary> /// Converts a JSON string into a CommandResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> CommandResource object represented by the provided JSON </returns> public static CommandResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<CommandResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the SIM that this Command was sent to or from /// </summary> [JsonProperty("sim_sid")] public string SimSid { get; private set; } /// <summary> /// The message body of the command sent to or from the SIM /// </summary> [JsonProperty("command")] public string Command { get; private set; } /// <summary> /// The status of the Command /// </summary> [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public CommandResource.StatusEnum Status { get; private set; } /// <summary> /// The direction of the Command /// </summary> [JsonProperty("direction")] [JsonConverter(typeof(StringEnumConverter))] public CommandResource.DirectionEnum Direction { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the Command resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private CommandResource() { } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.IO; namespace tk2dEditor.SpriteCollectionBuilder { public static class PlatformBuilder { public static void InitializeSpriteCollectionPlatforms(tk2dSpriteCollection gen, string root) { // Create all missing platform directories and sprite collection objects for (int i = 0; i < gen.platforms.Count; ++i) { tk2dSpriteCollectionPlatform plat = gen.platforms[i]; if (plat.name.Length > 0 && !plat.spriteCollection) { plat.spriteCollection = tk2dSpriteCollectionEditor.CreateSpriteCollection(root, gen.name + "@" + plat.name); plat.spriteCollection.managedSpriteCollection = true; EditorUtility.SetDirty(gen.spriteCollection); } } } static string FindFileInPath(string directory, string filename, string preferredExt, string[] otherExts) { string target = directory + "/" + filename + preferredExt; if (System.IO.File.Exists(target)) return target; foreach (string ext in otherExts) { if (ext == preferredExt) continue; target = directory + "/" + filename + ext; if (System.IO.File.Exists(target)) return target; } return ""; // not found } static readonly string[] textureExtensions = { ".psd", ".tiff", ".jpg", ".jpeg", ".tga", ".png", ".gif", ".bmp", ".iff", ".pict" }; static readonly string[] fontExtensions = { ".fnt", ".xml", ".txt" }; // Given a path to a texture, finds a platform specific version of it. Returns "" if not found in search paths static string FindAssetForPlatform(string platformName, string path, string[] extensions) { string directory = System.IO.Path.GetDirectoryName(path); string ext = System.IO.Path.GetExtension(path); string filename = System.IO.Path.GetFileNameWithoutExtension(path); int lastIndexOf = filename.LastIndexOf('@'); if (lastIndexOf != -1) filename = filename.Substring(0, lastIndexOf); // Find texture with same filename @platform // The first preferred path is with the filename@platform.ext string platformTexture = FindFileInPath(directory, filename + "@" + platformName, ext, extensions); // Second path to look for is platform/filename.ext if (platformTexture.Length == 0) { string altDirectory = directory + "/" + platformName; if (System.IO.Directory.Exists(altDirectory)) platformTexture = FindFileInPath(altDirectory, filename, ext, extensions); } // Third path to look for is platform/filename@platform.ext if (platformTexture.Length == 0) { string altDirectory = directory + "/" + platformName; if (System.IO.Directory.Exists(altDirectory)) platformTexture = FindFileInPath(altDirectory, filename + "@" + platformName, ext, extensions); } return platformTexture; } // Update target platforms public static void UpdatePlatformSpriteCollection(tk2dSpriteCollection source, tk2dSpriteCollection target, string dataPath, bool root, float scale, string platformName) { tk2dEditor.SpriteCollectionEditor.SpriteCollectionProxy proxy = new tk2dEditor.SpriteCollectionEditor.SpriteCollectionProxy(source); // Restore old sprite collection proxy.spriteCollection = target.spriteCollection; proxy.atlasTextures = target.atlasTextures; proxy.atlasMaterials = target.atlasMaterials; proxy.altMaterials = target.altMaterials; // This must always be zero, as children cannot have nested platforms. // That would open the door to a lot of unnecessary insanity proxy.platforms = new List<tk2dSpriteCollectionPlatform>(); // Update atlas sizes proxy.atlasWidth = (int)(proxy.atlasWidth * scale); proxy.atlasHeight = (int)(proxy.atlasHeight * scale); proxy.maxTextureSize = (int)(proxy.maxTextureSize * scale); proxy.forcedTextureWidth = (int)(proxy.forcedTextureWidth * scale); proxy.forcedTextureHeight = (int)(proxy.forcedTextureHeight * scale); if (!proxy.useTk2dCamera) proxy.targetOrthoSize *= 1.0f; proxy.globalScale = 1.0f / scale; // Don't bother changing stuff on the root object // The root object is the one that the sprite collection is defined on initially if (!root) { // Update textures foreach (tk2dSpriteCollectionDefinition param in proxy.textureParams) { if (param.texture == null) continue; string path = AssetDatabase.GetAssetPath(param.texture); string platformTexture = FindAssetForPlatform(platformName, path, textureExtensions); if (platformTexture.Length == 0) { LogNotFoundError(platformName, param.texture.name, "texture"); } else { Texture2D tex = AssetDatabase.LoadAssetAtPath(platformTexture, typeof(Texture2D)) as Texture2D; if (tex == null) { Debug.LogError("Unable to load platform specific texture '" + platformTexture + "'"); } else { param.texture = tex; } } // Handle spritesheets. Odd coordinates could cause issues if (param.extractRegion) { param.regionX = (int)(param.regionX * scale); param.regionY = (int)(param.regionY * scale); param.regionW = (int)(param.regionW * scale); param.regionH = (int)(param.regionH * scale); } if (param.anchor == tk2dSpriteCollectionDefinition.Anchor.Custom) { param.anchorX = (int)(param.anchorX * scale); param.anchorY = (int)(param.anchorY * scale); } if (param.customSpriteGeometry) { foreach (tk2dSpriteColliderIsland geom in param.geometryIslands) { for (int p = 0; p < geom.points.Length; ++p) geom.points[p] *= scale; } } else if (param.dice) { param.diceUnitX = (int)(param.diceUnitX * scale); param.diceUnitY = (int)(param.diceUnitY * scale); } if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon) { foreach (tk2dSpriteColliderIsland geom in param.polyColliderIslands) { for (int p = 0; p < geom.points.Length; ++p) geom.points[p] *= scale; } } else if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom) { param.boxColliderMax *= scale; param.boxColliderMin *= scale; } } } // We ALWAYS duplicate fonts if (target.fonts == null) target.fonts = new tk2dSpriteCollectionFont[0]; for (int i = 0; i < proxy.fonts.Count; ++i) { tk2dSpriteCollectionFont font = proxy.fonts[i]; if (!font.InUse || font.texture == null || font.data == null || font.editorData == null || font.bmFont == null) continue; // not valid for some reason or other bool needFontData = true; bool needFontEditorData = true; bool hasCorrespondingData = i < target.fonts.Length && target.fonts[i] != null; if (hasCorrespondingData) { tk2dSpriteCollectionFont targetFont = target.fonts[i]; if (targetFont.data != null) { font.data = targetFont.data; needFontData = false; } if (targetFont.editorData != null) { font.editorData = targetFont.editorData; needFontEditorData = false; } } string bmFontPath = AssetDatabase.GetAssetPath(font.bmFont); string texturePath = AssetDatabase.GetAssetPath(font.texture); if (!root) { // find platform specific versions bmFontPath = FindAssetForPlatform(platformName, bmFontPath, fontExtensions); texturePath = FindAssetForPlatform(platformName, texturePath, textureExtensions); if (bmFontPath.Length != 0 && texturePath.Length == 0) { // try to find a texture tk2dEditor.Font.Info fontInfo = tk2dEditor.Font.Builder.ParseBMFont(bmFontPath); if (fontInfo != null) texturePath = System.IO.Path.GetDirectoryName(bmFontPath).Replace('\\', '/') + "/" + System.IO.Path.GetFileName(fontInfo.texturePaths[0]); } if (bmFontPath.Length == 0) LogNotFoundError(platformName, font.bmFont.name, "font"); if (texturePath.Length == 0) LogNotFoundError(platformName, font.texture.name, "texture"); if (bmFontPath.Length == 0 || texturePath.Length == 0) continue; // not found // load the assets font.bmFont = AssetDatabase.LoadAssetAtPath(bmFontPath, typeof(UnityEngine.Object)); font.texture = AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D)) as Texture2D; } string targetDir = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(target)); // create necessary assets if (needFontData) { string srcPath = AssetDatabase.GetAssetPath(font.data); string destPath = AssetDatabase.GenerateUniqueAssetPath(GetCopyAtTargetPath(platformName, targetDir, srcPath)); AssetDatabase.CopyAsset(srcPath, destPath); AssetDatabase.Refresh(); font.data = AssetDatabase.LoadAssetAtPath(destPath, typeof(tk2dFontData)) as tk2dFontData; } if (needFontEditorData) { string srcPath = AssetDatabase.GetAssetPath(font.editorData); string destPath = AssetDatabase.GenerateUniqueAssetPath(GetCopyAtTargetPath(platformName, targetDir, srcPath)); AssetDatabase.CopyAsset(srcPath, destPath); AssetDatabase.Refresh(); font.editorData = AssetDatabase.LoadAssetAtPath(destPath, typeof(tk2dFont)) as tk2dFont; } if (font.editorData.bmFont != font.bmFont || font.editorData.texture != font.texture || font.editorData.data != font.data) { font.editorData.bmFont = font.bmFont; font.editorData.texture = font.texture; font.editorData.data = font.data; EditorUtility.SetDirty(font.editorData); } } proxy.CopyToTarget(target); } static string GetCopyAtTargetPath(string platformName, string targetDir, string srcPath) { string filename = System.IO.Path.GetFileNameWithoutExtension(srcPath); string ext = System.IO.Path.GetExtension(srcPath); string targetPath = targetDir + "/" + filename + "@" + platformName + ext; string destPath = AssetDatabase.GenerateUniqueAssetPath(targetPath); return destPath; } static void LogNotFoundError(string platformName, string assetName, string assetType) { Debug.LogError(string.Format("Unable to find platform specific {0} '{1}' for platform '{2}'", assetType, assetName, platformName)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net.Sockets; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.IO.Pipes { public abstract partial class PipeStream : Stream { // The Windows implementation of PipeStream sets the stream's handle during // creation, and as such should always have a handle, but the Unix implementation // sometimes sets the handle not during creation but later during connection. // As such, validation during member access needs to verify a valid handle on // Windows, but can't assume a valid handle on Unix. internal const bool CheckOperationsRequiresSetHandle = false; /// <summary>Characters that can't be used in a pipe's name.</summary> private readonly static char[] s_invalidFileNameChars = Path.GetInvalidFileNameChars(); /// <summary>Prefix to prepend to all pipe names.</summary> private readonly static string s_pipePrefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_"); internal static string GetPipePath(string serverName, string pipeName) { if (serverName != "." && serverName != Interop.Sys.GetHostName()) { // Cross-machine pipes are not supported. throw new PlatformNotSupportedException(SR.PlatformNotSupported_RemotePipes); } if (string.Equals(pipeName, AnonymousPipeName, StringComparison.OrdinalIgnoreCase)) { // Match Windows constraint throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved); } if (pipeName.IndexOfAny(s_invalidFileNameChars) >= 0) { // Since pipes are stored as files in the file system, we don't support // pipe names that are actually paths or that otherwise have invalid // filename characters in them. throw new PlatformNotSupportedException(SR.PlatformNotSupproted_InvalidNameChars); } // Return the pipe path. The pipe is created directly under %TMPDIR%. We don't bother // putting it into subdirectories, as the pipe will only exist on disk for the // duration between when the server starts listening and the client connects, after // which the pipe will be deleted. return s_pipePrefix + pipeName; } /// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary> /// <param name="safePipeHandle">The handle to validate.</param> internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { if (safePipeHandle.NamedPipeSocket == null) { Interop.Sys.FileStatus status; int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status)); if (result == 0) { if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO && (status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFSOCK) { throw new IOException(SR.IO_InvalidPipeHandle); } } } } /// <summary>Initializes the handle to be used asynchronously.</summary> /// <param name="handle">The handle.</param> [SecurityCritical] private void InitializeAsyncHandle(SafePipeHandle handle) { // nop } private void UninitializeAsyncHandle() { // nop } private unsafe int ReadCore(byte[] buffer, int offset, int count) { DebugAssertReadWriteArgs(buffer, offset, count, _handle); // For named pipes, receive on the socket. Socket socket = _handle.NamedPipeSocket; if (socket != null) { // For a blocking socket, we could simply use the same Read syscall as is done // for reading an anonymous pipe. However, for a non-blocking socket, Read could // end up returning EWOULDBLOCK rather than blocking waiting for data. Such a case // is already handled by Socket.Receive, so we use it here. try { return socket.Receive(buffer, offset, count, SocketFlags.None); } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } // For anonymous pipes, read from the file descriptor. fixed (byte* bufPtr = buffer) { int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr + offset, count)); Debug.Assert(result <= count); return result; } } private unsafe void WriteCore(byte[] buffer, int offset, int count) { DebugAssertReadWriteArgs(buffer, offset, count, _handle); // For named pipes, send to the socket. Socket socket = _handle.NamedPipeSocket; if (socket != null) { // For a blocking socket, we could simply use the same Write syscall as is done // for writing to anonymous pipe. However, for a non-blocking socket, Write could // end up returning EWOULDBLOCK rather than blocking waiting for space available. // Such a case is already handled by Socket.Send, so we use it here. try { while (count > 0) { int bytesWritten = socket.Send(buffer, offset, count, SocketFlags.None); Debug.Assert(bytesWritten <= count); count -= bytesWritten; offset += bytesWritten; } } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } // For anonymous pipes, write the file descriptor. fixed (byte* bufPtr = buffer) { while (count > 0) { int bytesWritten = CheckPipeCall(Interop.Sys.Write(_handle, bufPtr + offset, count)); Debug.Assert(bytesWritten <= count); count -= bytesWritten; offset += bytesWritten; } } } private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}"); Socket socket = InternalHandle.NamedPipeSocket; // If a cancelable token is used, we have a choice: we can either ignore it and use a true async operation // with Socket.ReceiveAsync, or we can use a polling loop on a worker thread to block for short intervals // and check for cancellation in between. We do the latter. if (cancellationToken.CanBeCanceled) { await Task.CompletedTask.ForceAsync(); // queue the remainder of the work to avoid blocking the caller int timeout = 10000; const int MaxTimeoutMicroseconds = 500000; while (true) { cancellationToken.ThrowIfCancellationRequested(); if (socket.Poll(timeout, SelectMode.SelectRead)) { return ReadCore(buffer, offset, count); } timeout = Math.Min(timeout * 2, MaxTimeoutMicroseconds); } } // The token wasn't cancelable, so we can simply use an async receive on the socket. try { return await socket.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false); } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}"); try { while (count > 0) { // cancellationToken is (mostly) ignored. We could institute a polling loop like we do for reads if // cancellationToken.CanBeCanceled, but that adds costs regardless of whether the operation will be canceled, and // most writes will complete immediately as they simply store data into the socket's buffer. The only time we end // up using it in a meaningful way is if a write completes partially, we'll check it on each individual write operation. cancellationToken.ThrowIfCancellationRequested(); int bytesWritten = await _handle.NamedPipeSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false); Debug.Assert(bytesWritten <= count); count -= bytesWritten; offset += bytesWritten; } } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } private IOException GetIOExceptionForSocketException(SocketException e) { if (e.SocketErrorCode == SocketError.Shutdown) // EPIPE { State = PipeState.Broken; } return new IOException(e.Message, e); } // Blocks until the other end of the pipe has read in all written buffer. [SecurityCritical] public void WaitForPipeDrain() { CheckWriteOperations(); if (!CanWrite) { throw Error.GetWriteNotSupported(); } // For named pipes on sockets, we could potentially partially implement this // via ioctl and TIOCOUTQ, which provides the number of unsent bytes. However, // that would require polling, and it wouldn't actually mean that the other // end has read all of the data, just that the data has left this end's buffer. throw new PlatformNotSupportedException(); } // Gets the transmission mode for the pipe. This is virtual so that subclassing types can // override this in cases where only one mode is legal (such as anonymous pipes) public virtual PipeTransmissionMode TransmissionMode { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } } // Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read // access. If that passes, call to GetNamedPipeInfo will succeed. public virtual int InBufferSize { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] get { CheckPipePropertyOperations(); if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } return GetPipeBufferSize(); } } // Gets the buffer size in the outbound direction for the pipe. This uses cached version // if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe. // However, returning cached is good fallback, especially if user specified a value in // the ctor. public virtual int OutBufferSize { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); if (!CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } return GetPipeBufferSize(); } } public virtual PipeTransmissionMode ReadMode { [SecurityCritical] get { CheckPipePropertyOperations(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] set { CheckPipePropertyOperations(); if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg); } if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based { throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode); } // nop, since it's already the only valid value } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary> /// We want to ensure that only one asynchronous operation is actually in flight /// at a time. The base Stream class ensures this by serializing execution via a /// semaphore. Since we don't delegate to the base stream for Read/WriteAsync due /// to having specialized support for cancellation, we do the same serialization here. /// </summary> private SemaphoreSlim _asyncActiveSemaphore; private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } private static void CreateDirectory(string directoryPath) { int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.Mask); // If successful created, we're done. if (result >= 0) return; // If the directory already exists, consider it a success. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EEXIST) return; // Otherwise, fail. throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true); } /// <summary>Creates an anonymous pipe.</summary> /// <param name="inheritability">The inheritability to try to use. This may not always be honored, depending on platform.</param> /// <param name="reader">The resulting reader end of the pipe.</param> /// <param name="writer">The resulting writer end of the pipe.</param> internal static unsafe void CreateAnonymousPipe( HandleInheritability inheritability, out SafePipeHandle reader, out SafePipeHandle writer) { // Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations reader = new SafePipeHandle(); writer = new SafePipeHandle(); // Create the OS pipe int* fds = stackalloc int[2]; CreateAnonymousPipe(inheritability, fds); // Store the file descriptors into our safe handles reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]); writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]); } internal int CheckPipeCall(int result) { if (result == -1) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EPIPE) State = PipeState.Broken; throw Interop.GetExceptionForIoErrno(errorInfo); } return result; } private int GetPipeBufferSize() { if (!Interop.Sys.Fcntl.CanGetSetPipeSz) { throw new PlatformNotSupportedException(); } // If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction). // If we don't, just return the buffer size that was passed to the constructor. return _handle != null ? CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) : _outBufferSize; } internal static unsafe void CreateAnonymousPipe(HandleInheritability inheritability, int* fdsptr) { var flags = (inheritability & HandleInheritability.Inheritable) == 0 ? Interop.Sys.PipeFlags.O_CLOEXEC : 0; Interop.CheckIo(Interop.Sys.Pipe(fdsptr, flags)); } internal static void ConfigureSocket( Socket s, SafePipeHandle pipeHandle, PipeDirection direction, int inBufferSize, int outBufferSize, HandleInheritability inheritability) { if (inBufferSize > 0) { s.ReceiveBufferSize = inBufferSize; } if (outBufferSize > 0) { s.SendBufferSize = outBufferSize; } if (inheritability != HandleInheritability.Inheritable) { Interop.Sys.Fcntl.SetCloseOnExec(pipeHandle); // ignore failures, best-effort attempt } switch (direction) { case PipeDirection.In: s.Shutdown(SocketShutdown.Send); break; case PipeDirection.Out: s.Shutdown(SocketShutdown.Receive); break; } } } }
// Copyright (C) 2014 dot42 // // Original filename: Regex.cs // // 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.Text.RegularExpressions.Internal; using Java.Util.Regex; namespace System.Text.RegularExpressions { public class Regex { [NonSerializedAttribute] public static readonly TimeSpan InfiniteMatchTimeout = TimeSpan.MaxValue; private PatternConverter patternConverter; private RegexOptions options; private TimeSpan matchTimeout; public Regex() { } public Regex(string pattern) :this(pattern, RegexOptions.None) { } public Regex(string pattern, RegexOptions options) :this(pattern, options, Regex.InfiniteMatchTimeout) { } public Regex(string pattern, RegexOptions options, TimeSpan matchTimeout) { patternConverter = new PatternConverter(pattern, options); this.options = options; this.matchTimeout = matchTimeout; } internal PatternConverter PatternConverter { get { return patternConverter; } } public RegexOptions Options { get { return options; } } /// <summary> /// Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor. /// </summary> public Match Match(string input) { return Match(input, 0); } /// <summary> /// Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor. /// </summary> public Match Match(string input, int startat) { return Match(input, startat, input.Length - startat); } /// <summary> /// Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor. /// </summary> public Match Match(string input, int beginning, int length) { var text = input.Substring(beginning, length); var pattern = Pattern.Compile(patternConverter.JavaPattern, JavaFlags(options)); var matcher = pattern.Matcher(text); return new Match(text, matcher, this, 0); } public static Match Match(string input, string pattern) { return Match(input, pattern, RegexOptions.None); } public static Match Match(string input, string pattern, RegexOptions options) { return Match(input, pattern, options, InfiniteMatchTimeout); } public static Match Match(string input, string pattern, RegexOptions options, TimeSpan matchTimeout) { var regex = new Regex(pattern, options, matchTimeout); return regex.Match(input); } /// <summary> /// Indicates whether the regular expression finds a match in the input string. /// </summary> public bool IsMatch(string input) { return Match(input).Success; } /// <summary> /// Indicates whether the regular expression finds a match in the input string. /// </summary> public bool IsMatch(string input, int startat) { return Match(input, startat).Success; } public static bool IsMatch(string input, string pattern) { return IsMatch(input, pattern, RegexOptions.None); } public static bool IsMatch(string input, string pattern, RegexOptions options) { return IsMatch(input, pattern, options, InfiniteMatchTimeout); } public static bool IsMatch(string input, string pattern, RegexOptions options, TimeSpan matchTimeout) { return Match(input, pattern, options, matchTimeout).Success; } public MatchCollection Matches(string input) { var pattern = Pattern.Compile(patternConverter.JavaPattern, JavaFlags(options)); var matcher = pattern.Matcher(input); return new MatchCollection(input, matcher, this); } public string Replace(string input, MatchEvaluator evaluator) { if(input == null) throw new ArgumentNullException("input"); if (evaluator == null) throw new ArgumentNullException("evaluator"); var builder = new StringBuilder(input.Length); var index = 0; foreach (Match match in Matches(input)) //only success matches are in the collection { builder.Append(input.Substring(index, match.Index - index)); builder.Append(evaluator(match)); index += match.Length; } builder.Append(input.Substring(index)); return input; } public string Replace(string input, string replacement) { if (input == null) throw new ArgumentNullException("input"); if (replacement == null) throw new ArgumentNullException("replacement"); var pattern = Pattern.Compile(patternConverter.JavaPattern, JavaFlags(options)); var matcher = pattern.Matcher(input); return matcher.ReplaceAll(replacement); } public int GroupNumberFromName(string name) { return patternConverter.PatternMap.GroupNumberFromName(name); } public int[] GetGroupNumbers() { return patternConverter.PatternMap.GetGroupNumbers(); } private static int JavaFlags(RegexOptions options) { int result = 0; if (HasEnabled(options, RegexOptions.IgnoreCase)) result += Pattern.CASE_INSENSITIVE; if (HasEnabled(options, RegexOptions.Multiline)) result += Pattern.MULTILINE; if (HasEnabled(options, RegexOptions.Singleline)) result += Pattern.DOTALL; if (HasEnabled(options, RegexOptions.IgnorePatternWhitespace)) result += Pattern.COMMENTS; if (HasEnabled(options, RegexOptions.CultureInvariant)) result += Pattern.UNICODE_CASE; if (HasEnabled(options, RegexOptions.RightToLeft)) throw new NotSupportedException("RightToLeft option in regular expression is not supported"); return result; } private static bool HasEnabled(RegexOptions options, RegexOptions flag) { return (options & flag) == flag; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Roslyn.Utilities; using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal abstract partial class AbstractCodeModelService : ICodeModelService { private readonly ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>> _treeToNodeKeyMaps = new ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>>(); protected readonly ISyntaxFactsService SyntaxFactsService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; private readonly AbstractNodeNameGenerator _nodeNameGenerator; private readonly AbstractNodeLocator _nodeLocator; private readonly AbstractCodeModelEventCollector _eventCollector; private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; private readonly IFormattingRule _lineAdjustmentFormattingRule; private readonly IFormattingRule _endRegionFormattingRule; protected AbstractCodeModelService( HostLanguageServices languageServiceProvider, IEditorOptionsFactoryService editorOptionsFactoryService, IEnumerable<IRefactorNotifyService> refactorNotifyServices, IFormattingRule lineAdjustmentFormattingRule, IFormattingRule endRegionFormattingRule) { Debug.Assert(languageServiceProvider != null); Debug.Assert(editorOptionsFactoryService != null); this.SyntaxFactsService = languageServiceProvider.GetService<ISyntaxFactsService>(); _editorOptionsFactoryService = editorOptionsFactoryService; _lineAdjustmentFormattingRule = lineAdjustmentFormattingRule; _endRegionFormattingRule = endRegionFormattingRule; _refactorNotifyServices = refactorNotifyServices; _nodeNameGenerator = CreateNodeNameGenerator(); _nodeLocator = CreateNodeLocator(); _eventCollector = CreateCodeModelEventCollector(); } protected string GetNewLineCharacter(SourceText text) { return _editorOptionsFactoryService.GetEditorOptions(text).GetNewLineCharacter(); } protected int GetTabSize(SourceText text) { var snapshot = text.FindCorrespondingEditorTextSnapshot(); return GetTabSize(snapshot); } protected int GetTabSize(ITextSnapshot snapshot) { if (snapshot == null) { throw new ArgumentNullException(nameof(snapshot)); } var textBuffer = snapshot.TextBuffer; return _editorOptionsFactoryService.GetOptions(textBuffer).GetTabSize(); } protected SyntaxToken GetTokenWithoutAnnotation(SyntaxToken current, Func<SyntaxToken, SyntaxToken> nextTokenGetter) { while (current.ContainsAnnotations) { current = nextTokenGetter(current); } return current; } protected TextSpan GetEncompassingSpan(SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken) { var startPosition = startToken.SpanStart; var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End; return TextSpan.FromBounds(startPosition, endPosition); } private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> BuildNodeKeyMap(SyntaxTree syntaxTree) { var nameOrdinalMap = new Dictionary<string, int>(); var nodeKeyMap = BidirectionalMap<SyntaxNodeKey, SyntaxNode>.Empty; foreach (var node in GetFlattenedMemberNodes(syntaxTree)) { var name = _nodeNameGenerator.GenerateName(node); int ordinal; if (!nameOrdinalMap.TryGetValue(name, out ordinal)) { ordinal = 0; } nameOrdinalMap[name] = ++ordinal; var key = new SyntaxNodeKey(name, ordinal); nodeKeyMap = nodeKeyMap.Add(key, node); } return nodeKeyMap; } private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> GetNodeKeyMap(SyntaxTree syntaxTree) { return _treeToNodeKeyMaps.GetValue(syntaxTree, BuildNodeKeyMap); } public SyntaxNodeKey GetNodeKey(SyntaxNode node) { var nodeKey = TryGetNodeKey(node); if (nodeKey.IsEmpty) { throw new ArgumentException(); } return nodeKey; } public SyntaxNodeKey TryGetNodeKey(SyntaxNode node) { var nodeKeyMap = GetNodeKeyMap(node.SyntaxTree); SyntaxNodeKey nodeKey; if (!nodeKeyMap.TryGetKey(node, out nodeKey)) { return SyntaxNodeKey.Empty; } return nodeKey; } public SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree) { var nodeKeyMap = GetNodeKeyMap(syntaxTree); SyntaxNode node; if (!nodeKeyMap.TryGetValue(nodeKey, out node)) { throw new ArgumentException(); } return node; } public bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node) { var nodeKeyMap = GetNodeKeyMap(syntaxTree); return nodeKeyMap.TryGetValue(nodeKey, out node); } public abstract bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope); public abstract IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent); protected IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxTree syntaxTree) { return GetMemberNodes(syntaxTree.GetRoot(), includeSelf: true, recursive: true, logicalFields: true, onlySupportedNodes: true); } protected IEnumerable<SyntaxNode> GetLogicalMemberNodes(SyntaxNode container) { return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: false); } public IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container) { return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: true); } /// <summary> /// Retrieves the members of a specified <paramref name="container"/> node. The members that are /// returned can be controlled by passing various parameters. /// </summary> /// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param> /// <param name="includeSelf">If true, the container is returned as well.</param> /// <param name="recursive">If true, members are recursed to return descendant members as well /// as immediate children. For example, a namespace would return the namespaces and types within. /// However, if <paramref name="recursive"/> is true, members with the namespaces and types would /// also be returned.</param> /// <param name="logicalFields">If true, field declarations are broken into their respective declarators. /// For example, the field "int x, y" would return two declarators, one for x and one for y in place /// of the field.</param> /// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param> public abstract IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes); public abstract string Language { get; } public abstract string AssemblyAttributeString { get; } public EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: return (EnvDTE.CodeElement)ExternalCodeEvent.Create(state, projectId, (IEventSymbol)symbol); case SymbolKind.Field: return (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, (IFieldSymbol)symbol); case SymbolKind.Method: return (EnvDTE.CodeElement)ExternalCodeFunction.Create(state, projectId, (IMethodSymbol)symbol); case SymbolKind.Namespace: return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, (INamespaceSymbol)symbol); case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)symbol; switch (namedType.TypeKind) { case TypeKind.Class: case TypeKind.Module: return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, namedType); case TypeKind.Delegate: return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, namedType); case TypeKind.Enum: return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, namedType); case TypeKind.Interface: return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, namedType); case TypeKind.Struct: return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, namedType); default: throw Exceptions.ThrowEFail(); } case SymbolKind.Property: var propertySymbol = (IPropertySymbol)symbol; return propertySymbol.IsWithEvents ? (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, propertySymbol) : (EnvDTE.CodeElement)ExternalCodeProperty.Create(state, projectId, (IPropertySymbol)symbol); default: throw Exceptions.ThrowEFail(); } } /// <summary> /// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/> /// </summary> public abstract EnvDTE.CodeElement CreateInternalCodeElement( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); public EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) { if (typeSymbol.TypeKind == TypeKind.Pointer || typeSymbol.TypeKind == TypeKind.TypeParameter || typeSymbol.TypeKind == TypeKind.Submission) { throw Exceptions.ThrowEFail(); } if (typeSymbol.TypeKind == TypeKind.Error || typeSymbol.TypeKind == TypeKind.Unknown) { return ExternalCodeUnknown.Create(state, projectId, typeSymbol); } var project = state.Workspace.CurrentSolution.GetProject(projectId); if (project == null) { throw Exceptions.ThrowEFail(); } if (typeSymbol.TypeKind == TypeKind.Dynamic) { var obj = project.GetCompilationAsync().Result.GetSpecialType(SpecialType.System_Object); return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, obj); } EnvDTE.CodeElement element; if (TryGetElementFromSource(state, project, typeSymbol, out element)) { return element; } EnvDTE.vsCMElement elementKind = GetElementKind(typeSymbol); switch (elementKind) { case EnvDTE.vsCMElement.vsCMElementClass: case EnvDTE.vsCMElement.vsCMElementModule: return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementInterface: return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementDelegate: return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementEnum: return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementStruct: return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, typeSymbol); default: Debug.Fail("Unsupported element kind: " + elementKind); throw Exceptions.ThrowEInvalidArg(); } } public abstract EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type); public abstract EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol); public abstract string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol); public abstract string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol); public abstract bool IsParameterNode(SyntaxNode node); public abstract bool IsAttributeNode(SyntaxNode node); public abstract bool IsAttributeArgumentNode(SyntaxNode node); public abstract bool IsOptionNode(SyntaxNode node); public abstract bool IsImportNode(SyntaxNode node); public ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId) { var project = workspace.CurrentSolution.GetProject(projectId); if (project == null) { throw Exceptions.ThrowEFail(); } return symbolId.Resolve(project.GetCompilationAsync().Result).Symbol; } protected EnvDTE.CodeFunction CreateInternalCodeAccessorFunction(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); var accessorKind = GetAccessorKind(node); return CodeAccessorFunction.Create(state, parentObj, accessorKind); } protected EnvDTE.CodeAttribute CreateInternalCodeAttribute(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { var parentNode = GetEffectiveParentForAttribute(node); AbstractCodeElement parentObject; if (IsParameterNode(parentNode)) { var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement); } else { var nodeKey = parentNode.AncestorsAndSelf() .Select(n => TryGetNodeKey(n)) .FirstOrDefault(nk => nk != SyntaxNodeKey.Empty); if (nodeKey == SyntaxNodeKey.Empty) { // This is an assembly-level attribute. parentNode = fileCodeModel.GetSyntaxRoot(); parentObject = null; } else { parentNode = fileCodeModel.LookupNode(nodeKey); var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement); } } string name; int ordinal; GetAttributeNameAndOrdinal(parentNode, node, out name, out ordinal); return CodeAttribute.Create(state, fileCodeModel, parentObject, name, ordinal); } protected EnvDTE80.CodeImport CreateInternalCodeImport(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode; string name; GetImportParentAndName(node, out parentNode, out name); AbstractCodeElement parentObj = null; if (parentNode != null) { var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); parentObj = ComAggregate.GetManagedObject<AbstractCodeElement>(parent); } return CodeImport.Create(state, fileCodeModel, parentObj, name); } protected EnvDTE.CodeParameter CreateInternalCodeParameter(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } string name = GetParameterName(node); var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); return CodeParameter.Create(state, parentObj, name); } protected EnvDTE80.CodeElement2 CreateInternalCodeOptionStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { string name; int ordinal; GetOptionNameAndOrdinal(node.Parent, node, out name, out ordinal); return CodeOptionsStatement.Create(state, fileCodeModel, name, ordinal); } protected EnvDTE80.CodeElement2 CreateInternalCodeInheritsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } string namespaceName; int ordinal; GetInheritsNamespaceAndOrdinal(parentNode, node, out namespaceName, out ordinal); var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); return CodeInheritsStatement.Create(state, parentObj, namespaceName, ordinal); } protected EnvDTE80.CodeElement2 CreateInternalCodeImplementsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } string namespaceName; int ordinal; GetImplementsNamespaceAndOrdinal(parentNode, node, out namespaceName, out ordinal); var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); return CodeImplementsStatement.Create(state, parentObj, namespaceName, ordinal); } protected EnvDTE80.CodeAttributeArgument CreateInternalCodeAttributeArgument(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode attributeNode; int index; GetAttributeArgumentParentAndIndex(node, out attributeNode, out index); var codeAttribute = CreateInternalCodeAttribute(state, fileCodeModel, attributeNode); var codeAttributeObj = ComAggregate.GetManagedObject<CodeAttribute>(codeAttribute); return CodeAttributeArgument.Create(state, codeAttributeObj, index); } public abstract EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); public abstract EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel); public abstract string GetUnescapedName(string name); public abstract string GetName(SyntaxNode node); public abstract SyntaxNode GetNodeWithName(SyntaxNode node); public abstract SyntaxNode SetName(SyntaxNode node, string name); public abstract string GetFullName(SyntaxNode node, SemanticModel semanticModel); public abstract string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel); public void Rename(ISymbol symbol, string newName, Solution solution) { // TODO: (tomescht) make this testable through unit tests. // Right now we have to go through the project system to find all // the outstanding CodeElements which might be affected by the // rename. This is silly. This functionality should be moved down // into the service layer. var workspace = solution.Workspace as VisualStudioWorkspaceImpl; if (workspace == null) { throw Exceptions.ThrowEFail(); } // Save the node keys. var nodeKeyValidation = new NodeKeyValidation(); foreach (var project in workspace.ProjectTracker.Projects) { nodeKeyValidation.AddProject(project); } // Rename symbol. var newSolution = Renamer.RenameSymbolAsync(solution, symbol, newName, solution.Options).WaitAndGetResult_CodeModel(CancellationToken.None); var changedDocuments = newSolution.GetChangedDocuments(solution); // Notify third parties of the coming rename operation and let exceptions propagate out _refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); // Update the workspace. if (!workspace.TryApplyChanges(newSolution)) { throw Exceptions.ThrowEFail(); } // Notify third parties of the completed rename operation and let exceptions propagate out _refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments); // Update the node keys. nodeKeyValidation.RestoreKeys(); } public abstract bool IsValidExternalSymbol(ISymbol symbol); public abstract string GetExternalSymbolName(ISymbol symbol); public abstract string GetExternalSymbolFullName(ISymbol symbol); public VirtualTreePoint? GetStartPoint(SyntaxNode node, EnvDTE.vsCMPart? part) { return _nodeLocator.GetStartPoint(node, part); } public VirtualTreePoint? GetEndPoint(SyntaxNode node, EnvDTE.vsCMPart? part) { return _nodeLocator.GetEndPoint(node, part); } public abstract EnvDTE.vsCMAccess GetAccess(ISymbol symbol); public abstract EnvDTE.vsCMAccess GetAccess(SyntaxNode node); public abstract SyntaxNode GetNodeWithModifiers(SyntaxNode node); public abstract SyntaxNode GetNodeWithType(SyntaxNode node); public abstract SyntaxNode GetNodeWithInitializer(SyntaxNode node); public abstract SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access); public abstract EnvDTE.vsCMElement GetElementKind(SyntaxNode node); protected EnvDTE.vsCMElement GetElementKind(ITypeSymbol typeSymbol) { switch (typeSymbol.TypeKind) { case TypeKind.Array: case TypeKind.Class: return EnvDTE.vsCMElement.vsCMElementClass; case TypeKind.Interface: return EnvDTE.vsCMElement.vsCMElementInterface; case TypeKind.Struct: return EnvDTE.vsCMElement.vsCMElementStruct; case TypeKind.Enum: return EnvDTE.vsCMElement.vsCMElementEnum; case TypeKind.Delegate: return EnvDTE.vsCMElement.vsCMElementDelegate; case TypeKind.Module: return EnvDTE.vsCMElement.vsCMElementModule; default: Debug.Fail("Unexpected TypeKind: " + typeSymbol.TypeKind); throw Exceptions.ThrowEInvalidArg(); } } protected bool TryGetElementFromSource(CodeModelState state, Project project, ITypeSymbol typeSymbol, out EnvDTE.CodeElement element) { element = null; if (!typeSymbol.IsDefinition) { return false; } // Here's the strategy for determine what source file we'd try to return an element from. // 1. Prefer source files that we don't heuristically flag as generated code. // 2. If all of the source files are generated code, pick the first one. var generatedCodeRecognitionService = project.Solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>(); Compilation compilation = null; Tuple<DocumentId, Location> generatedCode = null; DocumentId chosenDocumentId = null; Location chosenLocation = null; foreach (var location in typeSymbol.Locations) { if (location.IsInSource) { compilation = compilation ?? project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult_CodeModel(CancellationToken.None); if (compilation.ContainsSyntaxTree(location.SourceTree)) { var document = project.GetDocument(location.SourceTree); if (generatedCodeRecognitionService?.IsGeneratedCode(document) == false) { chosenLocation = location; chosenDocumentId = document.Id; break; } else { generatedCode = generatedCode ?? Tuple.Create(document.Id, location); } } } } if (chosenDocumentId == null && generatedCode != null) { chosenDocumentId = generatedCode.Item1; chosenLocation = generatedCode.Item2; } if (chosenDocumentId != null) { var fileCodeModel = state.Workspace.GetFileCodeModel(chosenDocumentId); if (fileCodeModel != null) { var underlyingFileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(fileCodeModel); element = underlyingFileCodeModel.CodeElementFromPosition(chosenLocation.SourceSpan.Start, GetElementKind(typeSymbol)); return element != null; } } return false; } public abstract bool IsAccessorNode(SyntaxNode node); public abstract MethodKind GetAccessorKind(SyntaxNode node); public abstract bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode); public abstract bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode); public abstract bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode); public abstract bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode); public abstract bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode); public abstract bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode); public abstract bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode); public abstract bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode); public abstract void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal); public abstract void GetInheritsNamespaceAndOrdinal(SyntaxNode inheritsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal); public abstract void GetImplementsNamespaceAndOrdinal(SyntaxNode implementsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal); public abstract void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal); public abstract SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode); public abstract string GetAttributeTarget(SyntaxNode attributeNode); public abstract string GetAttributeValue(SyntaxNode attributeNode); public abstract SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value); public abstract SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value); public abstract SyntaxNode GetNodeWithAttributes(SyntaxNode node); public abstract SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node); public abstract SyntaxNode CreateAttributeNode(string name, string value, string target = null); public abstract void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index); public abstract SyntaxNode CreateAttributeArgumentNode(string name, string value); public abstract string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode); public abstract string GetImportAlias(SyntaxNode node); public abstract string GetImportNamespaceOrType(SyntaxNode node); public abstract void GetImportParentAndName(SyntaxNode importNode, out SyntaxNode namespaceNode, out string name); public abstract SyntaxNode CreateImportNode(string name, string alias = null); public abstract string GetParameterName(SyntaxNode node); public virtual string GetParameterFullName(SyntaxNode node) { return GetParameterName(node); } public abstract EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node); public abstract SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind); public abstract EnvDTE80.vsCMParameterKind UpdateParameterKind(EnvDTE80.vsCMParameterKind parameterKind, PARAMETER_PASSING_MODE passingMode); public abstract SyntaxNode CreateParameterNode(string name, string type); public abstract EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name); public abstract bool SupportsEventThrower { get; } public abstract bool GetCanOverride(SyntaxNode memberNode); public abstract SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value); public abstract EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); public abstract SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind); public abstract string GetComment(SyntaxNode node); public abstract SyntaxNode SetComment(SyntaxNode node, string value); public abstract EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode); public abstract SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind); public abstract EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol); public abstract SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind); public abstract string GetDocComment(SyntaxNode node); public abstract SyntaxNode SetDocComment(SyntaxNode node, string value); public abstract EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol); public abstract EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); public abstract SyntaxNode SetInheritanceKind(SyntaxNode typeNode, EnvDTE80.vsCMInheritanceKind kind); public abstract bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol); public abstract SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value); public abstract bool GetIsConstant(SyntaxNode variableNode); public abstract SyntaxNode SetIsConstant(SyntaxNode variableNode, bool value); public abstract bool GetIsDefault(SyntaxNode propertyNode); public abstract SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value); public abstract bool GetIsGeneric(SyntaxNode memberNode); public abstract bool GetIsPropertyStyleEvent(SyntaxNode eventNode); public abstract bool GetIsShared(SyntaxNode memberNode, ISymbol symbol); public abstract SyntaxNode SetIsShared(SyntaxNode memberNode, bool value); public abstract bool GetMustImplement(SyntaxNode memberNode); public abstract SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value); public abstract EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode); public abstract SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind); public abstract EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode); public abstract SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol); public abstract Document Delete(Document document, SyntaxNode node); public abstract string GetMethodXml(SyntaxNode node, SemanticModel semanticModel); public abstract string GetInitExpression(SyntaxNode node); public abstract SyntaxNode AddInitExpression(SyntaxNode node, string value); public abstract CodeGenerationDestination GetDestination(SyntaxNode containerNode); protected abstract Accessibility GetDefaultAccessibility(SymbolKind targetSymbolKind, CodeGenerationDestination destination); public Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified) { // Note: Some EnvDTE.vsCMAccess members aren't "bitwise-mutually-exclusive" // Specifically, vsCMAccessProjectOrProtected (12) is a combination of vsCMAccessProject (4) and vsCMAccessProtected (8) // We therefore check for this first. if ((access & EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) == EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) { return Accessibility.ProtectedOrInternal; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessPrivate) != 0) { return Accessibility.Private; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessProject) != 0) { return Accessibility.Internal; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessProtected) != 0) { return Accessibility.Protected; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessPublic) != 0) { return Accessibility.Public; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessDefault) != 0) { return GetDefaultAccessibility(targetSymbolKind, destination); } else { throw new ArgumentException(ServicesVSResources.InvalidAccess, nameof(access)); } } public bool GetWithEvents(EnvDTE.vsCMAccess access) { return (access & EnvDTE.vsCMAccess.vsCMAccessWithEvents) != 0; } protected SpecialType GetSpecialType(EnvDTE.vsCMTypeRef type) { // TODO(DustinCa): Verify this list against VB switch (type) { case EnvDTE.vsCMTypeRef.vsCMTypeRefBool: return SpecialType.System_Boolean; case EnvDTE.vsCMTypeRef.vsCMTypeRefByte: return SpecialType.System_Byte; case EnvDTE.vsCMTypeRef.vsCMTypeRefChar: return SpecialType.System_Char; case EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal: return SpecialType.System_Decimal; case EnvDTE.vsCMTypeRef.vsCMTypeRefDouble: return SpecialType.System_Double; case EnvDTE.vsCMTypeRef.vsCMTypeRefFloat: return SpecialType.System_Single; case EnvDTE.vsCMTypeRef.vsCMTypeRefInt: return SpecialType.System_Int32; case EnvDTE.vsCMTypeRef.vsCMTypeRefLong: return SpecialType.System_Int64; case EnvDTE.vsCMTypeRef.vsCMTypeRefObject: return SpecialType.System_Object; case EnvDTE.vsCMTypeRef.vsCMTypeRefShort: return SpecialType.System_Int16; case EnvDTE.vsCMTypeRef.vsCMTypeRefString: return SpecialType.System_String; case EnvDTE.vsCMTypeRef.vsCMTypeRefVoid: return SpecialType.System_Void; default: // TODO: Support vsCMTypeRef2? It doesn't appear that Dev10 C# does... throw new ArgumentException(); } } private ITypeSymbol GetSpecialType(EnvDTE.vsCMTypeRef type, Compilation compilation) { return compilation.GetSpecialType(GetSpecialType(type)); } protected abstract ITypeSymbol GetTypeSymbolFromPartialName(string partialName, SemanticModel semanticModel, int position); public abstract ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation); public ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position) { if (type is EnvDTE.CodeTypeRef) { return GetTypeSymbolFromPartialName(((EnvDTE.CodeTypeRef)type).AsString, semanticModel, position); } else if (type is EnvDTE.CodeType) { return GetTypeSymbolFromFullName(((EnvDTE.CodeType)type).FullName, semanticModel.Compilation); } ITypeSymbol typeSymbol; if (type is EnvDTE.vsCMTypeRef || type is int) { typeSymbol = GetSpecialType((EnvDTE.vsCMTypeRef)type, semanticModel.Compilation); } else if (type is string) { typeSymbol = GetTypeSymbolFromPartialName((string)type, semanticModel, position); } else { throw new InvalidOperationException(); } if (typeSymbol == null) { throw new ArgumentException(); } return typeSymbol; } public abstract SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type); protected abstract int GetAttributeIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); /// <summary> /// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string /// representing the name of a member. This function translates the argument and returns the /// 1-based position of the specified attribute. /// </summary> public int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetAttributeIndexInContainer, GetAttributeNodes); } protected abstract int GetAttributeArgumentIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); public int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetAttributeArgumentIndexInContainer, GetAttributeArgumentNodes); } protected abstract int GetImportIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); public int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetImportIndexInContainer, GetImportNodes); } protected abstract int GetParameterIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); public int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetParameterIndexInContainer, GetParameterNodes); } /// <summary> /// Finds the index of the first child within the container for which <paramref name="predicate"/> returns true. /// Note that the result is a 1-based as that is what code model expects. Returns -1 if no match is found. /// </summary> protected abstract int GetMemberIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); /// <summary> /// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string /// representing the name of a member. This function translates the argument and returns the /// 1-based position of the specified member. /// </summary> public int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetMemberIndexInContainer, n => GetMemberNodes(n, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false)); } private int PositionVariantToInsertionIndex( object position, SyntaxNode containerNode, FileCodeModel fileCodeModel, Func<SyntaxNode, Func<SyntaxNode, bool>, int> getIndexInContainer, Func<SyntaxNode, IEnumerable<SyntaxNode>> getChildNodes) { int result; if (position is int) { result = (int)position; } else if (position is EnvDTE.CodeElement) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(position); if (codeElement == null || codeElement.FileCodeModel != fileCodeModel) { throw Exceptions.ThrowEInvalidArg(); } var positionNode = codeElement.LookupNode(); if (positionNode == null) { throw Exceptions.ThrowEFail(); } result = getIndexInContainer(containerNode, child => child == positionNode); } else if (position is string) { var name = (string)position; result = getIndexInContainer(containerNode, child => GetName(child) == name); } else if (position == null || position == Type.Missing) { result = 0; } else { // Nothing we can handle... throw Exceptions.ThrowEInvalidArg(); } // -1 means to insert at the end, so we'll return the last child. return result == -1 ? getChildNodes(containerNode).ToArray().Length : result; } protected abstract SyntaxNode GetFieldFromVariableNode(SyntaxNode variableNode); protected abstract SyntaxNode GetVariableFromFieldNode(SyntaxNode fieldNode); protected abstract SyntaxNode GetAttributeFromAttributeDeclarationNode(SyntaxNode attributeDeclarationNode); protected void GetNodesAroundInsertionIndex<TSyntaxNode>( TSyntaxNode containerNode, int childIndexToInsertAfter, out TSyntaxNode insertBeforeNode, out TSyntaxNode insertAfterNode) where TSyntaxNode : SyntaxNode { var childNodes = GetLogicalMemberNodes(containerNode).ToArray(); // Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members. // If it isn't 0, it means to insert the member node *after* the node at the 1-based index. Debug.Assert(childIndexToInsertAfter >= 0 && childIndexToInsertAfter <= childNodes.Length); // Initialize the nodes that we'll insert the new member before and after. insertBeforeNode = null; insertAfterNode = null; if (childIndexToInsertAfter == 0) { if (childNodes.Length > 0) { insertBeforeNode = (TSyntaxNode)childNodes[0]; } } else { insertAfterNode = (TSyntaxNode)childNodes[childIndexToInsertAfter - 1]; if (childIndexToInsertAfter < childNodes.Length) { insertBeforeNode = (TSyntaxNode)childNodes[childIndexToInsertAfter]; } } if (insertBeforeNode != null) { insertBeforeNode = (TSyntaxNode)GetFieldFromVariableNode(insertBeforeNode); } if (insertAfterNode != null) { insertAfterNode = (TSyntaxNode)GetFieldFromVariableNode(insertAfterNode); } } private int GetMemberInsertionIndex(SyntaxNode container, int insertionIndex) { var childNodes = GetLogicalMemberNodes(container).ToArray(); // Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members. // If it isn't 0, it means to insert the member node *after* the node at the 1-based index. Debug.Assert(insertionIndex >= 0 && insertionIndex <= childNodes.Length); if (insertionIndex == 0) { return 0; } else { var nodeAtIndex = GetFieldFromVariableNode(childNodes[insertionIndex - 1]); return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false).ToList().IndexOf(nodeAtIndex) + 1; } } private int GetAttributeArgumentInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } private int GetAttributeInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } private int GetImportInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } private int GetParameterInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } protected abstract bool IsCodeModelNode(SyntaxNode node); protected abstract TextSpan GetSpanToFormat(SyntaxNode root, TextSpan span); protected abstract SyntaxNode InsertMemberNodeIntoContainer(int index, SyntaxNode member, SyntaxNode container); protected abstract SyntaxNode InsertAttributeArgumentIntoContainer(int index, SyntaxNode attributeArgument, SyntaxNode container); protected abstract SyntaxNode InsertAttributeListIntoContainer(int index, SyntaxNode attribute, SyntaxNode container); protected abstract SyntaxNode InsertImportIntoContainer(int index, SyntaxNode import, SyntaxNode container); protected abstract SyntaxNode InsertParameterIntoContainer(int index, SyntaxNode parameter, SyntaxNode container); private Document FormatAnnotatedNode(Document document, SyntaxAnnotation annotation, IEnumerable<IFormattingRule> additionalRules, CancellationToken cancellationToken) { var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult_CodeModel(cancellationToken); var annotatedNode = root.GetAnnotatedNodesAndTokens(annotation).Single().AsNode(); var formattingSpan = GetSpanToFormat(root, annotatedNode.FullSpan); var formattingRules = Formatter.GetDefaultFormattingRules(document); if (additionalRules != null) { formattingRules = additionalRules.Concat(formattingRules); } return Formatter.FormatAsync( document, new TextSpan[] { formattingSpan }, options: null, rules: formattingRules, cancellationToken: cancellationToken).WaitAndGetResult_CodeModel(cancellationToken); } private SyntaxNode InsertNode( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode node, Func<int, SyntaxNode, SyntaxNode, SyntaxNode> insertNodeIntoContainer, CancellationToken cancellationToken, out Document newDocument) { var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult_CodeModel(cancellationToken); // Annotate the member we're inserting so we can get back to it. var annotation = new SyntaxAnnotation(); var gen = SyntaxGenerator.GetGenerator(document); node = node.WithAdditionalAnnotations(annotation); if (gen.GetDeclarationKind(node) != DeclarationKind.NamespaceImport) { // REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before? node = node.WithAdditionalAnnotations(Simplifier.Annotation); } var newContainerNode = insertNodeIntoContainer(insertionIndex, node, containerNode); var newRoot = root.ReplaceNode(containerNode, newContainerNode); document = document.WithSyntaxRoot(newRoot); if (!batchMode) { document = Simplifier.ReduceAsync(document, annotation, optionSet: null, cancellationToken: cancellationToken).WaitAndGetResult_CodeModel(cancellationToken); } document = FormatAnnotatedNode(document, annotation, new[] { _lineAdjustmentFormattingRule, _endRegionFormattingRule }, cancellationToken); // out param newDocument = document; // new node return document .GetSyntaxRootAsync(cancellationToken).WaitAndGetResult_CodeModel(cancellationToken) .GetAnnotatedNodesAndTokens(annotation) .Single() .AsNode(); } /// <summary> /// Override to determine whether <param name="newNode"/> adds a method body to <param name="node"/>. /// This is used to determine whether a blank line should be added inside the body when formatting. /// </summary> protected abstract bool AddBlankLineToMethodBody(SyntaxNode node, SyntaxNode newNode); public Document UpdateNode( Document document, SyntaxNode node, SyntaxNode newNode, CancellationToken cancellationToken) { // Annotate the member we're inserting so we can get back to it. var annotation = new SyntaxAnnotation(); // REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before? var annotatedNode = newNode.WithAdditionalAnnotations(annotation, Simplifier.Annotation); var oldRoot = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult_CodeModel(cancellationToken); var newRoot = oldRoot.ReplaceNode(node, annotatedNode); document = document.WithSyntaxRoot(newRoot); var additionalRules = AddBlankLineToMethodBody(node, newNode) ? SpecializedCollections.SingletonEnumerable(_lineAdjustmentFormattingRule) : null; document = FormatAnnotatedNode(document, annotation, additionalRules, cancellationToken); return document; } public SyntaxNode InsertAttribute( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetAttributeInsertionIndex(containerNode, insertionIndex), containerNode, attributeNode, InsertAttributeListIntoContainer, cancellationToken, out newDocument); return GetAttributeFromAttributeDeclarationNode(finalNode); } public SyntaxNode InsertAttributeArgument( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeArgumentNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetAttributeArgumentInsertionIndex(containerNode, insertionIndex), containerNode, attributeArgumentNode, InsertAttributeArgumentIntoContainer, cancellationToken, out newDocument); return finalNode; } public SyntaxNode InsertImport( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode importNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetImportInsertionIndex(containerNode, insertionIndex), containerNode, importNode, InsertImportIntoContainer, cancellationToken, out newDocument); return finalNode; } public SyntaxNode InsertParameter( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode parameterNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetParameterInsertionIndex(containerNode, insertionIndex), containerNode, parameterNode, InsertParameterIntoContainer, cancellationToken, out newDocument); return finalNode; } public SyntaxNode InsertMember( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode memberNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetMemberInsertionIndex(containerNode, insertionIndex), containerNode, memberNode, InsertMemberNodeIntoContainer, cancellationToken, out newDocument); return GetVariableFromFieldNode(finalNode); } public Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree) { return _eventCollector.Collect(oldTree, newTree); } public abstract bool IsNamespace(SyntaxNode node); public abstract bool IsType(SyntaxNode node); public virtual IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel) { // descendants may override (particularly VB). return SpecializedCollections.EmptyList<string>(); } public virtual bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel) { // descendants may override (particularly VB). return false; } public virtual Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken) { // descendants may override (particularly VB). return document; } public virtual Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken) { // descendants may override (particularly VB). return document; } public abstract string[] GetFunctionExtenderNames(); public abstract object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol); public abstract string[] GetPropertyExtenderNames(); public abstract object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol); public abstract string[] GetExternalTypeExtenderNames(); public abstract object GetExternalTypeExtender(string name, string externalLocation); public abstract string[] GetTypeExtenderNames(); public abstract object GetTypeExtender(string name, AbstractCodeType codeType); public abstract bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol); public abstract SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); public abstract SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); public abstract bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol); public abstract SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); public abstract SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); public abstract string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags); public virtual void AttachFormatTrackingToBuffer(ITextBuffer buffer) { // can be override by languages if needed } public virtual void DetachFormatTrackingToBuffer(ITextBuffer buffer) { // can be override by languages if needed } public virtual void EnsureBufferFormatted(ITextBuffer buffer) { // can be override by languages if needed } } }
using System; using System.CodeDom; using System.Collections.Generic; using System.Linq; using Xunit; namespace QuickGrid.Tests { public class QueryFilterParsingTests { private readonly IQueryable<ListItem> _items; public class ListItem { public string Value { get; set; } public DateTime Date { get; set; } public int Numeric { get; set; } } public QueryFilterParsingTests() { _items = new List<ListItem>() { new ListItem() {Value = "One", Date = DateTime.UtcNow.AddYears(-5), Numeric = 50}, new ListItem() {Value = "Two", Date = DateTime.UtcNow.AddYears(-4), Numeric = 40}, new ListItem() {Value = "Three", Date = DateTime.UtcNow.AddYears(-3), Numeric = 30}, new ListItem() {Value = "Four", Date = DateTime.UtcNow.AddYears(-2), Numeric = 20}, new ListItem() {Value = "Five", Date = DateTime.UtcNow.AddYears(-1), Numeric = 10}, }.AsQueryable(); } [Fact] public void CanCorrectlyParseEqualsExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Value", "=two"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("Value == \"two\"", list.Expression.ToString()); } [Fact] public void CanCorrectlyParseContainsExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Value", "%two%"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("Value.Contains(\"two\")", list.Expression.ToString()); } [Fact] public void CanCorrectlyParseStartsWithExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Value", "two%"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("Value.StartsWith(\"two\")", list.Expression.ToString()); } [Fact] public void CanCorrectlyParseEndsWithExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Value", "%two"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("Value.EndsWith(\"two\")", list.Expression.ToString()); } [Fact] public void CanCorrectlyParseContainsArrayExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Value", "(one,two)"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("new [] {\"one\", \"two\"}.Contains(r.Value)", list.Expression.ToString()); } [Fact] public void CanCorrectlyParseContainsArrayWithCommaExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Value", "('one,','two')"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("new [] {\"one,\", \"two\"}.Contains(r.Value)", list.Expression.ToString()); } [Fact] public void CanCorrectlyParseContainsArrayWithNotExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Value", "!(one,two)"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("Not(new [] {\"one\", \"two\"}.Contains(r.Value))", list.Expression.ToString()); } [Fact] public void CanCorrectlyParseGreaterThanExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Numeric", ">20"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("r.Numeric > 20", list.Expression.ToString()); } [Fact] public void CanCorrectlyParseGreaterThanEqualsExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Numeric", ">=20"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("r.Numeric >= 20", list.Expression.ToString()); } [Fact] public void CanCorrectlyParseLessThanExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Numeric", "<20"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("r.Numeric < 20", list.Expression.ToString()); } [Fact] public void CanCorrectlyParseLessThanEqualsExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Numeric", "<=20"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("r.Numeric <= 20", list.Expression.ToString()); } [Fact] public void CanCorrectlyParseLessThanEqualsWithDateExpression() { var options = new TestOptions { Filters = new Dictionary<string, string> { {"Date", "<=2020-01-01T12:30:00Z"} } }; var list = QueryOptions.Filter(_items, options); Assert.Contains("r.Date <= 1/01/2020 11:30:00 PM", list.Expression.ToString()); } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections; using System.Text; using System.IO; using System.Xml; using FluorineFx.Util; namespace FluorineFx.Json { internal enum JsonType { Object, Array, None } /// <summary> /// Specifies the state of the <see cref="JsonWriter"/>. /// </summary> public enum WriteState { /// <summary> /// An exception has been thrown, which has left the <see cref="JsonWriter"/> in an invalid state. /// You may call the <see cref="JsonWriter.Close"/> method to put the <see cref="JsonWriter"/> in the <c>Closed</c> state. /// Any other <see cref="JsonWriter"/> method calls results in an <see cref="InvalidOperationException"/> being thrown. /// </summary> Error, /// <summary> /// The <see cref="JsonWriter.Close"/> method has been called. /// </summary> Closed, /// <summary> /// An object is being written. /// </summary> Object, /// <summary> /// A array is being written. /// </summary> Array, /// <summary> /// A property is being written. /// </summary> Property, /// <summary> /// A write method has not been called. /// </summary> Start } /// <summary> /// Specifies formatting options for the <see cref="JsonWriter"/>. /// </summary> public enum Formatting { /// <summary> /// No special formatting is applied. This is the default. /// </summary> None, /// <summary> /// Causes child objects to be indented according to the <see cref="JsonWriter.Indentation"/> and <see cref="JsonWriter.IndentChar"/> settings. /// </summary> Indented } /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data. /// </summary> public class JsonWriter : IDisposable { private enum State { Start, Property, ObjectStart, Object, ArrayStart, Array, Closed, Error } // array that gives a new state based on the current state an the token being written private static readonly State[,] stateArray = { // Start PropertyName ObjectStart Object ArrayStart Array Closed Error // /* None */{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, /* StartObject */{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.Error, State.Error }, /* StartArray */{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.Error, State.Error }, /* StartProperty */{ State.Error, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error }, /* Comment */{ State.Error, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Error, State.Error }, /* Value */{ State.Error, State.Object, State.Error, State.Error, State.Array, State.Array, State.Error, State.Error }, }; private int _top; private ArrayList _stack; private ArrayList _serializeStack; private TextWriter _writer; private Formatting _formatting; private char _indentChar; private int _indentation; private char _quoteChar; private bool _quoteName; private State _currentState; internal ArrayList SerializeStack { get { if (_serializeStack == null) _serializeStack = new ArrayList(); return _serializeStack; } } /// <summary> /// Gets the state of the writer. /// </summary> public WriteState WriteState { get { switch (_currentState) { case State.Error: return WriteState.Error; case State.Closed: return WriteState.Closed; case State.Object: case State.ObjectStart: return WriteState.Object; case State.Array: case State.ArrayStart: return WriteState.Array; case State.Property: return WriteState.Property; case State.Start: return WriteState.Start; default: throw new JsonWriterException("Invalid state: " + _currentState); } } } /// <summary> /// Indicates how the output is formatted. /// </summary> public Formatting Formatting { get { return _formatting; } set { _formatting = value; } } /// <summary> /// Gets or sets how many IndentChars to write for each level in the hierarchy when <paramref name="Formatting"/> is set to <c>Formatting.Indented</c>. /// </summary> public int Indentation { get { return _indentation; } set { if (value < 0) throw new ArgumentException("Indentation value must be greater than 0."); _indentation = value; } } /// <summary> /// Gets or sets which character to use to quote attribute values. /// </summary> public char QuoteChar { get { return _quoteChar; } set { if (value != '"' && value != '\'') throw new ArgumentException(@"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); _quoteChar = value; } } /// <summary> /// Gets or sets which character to use for indenting when <paramref name="Formatting"/> is set to <c>Formatting.Indented</c>. /// </summary> public char IndentChar { get { return _indentChar; } set { _indentChar = value; } } /// <summary> /// Gets or sets a value indicating whether object names will be surrounded with quotes. /// </summary> public bool QuoteName { get { return _quoteName; } set { _quoteName = value; } } /// <summary> /// Creates an instance of the <c>JsonWriter</c> class using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <c>TextWriter</c> to write to.</param> public JsonWriter(TextWriter textWriter) { if (textWriter == null) throw new ArgumentNullException("textWriter"); _writer = textWriter; _quoteChar = '"'; _quoteName = true; _indentChar = ' '; _indentation = 2; _formatting = Formatting.None; _stack = new ArrayList(1); _stack.Add(JsonType.None); _currentState = State.Start; } private void Push(JsonType value) { _top++; if (_stack.Count <= _top) _stack.Add(value); else _stack[_top] = value; } private JsonType Pop() { JsonType value = Peek(); _top--; return value; } private JsonType Peek() { return (JsonType)_stack[_top]; } /// <summary> /// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. /// </summary> public void Flush() { _writer.Flush(); } /// <summary> /// Closes this stream and the underlying stream. /// </summary> public void Close() { AutoCompleteAll(); _writer.Close(); } /// <summary> /// Writes the beginning of a Json object. /// </summary> public void WriteStartObject() { AutoComplete(JsonToken.StartObject); Push(JsonType.Object); _writer.Write("{"); } /// <summary> /// Writes the end of a Json object. /// </summary> public void WriteEndObject() { AutoCompleteClose(JsonToken.EndObject); } /// <summary> /// Writes the beginning of a Json array. /// </summary> public void WriteStartArray() { AutoComplete(JsonToken.StartArray); Push(JsonType.Array); _writer.Write("["); } /// <summary> /// Writes the end of an array. /// </summary> public void WriteEndArray() { AutoCompleteClose(JsonToken.EndArray); } /// <summary> /// Writes the property name of a name/value pair on a Json object. /// </summary> /// <param name="name"></param> public void WritePropertyName(string name) { //_objectStack.Push(new JsonObjectInfo(JsonType.Property)); AutoComplete(JsonToken.PropertyName); if (_quoteName) _writer.Write(_quoteChar); _writer.Write(name); if (_quoteName) _writer.Write(_quoteChar); _writer.Write(':'); } /// <summary> /// Writes the end of the current Json object or array. /// </summary> public void WriteEnd() { WriteEnd(Peek()); } private void WriteEnd(JsonType type) { switch (type) { case JsonType.Object: WriteEndObject(); break; case JsonType.Array: WriteEndArray(); break; default: throw new JsonWriterException("Unexpected type when writing end: " + type); } } private void AutoCompleteAll() { while (_top > 0) { WriteEnd(); } } private JsonType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JsonType.Object; case JsonToken.EndArray: return JsonType.Array; default: throw new JsonWriterException("No type for token: " + token); } } private JsonToken GetCloseTokenForType(JsonType type) { switch (type) { case JsonType.Object: return JsonToken.EndObject; case JsonType.Array: return JsonToken.EndArray; default: throw new JsonWriterException("No close token for type: " + type); } } private void AutoCompleteClose(JsonToken tokenBeingClosed) { // write closing symbol and calculate new state int levelsToComplete = 0; for (int i = 0; i < _top; i++) { int currentLevel = _top - i; if ((JsonType)_stack[currentLevel] == GetTypeForCloseToken(tokenBeingClosed)) { levelsToComplete = i + 1; break; } } if (levelsToComplete == 0) throw new JsonWriterException("No token to close."); for (int i = 0; i < levelsToComplete; i++) { JsonToken token = GetCloseTokenForType(Pop()); if (_currentState != State.ObjectStart && _currentState != State.ArrayStart) WriteIndent(); switch (token) { case JsonToken.EndObject: _writer.Write("}"); break; case JsonToken.EndArray: _writer.Write("]"); break; default: throw new JsonWriterException("Invalid JsonToken: " + token); } } JsonType currentLevelType = Peek(); switch (currentLevelType) { case JsonType.Object: _currentState = State.Object; break; case JsonType.Array: _currentState = State.Array; break; case JsonType.None: _currentState = State.Start; break; default: throw new JsonWriterException("Unknown JsonType: " + currentLevelType); } } private void WriteIndent() { if (_formatting == Formatting.Indented) { _writer.Write(Environment.NewLine); // for each level of object... for (int i = 0; i < _top; i++) { // ...write the indent char the specified number of times for (int j = 0; j < _indentation; j++) { _writer.Write(_indentChar); } } } } private void AutoComplete(JsonToken tokenBeingWritten) { int token; switch (tokenBeingWritten) { default: token = (int)tokenBeingWritten; break; case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: // a value is being written token = 5; break; } // gets new state based on the current state and what is being written State newState = stateArray[token, (int)_currentState]; if (newState == State.Error) throw new JsonWriterException(string.Format("Token {0} in state {1} would result in an invalid JavaScript object.", tokenBeingWritten.ToString(), _currentState.ToString())); if ((_currentState == State.Object || _currentState == State.Array) && tokenBeingWritten != JsonToken.Comment) { _writer.Write(','); } else if (_currentState == State.Property) { if (_formatting == Formatting.Indented) _writer.Write(' '); } if (tokenBeingWritten == JsonToken.PropertyName || (WriteState == WriteState.Array)) { WriteIndent(); } _currentState = newState; } private void WriteValueInternal(string value, JsonToken token) { AutoComplete(token); _writer.Write(value); } #region WriteValue methods /// <summary> /// Writes a null value. /// </summary> public void WriteNull() { WriteValueInternal(JavaScriptConvert.Null, JsonToken.Null); } /// <summary> /// Writes an undefined value. /// </summary> public void WriteUndefined() { WriteValueInternal(JavaScriptConvert.Undefined, JsonToken.Undefined); } /// <summary> /// Writes raw JavaScript manually. /// </summary> /// <param name="javaScript">The raw JavaScript to write.</param> public void WriteRaw(string javaScript) { // hack. some 'raw' or 'other' token perhaps? WriteValueInternal(javaScript, JsonToken.Undefined); } /// <summary> /// Writes a <see cref="String"/> value. /// </summary> /// <param name="value">The <see cref="String"/> value to write.</param> public void WriteValue(string value) { WriteValueInternal(JavaScriptConvert.ToString(value, _quoteChar), JsonToken.String); } /// <summary> /// Writes a <see cref="Int32"/> value. /// </summary> /// <param name="value">The <see cref="Int32"/> value to write.</param> public void WriteValue(int value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt32"/> value. /// </summary> /// <param name="value">The <see cref="UInt32"/> value to write.</param> [CLSCompliant(false)] public void WriteValue(uint value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Integer); } /// <summary> /// Writes a <see cref="Int64"/> value. /// </summary> /// <param name="value">The <see cref="Int64"/> value to write.</param> public void WriteValue(long value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt64"/> value. /// </summary> /// <param name="value">The <see cref="UInt64"/> value to write.</param> [CLSCompliant(false)] public void WriteValue(ulong value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Integer); } /// <summary> /// Writes a <see cref="Single"/> value. /// </summary> /// <param name="value">The <see cref="Single"/> value to write.</param> public void WriteValue(float value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Float); } /// <summary> /// Writes a <see cref="Double"/> value. /// </summary> /// <param name="value">The <see cref="Double"/> value to write.</param> public void WriteValue(double value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Float); } /// <summary> /// Writes a <see cref="Boolean"/> value. /// </summary> /// <param name="value">The <see cref="Boolean"/> value to write.</param> public void WriteValue(bool value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Boolean); } /// <summary> /// Writes a <see cref="Int16"/> value. /// </summary> /// <param name="value">The <see cref="Int16"/> value to write.</param> public void WriteValue(short value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt16"/> value. /// </summary> /// <param name="value">The <see cref="UInt16"/> value to write.</param> [CLSCompliant(false)] public void WriteValue(ushort value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Integer); } /// <summary> /// Writes a <see cref="Char"/> value. /// </summary> /// <param name="value">The <see cref="Char"/> value to write.</param> public void WriteValue(char value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Integer); } /// <summary> /// Writes a <see cref="Byte"/> value. /// </summary> /// <param name="value">The <see cref="Byte"/> value to write.</param> public void WriteValue(byte value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Integer); } /// <summary> /// Writes a <see cref="SByte"/> value. /// </summary> /// <param name="value">The <see cref="SByte"/> value to write.</param> [CLSCompliant(false)] public void WriteValue(sbyte value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Integer); } /// <summary> /// Writes a <see cref="Decimal"/> value. /// </summary> /// <param name="value">The <see cref="Decimal"/> value to write.</param> public void WriteValue(decimal value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Float); } /// <summary> /// Writes a <see cref="DateTime"/> value. /// </summary> /// <param name="value">The <see cref="DateTime"/> value to write.</param> public void WriteValue(DateTime value) { WriteValueInternal(JavaScriptConvert.ToString(value), JsonToken.Date); } #endregion /// <summary> /// Writes out a comment <code>/*...*/</code> containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> public void WriteComment(string text) { AutoComplete(JsonToken.Comment); _writer.Write("/*"); _writer.Write(text); _writer.Write("*/"); } /// <summary> /// Writes out the given white space. /// </summary> /// <param name="ws">The string of white space characters.</param> public void WriteWhitespace(string ws) { if (ws != null) { if (!StringUtils.IsWhiteSpace(ws)) throw new JsonWriterException("Only white space characters should be used."); _writer.Write(ws); } } void IDisposable.Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (WriteState != WriteState.Closed) Close(); } /// <summary> /// Writes a JSON array of JSON strings given an enumerable source /// of arbitrary <see cref="Object"/> values. /// </summary> public void WriteStringArray(IEnumerable values) { if (values == null) { WriteNull(); } else { WriteStartArray(); foreach (object value in values) { if (JavaScriptConvert.IsNull(value)) WriteNull(); else WriteValue(value.ToString()); } WriteEndArray(); } } } }
using System; using System.IO; using System.Threading.Tasks; using GodotTools.Ides.Rider; using GodotTools.Internals; using JetBrains.Annotations; using static GodotTools.Internals.Globals; using File = GodotTools.Utils.File; using OS = GodotTools.Utils.OS; namespace GodotTools.Build { public static class BuildManager { private static BuildInfo _buildInProgress; public const string PropNameMSBuildMono = "MSBuild (Mono)"; public const string PropNameMSBuildVs = "MSBuild (VS Build Tools)"; public const string PropNameMSBuildJetBrains = "MSBuild (JetBrains Rider)"; public const string PropNameDotnetCli = "dotnet CLI"; public const string MsBuildIssuesFileName = "msbuild_issues.csv"; public const string MsBuildLogFileName = "msbuild_log.txt"; public delegate void BuildLaunchFailedEventHandler(BuildInfo buildInfo, string reason); public static event BuildLaunchFailedEventHandler BuildLaunchFailed; public static event Action<BuildInfo> BuildStarted; public static event Action<BuildResult> BuildFinished; public static event Action<string> StdOutputReceived; public static event Action<string> StdErrorReceived; private static void RemoveOldIssuesFile(BuildInfo buildInfo) { string issuesFile = GetIssuesFilePath(buildInfo); if (!File.Exists(issuesFile)) return; File.Delete(issuesFile); } private static void ShowBuildErrorDialog(string message) { var plugin = GodotSharpEditor.Instance; plugin.ShowErrorDialog(message, "Build error"); plugin.MakeBottomPanelItemVisible(plugin.MSBuildPanel); } public static void RestartBuild(BuildOutputView buildOutputView) => throw new NotImplementedException(); public static void StopBuild(BuildOutputView buildOutputView) => throw new NotImplementedException(); private static string GetLogFilePath(BuildInfo buildInfo) { return Path.Combine(buildInfo.LogsDirPath, MsBuildLogFileName); } private static string GetIssuesFilePath(BuildInfo buildInfo) { return Path.Combine(buildInfo.LogsDirPath, MsBuildIssuesFileName); } private static void PrintVerbose(string text) { if (Godot.OS.IsStdoutVerbose()) Godot.GD.Print(text); } public static bool Build(BuildInfo buildInfo) { if (_buildInProgress != null) throw new InvalidOperationException("A build is already in progress"); _buildInProgress = buildInfo; try { BuildStarted?.Invoke(buildInfo); // Required in order to update the build tasks list Internal.GodotMainIteration(); try { RemoveOldIssuesFile(buildInfo); } catch (IOException e) { BuildLaunchFailed?.Invoke(buildInfo, $"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}"); Console.Error.WriteLine(e); } try { int exitCode = BuildSystem.Build(buildInfo, StdOutputReceived, StdErrorReceived); if (exitCode != 0) PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}"); BuildFinished?.Invoke(exitCode == 0 ? BuildResult.Success : BuildResult.Error); return exitCode == 0; } catch (Exception e) { BuildLaunchFailed?.Invoke(buildInfo, $"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}"); Console.Error.WriteLine(e); return false; } } finally { _buildInProgress = null; } } public static async Task<bool> BuildAsync(BuildInfo buildInfo) { if (_buildInProgress != null) throw new InvalidOperationException("A build is already in progress"); _buildInProgress = buildInfo; try { BuildStarted?.Invoke(buildInfo); try { RemoveOldIssuesFile(buildInfo); } catch (IOException e) { BuildLaunchFailed?.Invoke(buildInfo, $"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}"); Console.Error.WriteLine(e); } try { int exitCode = await BuildSystem.BuildAsync(buildInfo, StdOutputReceived, StdErrorReceived); if (exitCode != 0) PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}"); BuildFinished?.Invoke(exitCode == 0 ? BuildResult.Success : BuildResult.Error); return exitCode == 0; } catch (Exception e) { BuildLaunchFailed?.Invoke(buildInfo, $"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}"); Console.Error.WriteLine(e); return false; } } finally { _buildInProgress = null; } } public static bool BuildProjectBlocking(string config, [CanBeNull] string[] targets = null, [CanBeNull] string platform = null) { var buildInfo = new BuildInfo(GodotSharpDirs.ProjectSlnPath, targets ?? new[] {"Build"}, config, restore: true); // If a platform was not specified, try determining the current one. If that fails, let MSBuild auto-detect it. if (platform != null || OS.PlatformNameMap.TryGetValue(Godot.OS.GetName(), out platform)) buildInfo.CustomProperties.Add($"GodotTargetPlatform={platform}"); if (Internal.GodotIsRealTDouble()) buildInfo.CustomProperties.Add("GodotRealTIsDouble=true"); return BuildProjectBlocking(buildInfo); } private static bool BuildProjectBlocking(BuildInfo buildInfo) { if (!File.Exists(buildInfo.Solution)) return true; // No solution to build // Make sure the API assemblies are up to date before building the project. // We may not have had the chance to update the release API assemblies, and the debug ones // may have been deleted by the user at some point after they were loaded by the Godot editor. string apiAssembliesUpdateError = Internal.UpdateApiAssembliesFromPrebuilt(buildInfo.Configuration == "ExportRelease" ? "Release" : "Debug"); if (!string.IsNullOrEmpty(apiAssembliesUpdateError)) { ShowBuildErrorDialog("Failed to update the Godot API assemblies"); return false; } using (var pr = new EditorProgress("mono_project_debug_build", "Building project solution...", 1)) { pr.Step("Building project solution", 0); if (!Build(buildInfo)) { ShowBuildErrorDialog("Failed to build project solution"); return false; } } return true; } public static bool EditorBuildCallback() { if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) return true; // No solution to build try { // Make sure our packages are added to the fallback folder NuGetUtils.AddBundledPackagesToFallbackFolder(NuGetUtils.GodotFallbackFolderPath); } catch (Exception e) { Godot.GD.PushError("Failed to setup Godot NuGet Offline Packages: " + e.Message); } if (GodotSharpEditor.Instance.SkipBuildBeforePlaying) return true; // Requested play from an external editor/IDE which already built the project return BuildProjectBlocking("Debug"); } public static void Initialize() { // Build tool settings var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings(); BuildTool msbuildDefault; if (OS.IsWindows) { if (RiderPathManager.IsExternalEditorSetToRider(editorSettings)) msbuildDefault = BuildTool.JetBrainsMsBuild; else msbuildDefault = !string.IsNullOrEmpty(OS.PathWhich("dotnet")) ? BuildTool.DotnetCli : BuildTool.MsBuildVs; } else { msbuildDefault = !string.IsNullOrEmpty(OS.PathWhich("dotnet")) ? BuildTool.DotnetCli : BuildTool.MsBuildMono; } EditorDef("mono/builds/build_tool", msbuildDefault); string hintString; if (OS.IsWindows) { hintString = $"{PropNameMSBuildMono}:{(int)BuildTool.MsBuildMono}," + $"{PropNameMSBuildVs}:{(int)BuildTool.MsBuildVs}," + $"{PropNameMSBuildJetBrains}:{(int)BuildTool.JetBrainsMsBuild}," + $"{PropNameDotnetCli}:{(int)BuildTool.DotnetCli}"; } else { hintString = $"{PropNameMSBuildMono}:{(int)BuildTool.MsBuildMono}," + $"{PropNameDotnetCli}:{(int)BuildTool.DotnetCli}"; } editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary { ["type"] = Godot.Variant.Type.Int, ["name"] = "mono/builds/build_tool", ["hint"] = Godot.PropertyHint.Enum, ["hint_string"] = hintString }); } } }
using System.Collections.Generic; using System.IO; using GitVersion.Core.Tests.Helpers; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model; using GitVersion.Model.Configuration; using GitTools.Testing; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Shouldly; namespace GitVersion.App.Tests { [TestFixture] public class ArgumentParserTests : TestBase { private IEnvironment environment; private IArgumentParser argumentParser; [SetUp] public void SetUp() { var sp = ConfigureServices(services => { services.AddSingleton<IArgumentParser, ArgumentParser>(); services.AddSingleton<IGlobbingResolver, GlobbingResolver>(); }); environment = sp.GetService<IEnvironment>(); argumentParser = sp.GetService<IArgumentParser>(); } [Test] public void EmptyMeansUseCurrentDirectory() { var arguments = argumentParser.ParseArguments(""); arguments.TargetPath.ShouldBe(System.Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); } [Test] public void SingleMeansUseAsTargetDirectory() { var arguments = argumentParser.ParseArguments("path"); arguments.TargetPath.ShouldBe("path"); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); } [Test] public void NoPathAndLogfileShouldUseCurrentDirectoryTargetDirectory() { var arguments = argumentParser.ParseArguments("-l logFilePath"); arguments.TargetPath.ShouldBe(System.Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); } [Test] public void HelpSwitchTest() { var arguments = argumentParser.ParseArguments("-h"); Assert.IsNull(arguments.TargetPath); Assert.IsNull(arguments.LogFilePath); arguments.IsHelp.ShouldBe(true); } [Test] public void VersionSwitchTest() { var arguments = argumentParser.ParseArguments("-version"); Assert.IsNull(arguments.TargetPath); Assert.IsNull(arguments.LogFilePath); arguments.IsVersion.ShouldBe(true); } [Test] public void TargetDirectoryAndLogFilePathCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -l logFilePath"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); } [Test] public void UsernameAndPasswordCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -u [username] -p [password]"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.Authentication.Username.ShouldBe("[username]"); arguments.Authentication.Password.ShouldBe("[password]"); arguments.IsHelp.ShouldBe(false); } [Test] public void UnknownOutputShouldThrow() { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments("targetDirectoryPath -output invalid_value")); exception.Message.ShouldBe("Value 'invalid_value' cannot be parsed as output type, please use 'json', 'file' or 'buildserver'"); } [Test] public void OutputDefaultsToJson() { var arguments = argumentParser.ParseArguments("targetDirectoryPath"); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void OutputJsonCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output json"); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void MultipleOutputJsonCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output json -output json"); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void OutputBuildserverCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void MultipleOutputBuildserverCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output buildserver"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void OutputFileCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output file"); arguments.Output.ShouldContain(OutputType.File); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); } [Test] public void MultipleOutputFileCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output file -output file"); arguments.Output.ShouldContain(OutputType.File); arguments.Output.ShouldNotContain(OutputType.BuildServer); arguments.Output.ShouldNotContain(OutputType.Json); } [Test] public void OutputBuildserverAndJsonCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output json"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldNotContain(OutputType.File); } [Test] public void OutputBuildserverAndJsonAndFileCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -output json -output file"); arguments.Output.ShouldContain(OutputType.BuildServer); arguments.Output.ShouldContain(OutputType.Json); arguments.Output.ShouldContain(OutputType.File); } [Test] public void MultipleArgsAndFlag() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -updateAssemblyInfo"); arguments.Output.ShouldContain(OutputType.BuildServer); } [TestCase("-output file", "GitVersion.json")] [TestCase("-output file -outputfile version.json", "version.json")] public void OutputFileArgumentCanBeParsed(string args, string outputFile) { var arguments = argumentParser.ParseArguments(args); arguments.Output.ShouldContain(OutputType.File); arguments.OutputFile.ShouldBe(outputFile); } [Test] public void UrlAndBranchNameCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -url http://github.com/Particular/GitVersion.git -b somebranch"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.TargetUrl.ShouldBe("http://github.com/Particular/GitVersion.git"); arguments.TargetBranch.ShouldBe("somebranch"); arguments.IsHelp.ShouldBe(false); } [Test] public void WrongNumberOfArgumentsShouldThrow() { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg")); exception.Message.ShouldBe("Could not parse command line parameter 'extraArg'."); } [TestCase("targetDirectoryPath -x logFilePath")] [TestCase("/invalid-argument")] public void UnknownArgumentsShouldThrow(string arguments) { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments(arguments)); exception.Message.ShouldStartWith("Could not parse command line parameter"); } [TestCase("-updateAssemblyInfo true")] [TestCase("-updateAssemblyInfo 1")] [TestCase("-updateAssemblyInfo")] [TestCase("-updateAssemblyInfo assemblyInfo.cs")] [TestCase("-updateAssemblyInfo assemblyInfo.cs -ensureassemblyinfo")] [TestCase("-updateAssemblyInfo assemblyInfo.cs otherAssemblyInfo.cs")] [TestCase("-updateAssemblyInfo Assembly.cs Assembly.cs -ensureassemblyinfo")] public void UpdateAssemblyInfoTrue(string command) { var arguments = argumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(true); } [TestCase("-updateProjectFiles assemblyInfo.csproj")] [TestCase("-updateProjectFiles assemblyInfo.csproj")] [TestCase("-updateProjectFiles assemblyInfo.csproj otherAssemblyInfo.fsproj")] [TestCase("-updateProjectFiles")] public void UpdateProjectTrue(string command) { var arguments = argumentParser.ParseArguments(command); arguments.UpdateProjectFiles.ShouldBe(true); } [TestCase("-updateAssemblyInfo false")] [TestCase("-updateAssemblyInfo 0")] public void UpdateAssemblyInfoFalse(string command) { var arguments = argumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(false); } [TestCase("-updateAssemblyInfo Assembly.cs Assembly1.cs -ensureassemblyinfo")] public void CreateMulitpleAssemblyInfoProtected(string command) { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments(command)); exception.Message.ShouldBe("Can't specify multiple assembly info files when using /ensureassemblyinfo switch, either use a single assembly info file or do not specify /ensureassemblyinfo and create assembly info files manually"); } [TestCase("-updateProjectFiles Assembly.csproj -ensureassemblyinfo")] public void UpdateProjectInfoWithEnsureAssemblyInfoProtected(string command) { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments(command)); exception.Message.ShouldBe("Cannot specify -ensureassemblyinfo with updateprojectfiles: please ensure your project file exists before attempting to update it"); } [Test] public void UpdateAssemblyInfoWithFilename() { using var repo = new EmptyRepositoryFixture(); var assemblyFile = Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = File.Create(assemblyFile); var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(1); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); } [Test] public void UpdateAssemblyInfoWithMultipleFilenames() { using var repo = new EmptyRepositoryFixture(); var assemblyFile1 = Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = File.Create(assemblyFile1); var assemblyFile2 = Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); using var file2 = File.Create(assemblyFile2); var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo CommonAssemblyInfo.cs VersionAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(2); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("VersionAssemblyInfo.cs")); } [Test] public void UpdateProjectFilesWithMultipleFilenames() { using var repo = new EmptyRepositoryFixture(); var assemblyFile1 = Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.csproj"); using var file = File.Create(assemblyFile1); var assemblyFile2 = Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.csproj"); using var file2 = File.Create(assemblyFile2); var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateProjectFiles CommonAssemblyInfo.csproj VersionAssemblyInfo.csproj"); arguments.UpdateProjectFiles.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(2); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.csproj")); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("VersionAssemblyInfo.csproj")); } [Test] public void UpdateAssemblyInfoWithMultipleFilenamesMatchingGlobbing() { using var repo = new EmptyRepositoryFixture(); var assemblyFile1 = Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = File.Create(assemblyFile1); var assemblyFile2 = Path.Combine(repo.RepositoryPath, "VersionAssemblyInfo.cs"); using var file2 = File.Create(assemblyFile2); var subdir = Path.Combine(repo.RepositoryPath, "subdir"); Directory.CreateDirectory(subdir); var assemblyFile3 = Path.Combine(subdir, "LocalAssemblyInfo.cs"); using var file3 = File.Create(assemblyFile3); var arguments = argumentParser.ParseArguments($"-targetpath {repo.RepositoryPath} -updateAssemblyInfo **/*AssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(3); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("VersionAssemblyInfo.cs")); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("LocalAssemblyInfo.cs")); } [Test] public void UpdateAssemblyInfoWithRelativeFilename() { using var repo = new EmptyRepositoryFixture(); var assemblyFile = Path.Combine(repo.RepositoryPath, "CommonAssemblyInfo.cs"); using var file = File.Create(assemblyFile); var targetPath = Path.Combine(repo.RepositoryPath, "subdir1", "subdir2"); Directory.CreateDirectory(targetPath); var arguments = argumentParser.ParseArguments($"-targetpath {targetPath} -updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(1); arguments.UpdateAssemblyInfoFileName.ShouldContain(x => Path.GetFileName(x).Equals("CommonAssemblyInfo.cs")); } [Test] public void OverrideconfigWithNoOptions() { var arguments = argumentParser.ParseArguments("/overrideconfig"); arguments.OverrideConfig.ShouldBeNull(); } [TestCaseSource(nameof(OverrideconfigWithInvalidOptionTestData))] public string OverrideconfigWithInvalidOption(string options) { var exception = Assert.Throws<WarningException>(() => argumentParser.ParseArguments($"/overrideconfig {options}")); return exception.Message; } private static IEnumerable<TestCaseData> OverrideconfigWithInvalidOptionTestData() { yield return new TestCaseData("tag-prefix=sample=asdf") { ExpectedResult = "Could not parse /overrideconfig option: tag-prefix=sample=asdf. Ensure it is in format 'key=value'." }; yield return new TestCaseData("unknown-option=25") { ExpectedResult = "Could not parse /overrideconfig option: unknown-option=25. Unsuported 'key'." }; yield return new TestCaseData("update-build-number=1") { ExpectedResult = "Could not parse /overrideconfig option: update-build-number=1. Ensure that 'value' is 'true' or 'false'." }; yield return new TestCaseData("tag-pre-release-weight=invalid-value") { ExpectedResult = "Could not parse /overrideconfig option: tag-pre-release-weight=invalid-value. Ensure that 'value' is valid integer number." }; yield return new TestCaseData("assembly-versioning-scheme=WrongEnumValue") { ExpectedResult = $"Could not parse /overrideconfig option: assembly-versioning-scheme=WrongEnumValue. Ensure that 'value' is valid for specified 'key' enumeration: {System.Environment.NewLine}" + $"MajorMinorPatchTag{System.Environment.NewLine}" + $"MajorMinorPatch{System.Environment.NewLine}" + $"MajorMinor{System.Environment.NewLine}" + $"Major{System.Environment.NewLine}" + $"None{System.Environment.NewLine}" }; } [TestCaseSource(nameof(OverrideconfigWithSingleOptionTestData))] public void OverrideconfigWithSingleOptions(string options, Config expected) { var arguments = argumentParser.ParseArguments($"/overrideconfig {options}"); arguments.OverrideConfig.ShouldBeEquivalentTo(expected); } private static IEnumerable<TestCaseData> OverrideconfigWithSingleOptionTestData() { yield return new TestCaseData( "assembly-versioning-scheme=MajorMinor", new Config { AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinor, } ); yield return new TestCaseData( "assembly-file-versioning-scheme=\"MajorMinorPatch\"", new Config { AssemblyFileVersioningScheme = AssemblyFileVersioningScheme.MajorMinorPatch, } ); yield return new TestCaseData( "assembly-informational-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", new Config { AssemblyInformationalFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}", } ); yield return new TestCaseData( "assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", new Config { AssemblyVersioningFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}", } ); yield return new TestCaseData( "assembly-file-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", new Config { AssemblyFileVersioningFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}", } ); yield return new TestCaseData( "mode=ContinuousDelivery", new Config { VersioningMode = GitVersion.VersionCalculation.VersioningMode.ContinuousDelivery } ); yield return new TestCaseData( "tag-prefix=sample", new Config { TagPrefix = "sample" } ); yield return new TestCaseData( "continuous-delivery-fallback-tag=cd-tag", new Config { ContinuousDeploymentFallbackTag = "cd-tag" } ); yield return new TestCaseData( "next-version=1", new Config { NextVersion = "1" } ); yield return new TestCaseData( "major-version-bump-message=\"This is major version bump message.\"", new Config { MajorVersionBumpMessage = "This is major version bump message." } ); yield return new TestCaseData( "minor-version-bump-message=\"This is minor version bump message.\"", new Config { MinorVersionBumpMessage = "This is minor version bump message." } ); yield return new TestCaseData( "patch-version-bump-message=\"This is patch version bump message.\"", new Config { PatchVersionBumpMessage = "This is patch version bump message." } ); yield return new TestCaseData( "no-bump-message=\"This is no bump message.\"", new Config { NoBumpMessage = "This is no bump message." } ); yield return new TestCaseData( "legacy-semver-padding=99", new Config { LegacySemVerPadding = 99 } ); yield return new TestCaseData( "build-metadata-padding=30", new Config { BuildMetaDataPadding = 30 } ); yield return new TestCaseData( "commits-since-version-source-padding=5", new Config { CommitsSinceVersionSourcePadding = 5 } ); yield return new TestCaseData( "tag-pre-release-weight=2", new Config { TagPreReleaseWeight = 2 } ); yield return new TestCaseData( "commit-message-incrementing=MergeMessageOnly", new Config { CommitMessageIncrementing = CommitMessageIncrementMode.MergeMessageOnly } ); yield return new TestCaseData( "increment=Minor", new Config { Increment = IncrementStrategy.Minor } ); yield return new TestCaseData( "commit-date-format=\"MM/dd/yyyy h:mm tt\"", new Config { CommitDateFormat = "MM/dd/yyyy h:mm tt" } ); yield return new TestCaseData( "update-build-number=true", new Config { UpdateBuildNumber = true } ); } [TestCaseSource(nameof(OverrideconfigWithMultipleOptionsTestData))] public void OverrideconfigWithMultipleOptions(string options, Config expected) { var arguments = argumentParser.ParseArguments(options); arguments.OverrideConfig.ShouldBeEquivalentTo(expected); } private static IEnumerable<TestCaseData> OverrideconfigWithMultipleOptionsTestData() { yield return new TestCaseData( "/overrideconfig tag-prefix=sample /overrideconfig assembly-versioning-scheme=MajorMinor", new Config { TagPrefix = "sample", AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinor, } ); yield return new TestCaseData( "/overrideconfig tag-prefix=sample /overrideconfig assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"", new Config { TagPrefix = "sample", AssemblyVersioningFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}" } ); yield return new TestCaseData( "/overrideconfig tag-prefix=sample /overrideconfig assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\" /overrideconfig update-build-number=true /overrideconfig assembly-versioning-scheme=MajorMinorPatchTag /overrideconfig mode=ContinuousDelivery /overrideconfig tag-pre-release-weight=4", new Config { TagPrefix = "sample", AssemblyVersioningFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}", UpdateBuildNumber = true, AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatchTag, VersioningMode = GitVersion.VersionCalculation.VersioningMode.ContinuousDelivery, TagPreReleaseWeight = 4 } ); } [Test] public void EnsureAssemblyInfoTrueWhenFound() { var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] public void EnsureAssemblyInfoTrue() { var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo true"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] public void EnsureAssemblyInfoFalse() { var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo false"); arguments.EnsureAssemblyInfo.ShouldBe(false); } [Test] public void DynamicRepoLocation() { var arguments = argumentParser.ParseArguments("-dynamicRepoLocation c:\\foo\\"); arguments.DynamicRepositoryClonePath.ShouldBe("c:\\foo\\"); } [Test] public void CanLogToConsole() { var arguments = argumentParser.ParseArguments("-l console"); arguments.LogFilePath.ShouldBe("console"); } [Test] public void NofetchTrueWhenDefined() { var arguments = argumentParser.ParseArguments("-nofetch"); arguments.NoFetch.ShouldBe(true); } [Test] public void NonormilizeTrueWhenDefined() { var arguments = argumentParser.ParseArguments("-nonormalize"); arguments.NoNormalize.ShouldBe(true); } [Test] public void OtherArgumentsCanBeParsedBeforeNofetch() { var arguments = argumentParser.ParseArguments("targetpath -nofetch "); arguments.TargetPath.ShouldBe("targetpath"); arguments.NoFetch.ShouldBe(true); } [Test] public void OtherArgumentsCanBeParsedBeforeNonormalize() { var arguments = argumentParser.ParseArguments("targetpath -nonormalize"); arguments.TargetPath.ShouldBe("targetpath"); arguments.NoNormalize.ShouldBe(true); } [Test] public void OtherArgumentsCanBeParsedBeforeNocache() { var arguments = argumentParser.ParseArguments("targetpath -nocache"); arguments.TargetPath.ShouldBe("targetpath"); arguments.NoCache.ShouldBe(true); } [TestCase("-nofetch -nonormalize -nocache")] [TestCase("-nofetch -nocache -nonormalize")] [TestCase("-nocache -nofetch -nonormalize")] [TestCase("-nocache -nonormalize -nofetch")] [TestCase("-nonormalize -nocache -nofetch")] [TestCase("-nonormalize -nofetch -nocache")] public void SeveralSwitchesCanBeParsed(string commandLineArgs) { var arguments = argumentParser.ParseArguments(commandLineArgs); arguments.NoCache.ShouldBe(true); arguments.NoNormalize.ShouldBe(true); arguments.NoFetch.ShouldBe(true); } [Test] public void LogPathCanContainForwardSlash() { var arguments = argumentParser.ParseArguments("-l /some/path"); arguments.LogFilePath.ShouldBe("/some/path"); } [Test] public void BooleanArgumentHandling() { var arguments = argumentParser.ParseArguments("/nofetch /updateassemblyinfo true"); arguments.NoFetch.ShouldBe(true); arguments.UpdateAssemblyInfo.ShouldBe(true); } [Test] public void NocacheTrueWhenDefined() { var arguments = argumentParser.ParseArguments("-nocache"); arguments.NoCache.ShouldBe(true); } [TestCase("-verbosity x", true, Verbosity.Normal)] [TestCase("-verbosity diagnostic", false, Verbosity.Diagnostic)] [TestCase("-verbosity Minimal", false, Verbosity.Minimal)] [TestCase("-verbosity NORMAL", false, Verbosity.Normal)] [TestCase("-verbosity quiet", false, Verbosity.Quiet)] [TestCase("-verbosity Verbose", false, Verbosity.Verbose)] public void CheckVerbosityParsing(string command, bool shouldThrow, Verbosity expectedVerbosity) { if (shouldThrow) { Assert.Throws<WarningException>(() => argumentParser.ParseArguments(command)); } else { var arguments = argumentParser.ParseArguments(command); arguments.Verbosity.ShouldBe(expectedVerbosity); } } [Test] public void EmptyArgumentsRemoteUsernameDefinedSetsUsername() { environment.SetEnvironmentVariable("GITVERSION_REMOTE_USERNAME", "value"); var arguments = argumentParser.ParseArguments(string.Empty); arguments.Authentication.Username.ShouldBe("value"); } [Test] public void EmptyArgumentsRemotePasswordDefinedSetsPassword() { environment.SetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD", "value"); var arguments = argumentParser.ParseArguments(string.Empty); arguments.Authentication.Password.ShouldBe("value"); } [Test] public void ArbitraryArgumentsRemoteUsernameDefinedSetsUsername() { environment.SetEnvironmentVariable("GITVERSION_REMOTE_USERNAME", "value"); var arguments = argumentParser.ParseArguments("-nocache"); arguments.Authentication.Username.ShouldBe("value"); } [Test] public void ArbitraryArgumentsRemotePasswordDefinedSetsPassword() { environment.SetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD", "value"); var arguments = argumentParser.ParseArguments("-nocache"); arguments.Authentication.Password.ShouldBe("value"); } } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.List.Contains(T) /// </summary> public class ListContains { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int"); try { int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 }; List<int> listObject = new List<int>(iArray); int i = this.GetInt32(0, 10); if (!listObject.Contains(i)) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,The i is: " + i); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is a referece type of string"); try { string[] strArray = { "apple", "banana", "chocolate", "dog", "food" }; List<string> listObject = new List<string>(strArray); if (!listObject.Contains("dog")) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is custom type"); try { MyClass myclass1 = new MyClass(); MyClass myclass2 = new MyClass(); MyClass myclass3 = new MyClass(); MyClass[] mc = new MyClass[3] { myclass1, myclass2, myclass3 }; List<MyClass> listObject = new List<MyClass>(mc); if (!listObject.Contains(myclass1)) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: The list does not contain the element"); try { char[] chArray = { '1', '9', '3', '6', '5', '8', '7', '2', '4' }; List<char> listObject = new List<char>(chArray); if (listObject.Contains('t')) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: The argument is a null reference"); try { string[] strArray = { "apple", "banana", "chocolate", null, "food" }; List<string> listObject = new List<string>(strArray); if (!listObject.Contains(null)) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases #endregion #endregion public static int Main() { ListContains test = new ListContains(); TestLibrary.TestFramework.BeginTestCase("ListContains"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } } public class MyClass { }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\RootMotionSource.h:727 namespace UnrealEngine { public partial class FRootMotionSourceGroup : NativeStructWrapper { public FRootMotionSourceGroup(IntPtr NativePointer, bool IsRef = false) : base(NativePointer, IsRef) { } public FRootMotionSourceGroup() : base(E_CreateStruct_FRootMotionSourceGroup(), false) { } [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_FRootMotionSourceGroup_bHasAdditiveSources_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRootMotionSourceGroup_bHasAdditiveSources_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_FRootMotionSourceGroup_bHasOverrideSources_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRootMotionSourceGroup_bHasOverrideSources_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern byte E_PROP_FRootMotionSourceGroup_bIsAdditiveVelocityApplied_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRootMotionSourceGroup_bIsAdditiveVelocityApplied_SET(IntPtr Ptr, byte Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_FRootMotionSourceGroup_LastAccumulatedSettings_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRootMotionSourceGroup_LastAccumulatedSettings_SET(IntPtr Ptr, IntPtr Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_FRootMotionSourceGroup_LastPreAdditiveVelocity_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRootMotionSourceGroup_LastPreAdditiveVelocity_SET(IntPtr Ptr, IntPtr Value); #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FRootMotionSourceGroup(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FRootMotionSourceGroup_AccumulateAdditiveRootMotionVelocity(IntPtr self, float deltaTime, IntPtr character, IntPtr moveComponent, IntPtr inOutVelocity); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FRootMotionSourceGroup_AccumulateOverrideRootMotionVelocity(IntPtr self, float deltaTime, IntPtr character, IntPtr moveComponent, IntPtr inOutVelocity); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FRootMotionSourceGroup_ApplyTimeStampReset(IntPtr self, float deltaTime); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FRootMotionSourceGroup_CleanUpInvalidRootMotion(IntPtr self, float deltaTime, IntPtr character, IntPtr moveComponent); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FRootMotionSourceGroup_Clear(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FRootMotionSourceGroup_CullInvalidSources(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FRootMotionSourceGroup_HasActiveRootMotionSources(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FRootMotionSourceGroup_HasAdditiveVelocity(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FRootMotionSourceGroup_HasOverrideVelocity(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FRootMotionSourceGroup_HasRootMotionToApply(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FRootMotionSourceGroup_HasVelocity(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FRootMotionSourceGroup_PrepareRootMotion(IntPtr self, float deltaTime, IntPtr character, IntPtr inMoveComponent, bool bForcePrepareAll); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FRootMotionSourceGroup_RemoveRootMotionSource(IntPtr self, string instanceName); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FRootMotionSourceGroup_SetPendingRootMotionSourceMinStartTimes(IntPtr self, float newStartTime); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FRootMotionSourceGroup_UpdateStateFrom(IntPtr self, IntPtr groupToTakeStateFrom, bool bMarkForSimulatedCatchup); #endregion #region Property public byte bHasAdditiveSources { get => E_PROP_FRootMotionSourceGroup_bHasAdditiveSources_GET(NativePointer); set => E_PROP_FRootMotionSourceGroup_bHasAdditiveSources_SET(NativePointer, value); } public byte bHasOverrideSources { get => E_PROP_FRootMotionSourceGroup_bHasOverrideSources_GET(NativePointer); set => E_PROP_FRootMotionSourceGroup_bHasOverrideSources_SET(NativePointer, value); } public byte bIsAdditiveVelocityApplied { get => E_PROP_FRootMotionSourceGroup_bIsAdditiveVelocityApplied_GET(NativePointer); set => E_PROP_FRootMotionSourceGroup_bIsAdditiveVelocityApplied_SET(NativePointer, value); } public FRootMotionSourceSettings LastAccumulatedSettings { get => E_PROP_FRootMotionSourceGroup_LastAccumulatedSettings_GET(NativePointer); set => E_PROP_FRootMotionSourceGroup_LastAccumulatedSettings_SET(NativePointer, value); } public FVector_NetQuantize10 LastPreAdditiveVelocity { get => E_PROP_FRootMotionSourceGroup_LastPreAdditiveVelocity_GET(NativePointer); set => E_PROP_FRootMotionSourceGroup_LastPreAdditiveVelocity_SET(NativePointer, value); } #endregion #region ExternMethods /// <summary> /// Helper function for accumulating additive velocity into InOutVelocity /// </summary> public void AccumulateAdditiveRootMotionVelocity(float deltaTime, ACharacter character, UCharacterMovementComponent moveComponent, FVector inOutVelocity) => E_FRootMotionSourceGroup_AccumulateAdditiveRootMotionVelocity(this, deltaTime, character, moveComponent, inOutVelocity); /// <summary> /// Helper function for accumulating override velocity into InOutVelocity /// </summary> public void AccumulateOverrideRootMotionVelocity(float deltaTime, ACharacter character, UCharacterMovementComponent moveComponent, FVector inOutVelocity) => E_FRootMotionSourceGroup_AccumulateOverrideRootMotionVelocity(this, deltaTime, character, moveComponent, inOutVelocity); /// <summary> /// Applies a reset to the start time for each root motion when the time stamp is reset /// </summary> public void ApplyTimeStampReset(float deltaTime) => E_FRootMotionSourceGroup_ApplyTimeStampReset(this, deltaTime); public void CleanUpInvalidRootMotion(float deltaTime, ACharacter character, UCharacterMovementComponent moveComponent) => E_FRootMotionSourceGroup_CleanUpInvalidRootMotion(this, deltaTime, character, moveComponent); /// <summary> /// Clear the contents to return it to "empty" /// </summary> public void Clear() => E_FRootMotionSourceGroup_Clear(this); /// <summary> /// Removes any Sources without a valid ID /// </summary> public void CullInvalidSources() => E_FRootMotionSourceGroup_CullInvalidSources(this); /// <summary> /// </summary> /// <return>true</return> public bool HasActiveRootMotionSources() => E_FRootMotionSourceGroup_HasActiveRootMotionSources(this); /// <summary> /// </summary> /// <return>true</return> public bool HasAdditiveVelocity() => E_FRootMotionSourceGroup_HasAdditiveVelocity(this); /// <summary> /// </summary> /// <return>true</return> public bool HasOverrideVelocity() => E_FRootMotionSourceGroup_HasOverrideVelocity(this); /// <summary> /// Not valid outside of the scope of that function. Since RootMotion is extracted and used in it. /// </summary> /// <return>true</return> public bool HasRootMotionToApply() => E_FRootMotionSourceGroup_HasRootMotionToApply(this); /// <summary> /// </summary> /// <return>true</return> public bool HasVelocity() => E_FRootMotionSourceGroup_HasVelocity(this); /// <summary> /// Generates root motion by accumulating transforms through current root motion sources. /// <para>Needed due to SavedMove playback/server correction only applying corrections to </para> /// Sources that need updating, so in that case we only Prepare those that need it. /// </summary> /// <param name="bForcePrepareAll">Used during "live" PerformMovements() to ensure all sources get prepared</param> public void PrepareRootMotion(float deltaTime, ACharacter character, UCharacterMovementComponent inMoveComponent, bool bForcePrepareAll = false) => E_FRootMotionSourceGroup_PrepareRootMotion(this, deltaTime, character, inMoveComponent, bForcePrepareAll); /// <summary> /// Remove a RootMotionSource from this Group by name /// </summary> public void RemoveRootMotionSource(string instanceName) => E_FRootMotionSourceGroup_RemoveRootMotionSource(this, instanceName); /// <summary> /// Sets the StartTime of all pending root motion sources to be at least this time, can be used on servers to match client-side start times /// </summary> public void SetPendingRootMotionSourceMinStartTimes(float newStartTime) => E_FRootMotionSourceGroup_SetPendingRootMotionSourceMinStartTimes(this, newStartTime); /// <summary> /// Update contained Sources to state in matching sources from other group. /// <para>Used for correcting root motion state when receiving authoritative state from server. </para> /// </summary> /// <param name="groupToTakeStateFrom">the Authoritative Group to take state from</param> /// <param name="bMarkForSimulatedCatchup">marks Sources as needing to return to their current Time on next Prepare</param> /// <return>whether</return> public void UpdateStateFrom(FRootMotionSourceGroup groupToTakeStateFrom, bool bMarkForSimulatedCatchup = false) => E_FRootMotionSourceGroup_UpdateStateFrom(this, groupToTakeStateFrom, bMarkForSimulatedCatchup); #endregion public static implicit operator IntPtr(FRootMotionSourceGroup self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator FRootMotionSourceGroup(IntPtr adress) { return adress == IntPtr.Zero ? null : new FRootMotionSourceGroup(adress, false); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 3/1/2010 2:03:50 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using DotSpatial.NTSExtension; using GeoAPI.Geometries; namespace DotSpatial.Data { /// <summary> /// Segment /// </summary> public class Segment { #region Private Variables /// <summary> /// The start point of the segment /// </summary> public Vertex P1; /// <summary> /// the end point of the segment /// </summary> public Vertex P2; /// <summary> /// Gets or sets the precision for calculating equality, but this is just a re-direction to Vertex.Epsilon /// </summary> public static double Epsilon { get { return Vertex.Epsilon; } set { Vertex.Epsilon = value; } } #endregion #region Constructors /// <summary> /// Creates a segment from double valued ordinates. /// </summary> /// <param name="x1"></param> /// <param name="y1"></param> /// <param name="x2"></param> /// <param name="y2"></param> public Segment(double x1, double y1, double x2, double y2) { P1 = new Vertex(x1, y1); P2 = new Vertex(x2, y2); } /// <summary> /// Creates a new instance of Segment /// </summary> public Segment(Vertex p1, Vertex p2) { P1 = p1; P2 = p2; } #endregion #region Methods /// <summary> /// Uses the intersection count to detect if there is an intersection /// </summary> /// <param name="other"></param> /// <returns></returns> public bool Intersects(Segment other) { return (IntersectionCount(other) > 0); } /// <summary> /// Calculates the shortest distance to this line segment from the specified MapWinGIS.Point /// </summary> /// <param name="point">A MapWinGIS.Point specifing the location to find the distance to the line</param> /// <returns>A double value that is the shortest distance from the given Point to this line segment</returns> public double DistanceTo(Coordinate point) { Vertex p = new Vertex(point.X, point.Y); Vertex pt = ClosestPointTo(p); Vector dist = new Vector(new Coordinate(pt.X, pt.Y), point); return dist.Length2D; } /// <summary> /// Returns a vertex representing the closest point on this line segment from a given vertex /// </summary> /// <param name="point">The point we want to be close to</param> /// <returns>The point on this segment that is closest to the given point</returns> public Vertex ClosestPointTo(Vertex point) { EndPointInteraction endPointFlag; return ClosestPointTo(point, false, out endPointFlag); } /// <summary> /// Returns a vertex representing the closest point on this line segment from a given vertex /// </summary> /// <param name="point">The point we want to be close to</param> /// <param name="isInfiniteLine">If true treat the line as infinitly long</param> /// <param name="endPointFlag">Outputs 0 if the vertex is on the line segment, 1 if beyond P0, 2 if beyong P1 and -1 if P1=P2</param> /// <returns>The point on this segment or infinite line that is closest to the given point</returns> public Vertex ClosestPointTo(Vertex point, bool isInfiniteLine, out EndPointInteraction endPointFlag) { // If the points defining this segment are the same, we treat the segment as a point // special handling to avoid 0 in denominator later if (P2.X == P1.X && P2.Y == P1.Y) { endPointFlag = EndPointInteraction.P1equalsP2; return P1; } //http://softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm Vector v = ToVector(); // vector from p1 to p2 in the segment v.Z = 0; Vector w = new Vector(P1.ToCoordinate(), point.ToCoordinate()); // vector from p1 to Point w.Z = 0; double c1 = w.Dot(v); // the dot product represents the projection onto the line if (c1 < 0) { endPointFlag = EndPointInteraction.PastP1; if (!isInfiniteLine) // The closest point on the segment to Point is p1 return P1; } double c2 = v.Dot(v); if (c2 <= c1) { endPointFlag = EndPointInteraction.PastP2; if (!isInfiniteLine) // The closest point on the segment to Point is p2 return P2; } // The closest point on the segment is perpendicular to the point, // but somewhere on the segment between P1 and P2 endPointFlag = EndPointInteraction.OnLine; double b = c1 / c2; v = v.Multiply(b); Vertex pb = new Vertex(P1.X + v.X, P1.Y + v.Y); return pb; } /// <summary> /// Casts this to a vector /// </summary> /// <returns></returns> public Vector ToVector() { double x = P2.X - P1.X; double y = P2.Y - P1.Y; return new Vector(x, y, 0); } /// <summary> /// Determines the shortest distance between two segments /// </summary> /// <param name="lineSegment">Segment, The line segment to test against this segment</param> /// <returns>Double, the shortest distance between two segments</returns> public double DistanceTo(Segment lineSegment) { //http://www.geometryalgorithms.com/Archive/algorithm_0106/algorithm_0106.htm const double smallNum = 0.00000001; Vector u = ToVector(); // Segment 1 Vector v = lineSegment.ToVector(); // Segment 2 Vector w = ToVector(); double a = u.Dot(u); // length of segment 1 double b = u.Dot(v); // length of segment 2 projected onto line 1 double c = v.Dot(v); // length of segment 2 double d = u.Dot(w); // double e = v.Dot(w); double dist = a * c - b * b; double sc, sN, sD = dist; double tc, tN, tD = dist; // compute the line parameters of the two closest points if (dist < smallNum) { // the lines are almost parallel force using point P0 on segment 1 // to prevent possible division by 0 later sN = 0.0; sD = 1.0; tN = e; tD = c; } else { // get the closest points on the infinite lines sN = (b * e - c * d); tN = (a * e - b * d); if (sN < 0.0) { // sc < 0 => the s=0 edge is visible sN = 0.0; tN = e; tD = c; } else if (sN > sD) { // sc > 1 => the s=1 edge is visible sN = sD; tN = e + b; tD = c; } } if (tN < 0.0) { // tc < 0 => the t=0 edge is visible tN = 0.0; // recompute sc for this edge if (-d < 0.0) { sN = 0.0; } else if (-d > a) { sN = sD; } else { sN = -d; sD = a; } } else if (tN > tD) { // tc > 1 => the t = 1 edge is visible // recompute sc for this edge if ((-d + b) < 0.0) { sN = 0; } else if ((-d + b) > a) { sN = sD; } else { sN = (-d + b); sD = a; } } // finally do the division to get sc and tc if (Math.Abs(sN) < smallNum) { sc = 0.0; } else { sc = sN / sD; } if (Math.Abs(tN) < smallNum) { tc = 0.0; } else { tc = tN / tD; } // get the difference of the two closest points Vector dU = u.Multiply(sc); Vector dV = v.Multiply(tc); Vector dP = (w.Add(dU)).Subtract(dV); // S1(sc) - S2(tc) return dP.Length2D; } /// <summary> /// Returns 0 if no intersections occur, 1 if an intersection point is found, /// and 2 if the segments are colinear and overlap. /// </summary> /// <param name="other"></param> /// <returns></returns> public int IntersectionCount(Segment other) { double x1 = P1.X; double y1 = P1.Y; double x2 = P2.X; double y2 = P2.Y; double x3 = other.P1.X; double y3 = other.P1.Y; double x4 = other.P2.X; double y4 = other.P2.Y; double denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); //The case of two degenerate segements if ((x1 == x2) && (y1 == y2) && (x3 == x4) && (y3 == y4)) { if ((x1 != x3) || (y1 != y3)) return 0; } // if denom is 0, then the two lines are parallel double na = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); double nb = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3); // if denom is 0 AND na and nb are 0, then the lines are coincident and DO intersect if (Math.Abs(denom) < Epsilon && Math.Abs(na) < Epsilon && Math.Abs(nb) < Epsilon) return 2; // If denom is 0, but na or nb are not 0, then the lines are parallel and not coincident if (denom == 0) return 0; double ua = na / denom; double ub = nb / denom; if (ua < 0 || ua > 1) return 0; // not intersecting with segment a if (ub < 0 || ub > 1) return 0; // not intersecting with segment b // If we get here, then one intersection exists and it is found on both line segments return 1; } /// <summary> /// Tests to see if the specified segment contains the point within Epsilon tollerance. /// </summary> /// <returns></returns> public bool IntersectsVertex(Vertex point) { double x1 = P1.X; double y1 = P1.Y; double x2 = P2.X; double y2 = P2.Y; double pX = point.X; double pY = point.Y; // COllinear if (Math.Abs((x2 - x1) * (pY - y1) - (pX - x1) * (y2 - y1)) > Epsilon) return false; // In the x is in bounds and it is colinear, it is on the segment if (x1 < x2) { if (x1 <= pX && pX <= x2) return true; } else { if (x2 <= pX && pX <= x1) return true; } return false; } #endregion } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System.Collections.Generic; using NUnit.Framework.Internal; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Attributes { public class TestMethodBuilderTests { #region TestAttribute [Test] public void TestAttribute_NoArgs_Runnable() { var method = GetMethod("MethodWithoutArgs"); TestMethod test = new TestAttribute().BuildFrom(method, null); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void TestAttribute_WithArgs_NotRunnable() { var method = GetMethod("MethodWithIntArgs"); TestMethod test = new TestAttribute().BuildFrom(method, null); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } #endregion #region TestCaseAttribute [Test] public void TestCaseAttribute_NoArgs_NotRunnable() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseAttribute(5, 42).BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void TestCaseAttribute_RightArgs_Runnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseAttribute(5, 42).BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void TestCaseAttribute_WrongArgs_NotRunnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseAttribute(5, 42, 99).BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.NotRunnable)); } #endregion #region TestCaseSourceAttribute [Test] public void TestCaseSourceAttribute_NoArgs_NotRunnable() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("GoodData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void TestCaseSourceAttribute_NoArgs_NoData_NotRunnable() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("ZeroData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void TestCaseSourceAttribute_RightArgs_Runnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("GoodData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void TestCaseSourceAttribute_WrongArgs_NotRunnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("BadData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } #endregion #region TheoryAttribute [Test] public void TheoryAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TheoryAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void TheoryAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TheoryAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(9)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region CombinatorialAttribute [Test] public void CombinatorialAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new CombinatorialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void CombinatorialAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntValues"); List<TestMethod> tests = new List<TestMethod>(new CombinatorialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(6)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region PairwiseAttribute [Test] public void PairwiseAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new PairwiseAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void PairwiseAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntValues"); List<TestMethod> tests = new List<TestMethod>(new PairwiseAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(6)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region SequentialAttribute [Test] public void SequentialAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new SequentialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void SequentialAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntValues"); List<TestMethod> tests = new List<TestMethod>(new SequentialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region Helper Methods and Data private IMethodInfo GetMethod(string methodName) { return new MethodWrapper(GetType(), methodName); } public static void MethodWithoutArgs() { } public static void MethodWithIntArgs(int x, int y) { } public static void MethodWithIntValues( [Values(1, 2, 3)]int x, [Values(10, 20)]int y) { } static object[] ZeroData = new object[0]; static object[] GoodData = new object[] { new object[] { 12, 3 }, new object[] { 12, 4 }, new object[] { 12, 6 } }; static object[] BadData = new object[] { new object[] { 12, 3, 4 }, new object[] { 12, 4, 3 }, new object[] { 12, 6, 2 } }; [DatapointSource] int[] ints = new int[] { 1, 2, 3 }; #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestTools.StackSdk.Dtyp; using Microsoft.Protocols.TestTools.StackSdk.Messages; using Microsoft.Protocols.TestTools.StackSdk.Messages.Runtime.Marshaling; namespace Microsoft.Protocols.TestTools.StackSdk.Security.Pac { /// <summary> /// Facade of Pac utility. /// </summary> public static class PacUtility { /// <summary> /// The length of NTLM password length, defined in TD section 2.6.4. /// </summary> public const int NtlmPasswordLength = 16; /// <summary> /// The package name of NTLM, defined in TD endnote 9. /// </summary> public const string NtlmPackageName = "NTLM"; #region Public Methods public static PacType DecodePacType(byte[] buffer) { return new PacType(buffer); } /// <summary> /// Creates an empty KerbValidationInfo instance. /// </summary> /// <param name="native">native structure contains kerb validation information.</param> /// <returns>The created KerbValidationInfo instance.</returns> public static KerbValidationInfo CreateKerbValidationInfoBuffer(KERB_VALIDATION_INFO native) { KerbValidationInfo kerbInfo = new KerbValidationInfo(); kerbInfo.NativeKerbValidationInfo = native; return kerbInfo; } /// <summary> /// Creates an PacClientInfo instance using the specified clientId and name. /// </summary> /// <param name="clientId">A FileTime that contains the Kerberos initial /// ticket-granting ticket TGT authentication time, as specified in [RFC4120] /// section 5.3.</param> /// <param name="name">The client's account name</param> /// <returns>The created PacClientInfo instance.</returns> public static PacClientInfo CreateClientInfoBuffer(_FILETIME clientId, string name) { PacClientInfo clientInfo = new PacClientInfo(); clientInfo.NativePacClientInfo.ClientId = clientId; clientInfo.NativePacClientInfo.Name = name.ToCharArray(); clientInfo.NativePacClientInfo.NameLength = (ushort)(name.Length * 2); return clientInfo; } /// <summary> /// Creates an UpnDnsInfo instance using the specified flag, upn and dnsDomain. /// </summary> /// <param name="flag">U means The user account object does not have the /// userPrincipalName attribute ([MS-ADA3] section 2.348) set.</param> /// <param name="upn">The UPN information.</param> /// <param name="dnsDomain">The DNS information.</param> /// <returns>The created UpnDnsInfo instance.</returns> public static UpnDnsInfo CreateUpnDnsInfoBuffer(UPN_DNS_INFO_Flags_Values flag, string upn, string dnsDomain) { UpnDnsInfo upnDnsInfo = new UpnDnsInfo(); upnDnsInfo.NativeUpnDnsInfo.Flags = flag; upnDnsInfo.Upn = upn; upnDnsInfo.DnsDomain = dnsDomain; return upnDnsInfo; } /// <summary> /// Creates an S4uDelegationInfo instance using the specified s4U2proxyTarget and /// s4UTransitedServices. /// </summary> /// <param name="s4U2proxyTarget">the name of the principal to whom the application /// can be constraint delegated.</param> /// <param name="s4UTransitedServices">The list of all services that configured to /// be delegated.</param> /// <returns>The created S4uDelegationInfo instance.</returns> public static S4uDelegationInfo CreateS4uInfoBuffer( string s4U2proxyTarget, params string[] s4UTransitedServices) { S4uDelegationInfo s4uInfo = new S4uDelegationInfo(); s4uInfo.NativeS4uDelegationInfo.S4U2proxyTarget = DtypUtility.ToRpcUnicodeString(s4U2proxyTarget); s4uInfo.NativeS4uDelegationInfo.TransitedListSize = (uint)s4UTransitedServices.Length; _RPC_UNICODE_STRING[] transitedServiceArray = new _RPC_UNICODE_STRING[s4UTransitedServices.Length]; for (int i = 0; i < transitedServiceArray.Length; i++) { transitedServiceArray[i] = DtypUtility.ToRpcUnicodeString(s4UTransitedServices[i]); } s4uInfo.NativeS4uDelegationInfo.S4UTransitedServices = transitedServiceArray; return s4uInfo; } /// <summary> /// Creates an PacCredentialInfo instance using the specified Type and credentials. /// </summary> /// <param name="type">Encryption Type.</param> /// <param name="key">The encrypt key.</param> /// <param name="credentials">A list of security package supplemental credentials.</param> /// <returns>The created PacCredentialInfo instance.</returns> /// <exception cref="ArgumentOutOfRangeException">Type is not defined.</exception> public static PacCredentialInfo CreateCredentialInfoBuffer( EncryptionType_Values type, byte[] key, _SECPKG_SUPPLEMENTAL_CRED[] credentials) { PacCredentialInfo credentialInfo = new PacCredentialInfo(); credentialInfo.NativePacCredentialInfo.EncryptionType = type; _PAC_CREDENTIAL_DATA credentialData = new _PAC_CREDENTIAL_DATA(); credentialData.CredentialCount = (uint)credentials.Length; credentialData.Credentials = credentials; credentialInfo.Encrypt(credentialData, key); return credentialInfo; } /// <summary> /// Creates an PacType instance using the specified signature types and PacInfoBuffers /// </summary> /// <param name="serverSignatureType">Server signature signatureType.</param> /// <param name="serverSignKey">The server signature key used to generate server signature.</param> /// <param name="kdcSignatureType">KDC signature Type.</param> /// <param name="kdcSignKey">The KDC signature key used to generate KDC signature.</param> /// <param name="pacInfoBuffers">A list of PacInfoBuffer used to create the PacType. /// Note: DO NOT include the signatures (server signature and KDC signature)!</param> /// <returns>The created PacType instance.</returns> public static PacType CreatePacType( PAC_SIGNATURE_DATA_SignatureType_Values serverSignatureType, byte[] serverSignKey, PAC_SIGNATURE_DATA_SignatureType_Values kdcSignatureType, byte[] kdcSignKey, params PacInfoBuffer[] pacInfoBuffers) { return new PacType( serverSignatureType, serverSignKey, kdcSignatureType, kdcSignKey, pacInfoBuffers); } #endregion #region Internal Methods /// <summary> /// Unmarshals data from an NDR-encoded byte array to an object. /// </summary> /// <typeparam name="T">Type of the decoded object.</typeparam> /// <param name="buffer">The byte array containing NDR-encoded data.</param> /// <param name="index">Begin of encoded data.</param> /// <param name="count">Size of encoded data.</param> /// <param name="formatStringOffset">Format string offset of the data Type.</param> /// <returns>The object containing data in the byte array.</returns> internal static T NdrUnmarshal<T>(byte[] buffer, int index, int count, int formatStringOffset, bool force32Bit = true, int alignment = 4) where T : struct { using (PickleMarshaller marshaller = new PickleMarshaller(FormatString.Pac)) { return marshaller.Decode<T>(buffer, index, count, formatStringOffset, force32Bit, alignment); } } /// <summary> /// Marshals data from an object to an NDR-encoded byte array. /// </summary> /// <param name="obj">The pointer to an unmanaged block of memory /// which contains the content of object.</param> /// <param name="formatStringOffset">Format string offset of the data Type.</param> /// <returns>The byte array of NDR-encoded data.</returns> internal static byte[] NdrMarshal(IntPtr obj, int formatStringOffset) { using (PickleMarshaller marshaller = new PickleMarshaller(FormatString.Pac)) { return marshaller.Encode(obj, formatStringOffset); } } /// <summary> /// Read an object from the specified buffer using Channel. /// </summary> /// <typeparam name="T">The type of the object. Vary length members /// must have attributes "StaticSize" or "Size" defined.</typeparam> /// <param name="buffer">The buffer contains object content.</param> /// <returns>The object read from buffer.</returns> internal static T MemoryToObject<T>(byte[] buffer) { return MemoryToObject<T>(buffer, 0, buffer.Length); } /// <summary> /// Read an object from the specified buffer using Channel, /// beginning from <paramref name="index"/> of the <paramref name="buffer"/>, /// totally read <paramref name="count"/> bytes. /// </summary> /// <typeparam name="T">The type of the object. Vary length members /// must have attributes "StaticSize" or "Size" defined.</typeparam> /// <param name="buffer">The buffer contains object content.</param> /// <param name="index">The zero-based index from which to begin reading.</param> /// <param name="count">The maximum number of bytes to be read from the buffer.</param> /// <returns>The object read from the buffer.</returns> internal static T MemoryToObject<T>(byte[] buffer, int index, int count) { using (MemoryStream stream = new MemoryStream(buffer, index, count, false)) { using (Channel channel = new Channel(null, stream)) { return channel.Read<T>(); } } } /// <summary> /// Write an object to the specified buffer using Channel. /// </summary> /// <typeparam name="T">The type of the object. Vary length members /// must have attributes "StaticSize" or "Size" defined.</typeparam> /// <param name="obj">The object to be written to the buffer.</param> /// <returns>The buffer contains object content.</returns> internal static byte[] ObjectToMemory<T>(T obj) { using (MemoryStream stream = new MemoryStream()) { using (Channel channel = new Channel(null, stream)) { channel.Write(obj); } byte[] buffer = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(buffer, 0, buffer.Length); return buffer; } } /// <summary> /// Align offset to specified align unit, for example 8. /// </summary> /// <param name="offset">An int value to be aligned to specified boundary.</param> /// <param name="alignUnit">The boundary unit, for example 8. /// Must not be Zero (0).</param> /// <returns>The aligned offset.</returns> internal static int AlignTo(int offset, int alignUnit) { if (alignUnit == 0) { throw new ArgumentNullException("alignUnit"); } if (offset % alignUnit != 0) { int reminder = offset % alignUnit; offset += (alignUnit - reminder); } return offset; } #endregion } }
//#define REREAD_STATE_AFTER_WRITE_FAILED using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Xunit; using Xunit.Abstractions; using Orleans; using Orleans.Hosting; using Orleans.Runtime; using Orleans.TestingHost; using Orleans.Providers; using Orleans.Persistence.AzureStorage; using TestExtensions; using TestExtensions.Runners; using UnitTests.GrainInterfaces; // ReSharper disable RedundantAssignment // ReSharper disable UnusedVariable // ReSharper disable InconsistentNaming namespace Tester.AzureUtils.Persistence { /// <summary> /// Base_PersistenceGrainTests - a base class for testing persistence providers /// </summary> public abstract class Base_PersistenceGrainTests_AzureStore : OrleansTestingBase { private readonly ITestOutputHelper output; protected TestCluster HostedCluster { get; private set; } private readonly double timingFactor; protected readonly ILogger logger; private const int LoopIterations_Grain = 1000; private const int BatchSize = 100; private GrainPersistenceTestsRunner basicPersistenceTestsRunner; private const int MaxReadTime = 200; private const int MaxWriteTime = 2000; public class SiloBuilderConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.UseAzureStorageClustering(options => { options.ConnectionString = TestDefaultConfiguration.DataConnectionString; options.MaxStorageBusyRetries = 3; }); } } public class ClientBuilderConfigurator : IClientBuilderConfigurator { public void Configure(IConfiguration configuration, IClientBuilder clientBuilder) { clientBuilder.UseAzureStorageClustering(gatewayOptions => { gatewayOptions.ConnectionString = TestDefaultConfiguration.DataConnectionString; }); } } public static IProviderConfiguration GetNamedProviderConfigForShardedProvider(IEnumerable<KeyValuePair<string, IProviderConfiguration>> providers, string providerName) { var providerConfig = providers.Where(o => o.Key.Equals(providerName)).Select(o => o.Value); return providerConfig.First(); } public Base_PersistenceGrainTests_AzureStore(ITestOutputHelper output, BaseTestClusterFixture fixture) { this.output = output; this.logger = fixture.Logger; HostedCluster = fixture.HostedCluster; GrainFactory = fixture.GrainFactory; timingFactor = TestUtils.CalibrateTimings(); this.basicPersistenceTestsRunner = new GrainPersistenceTestsRunner(output, fixture); } public IGrainFactory GrainFactory { get; } protected Task Grain_AzureStore_Delete() { return this.basicPersistenceTestsRunner.Grain_GrainStorage_Delete(); } protected Task Grain_AzureStore_Read() { return this.basicPersistenceTestsRunner.Grain_GrainStorage_Read(); } protected Task Grain_GuidKey_AzureStore_Read_Write() { return this.basicPersistenceTestsRunner.Grain_GuidKey_GrainStorage_Read_Write(); } protected Task Grain_LongKey_AzureStore_Read_Write() { return this.basicPersistenceTestsRunner.Grain_LongKey_GrainStorage_Read_Write(); } protected Task Grain_LongKeyExtended_AzureStore_Read_Write() { return this.basicPersistenceTestsRunner.Grain_LongKeyExtended_GrainStorage_Read_Write(); } protected Task Grain_GuidKeyExtended_AzureStore_Read_Write() { return this.basicPersistenceTestsRunner.Grain_GuidKeyExtended_GrainStorage_Read_Write(); } protected Task Grain_Generic_AzureStore_Read_Write() { return this.basicPersistenceTestsRunner.Grain_Generic_GrainStorage_Read_Write(); } protected Task Grain_Generic_AzureStore_DiffTypes() { return this.basicPersistenceTestsRunner.Grain_Generic_GrainStorage_DiffTypes(); } protected Task Grain_AzureStore_SiloRestart() { return this.basicPersistenceTestsRunner.Grain_GrainStorage_SiloRestart(); } protected void Persistence_Perf_Activate() { const string testName = "Persistence_Perf_Activate"; int n = LoopIterations_Grain; TimeSpan target = TimeSpan.FromMilliseconds(MaxReadTime * n); // Timings for Activate RunPerfTest(n, testName, target, grainNoState => grainNoState.PingAsync(), grainMemory => grainMemory.DoSomething(), grainMemoryStore => grainMemoryStore.GetValue(), grainAzureStore => grainAzureStore.GetValue()); } protected void Persistence_Perf_Write() { const string testName = "Persistence_Perf_Write"; int n = LoopIterations_Grain; TimeSpan target = TimeSpan.FromMilliseconds(MaxWriteTime * n); // Timings for Write RunPerfTest(n, testName, target, grainNoState => grainNoState.EchoAsync(testName), grainMemory => grainMemory.DoWrite(n), grainMemoryStore => grainMemoryStore.DoWrite(n), grainAzureStore => grainAzureStore.DoWrite(n)); } protected void Persistence_Perf_Write_Reread() { const string testName = "Persistence_Perf_Write_Read"; int n = LoopIterations_Grain; TimeSpan target = TimeSpan.FromMilliseconds(MaxWriteTime * n); // Timings for Write RunPerfTest(n, testName + "--Write", target, grainNoState => grainNoState.EchoAsync(testName), grainMemory => grainMemory.DoWrite(n), grainMemoryStore => grainMemoryStore.DoWrite(n), grainAzureStore => grainAzureStore.DoWrite(n)); // Timings for Activate RunPerfTest(n, testName + "--ReRead", target, grainNoState => grainNoState.GetLastEchoAsync(), grainMemory => grainMemory.DoRead(), grainMemoryStore => grainMemoryStore.DoRead(), grainAzureStore => grainAzureStore.DoRead()); } protected async Task Persistence_Silo_StorageProvider_Azure(string providerName) { List<SiloHandle> silos = this.HostedCluster.GetActiveSilos().ToList(); foreach (var silo in silos) { var testHooks = this.HostedCluster.Client.GetTestHooks(silo); List<string> providers = (await testHooks.GetStorageProviderNames()).ToList(); Assert.True(providers.Contains(providerName), $"No storage provider found: {providerName}"); } } #region Utility functions // ---------- Utility functions ---------- protected void RunPerfTest(int n, string testName, TimeSpan target, Func<IEchoTaskGrain, Task> actionNoState, Func<IPersistenceTestGrain, Task> actionMemory, Func<IMemoryStorageTestGrain, Task> actionMemoryStore, Func<IGrainStorageTestGrain, Task> actionAzureTable) { IEchoTaskGrain[] noStateGrains = new IEchoTaskGrain[n]; IPersistenceTestGrain[] memoryGrains = new IPersistenceTestGrain[n]; IGrainStorageTestGrain[] azureStoreGrains = new IGrainStorageTestGrain[n]; IMemoryStorageTestGrain[] memoryStoreGrains = new IMemoryStorageTestGrain[n]; for (int i = 0; i < n; i++) { Guid id = Guid.NewGuid(); noStateGrains[i] = this.GrainFactory.GetGrain<IEchoTaskGrain>(id); memoryGrains[i] = this.GrainFactory.GetGrain<IPersistenceTestGrain>(id); azureStoreGrains[i] = this.GrainFactory.GetGrain<IGrainStorageTestGrain>(id); memoryStoreGrains[i] = this.GrainFactory.GetGrain<IMemoryStorageTestGrain>(id); } TimeSpan baseline, elapsed; elapsed = baseline = TestUtils.TimeRun(n, TimeSpan.Zero, testName + " (No state)", () => RunIterations(testName, n, i => actionNoState(noStateGrains[i]))); elapsed = TestUtils.TimeRun(n, baseline, testName + " (Local Memory Store)", () => RunIterations(testName, n, i => actionMemory(memoryGrains[i]))); elapsed = TestUtils.TimeRun(n, baseline, testName + " (Dev Store Grain Store)", () => RunIterations(testName, n, i => actionMemoryStore(memoryStoreGrains[i]))); elapsed = TestUtils.TimeRun(n, baseline, testName + " (Azure Table Store)", () => RunIterations(testName, n, i => actionAzureTable(azureStoreGrains[i]))); if (elapsed > target.Multiply(timingFactor)) { string msg = string.Format("{0}: Elapsed time {1} exceeds target time {2}", testName, elapsed, target); if (elapsed > target.Multiply(2.0 * timingFactor)) { Assert.True(false, msg); } else { throw new SkipException(msg); } } } private void RunIterations(string testName, int n, Func<int, Task> action) { List<Task> promises = new List<Task>(); Stopwatch sw = Stopwatch.StartNew(); // Fire off requests in batches for (int i = 0; i < n; i++) { var promise = action(i); promises.Add(promise); if ((i % BatchSize) == 0 && i > 0) { Task.WaitAll(promises.ToArray(), AzureTableDefaultPolicies.TableCreationTimeout); promises.Clear(); //output.WriteLine("{0} has done {1} iterations in {2} at {3} RPS", // testName, i, sw.Elapsed, i / sw.Elapsed.TotalSeconds); } } Task.WaitAll(promises.ToArray(), AzureTableDefaultPolicies.TableCreationTimeout); sw.Stop(); output.WriteLine("{0} completed. Did {1} iterations in {2} at {3} RPS", testName, n, sw.Elapsed, n / sw.Elapsed.TotalSeconds); } #endregion } } // ReSharper restore RedundantAssignment // ReSharper restore UnusedVariable // ReSharper restore InconsistentNaming
using Lucene.Net.Diagnostics; using Lucene.Net.Support; using System; using System.IO; namespace Lucene.Net.Util.Packed { /* * 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 DataInput = Lucene.Net.Store.DataInput; using IndexInput = Lucene.Net.Store.IndexInput; /// <summary> /// Reader for sequences of <see cref="long"/>s written with <see cref="BlockPackedWriter"/>. /// <para/> /// @lucene.internal /// </summary> /// <seealso cref="BlockPackedWriter"/> public sealed class BlockPackedReaderIterator { internal static long ZigZagDecode(long n) { return (((long)((ulong)n >> 1)) ^ -(n & 1)); } // same as DataInput.ReadVInt64 but supports negative values /// <summary> /// NOTE: This was readVLong() in Lucene. /// </summary> internal static long ReadVInt64(DataInput @in) { byte b = @in.ReadByte(); if ((sbyte)b >= 0) { return b; } long i = b & 0x7FL; b = @in.ReadByte(); i |= (b & 0x7FL) << 7; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 14; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 21; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 28; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 35; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 42; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0x7FL) << 49; if ((sbyte)b >= 0) { return i; } b = @in.ReadByte(); i |= (b & 0xFFL) << 56; return i; } internal DataInput @in; internal readonly int packedIntsVersion; internal long valueCount; internal readonly int blockSize; internal readonly long[] values; internal readonly Int64sRef valuesRef; internal byte[] blocks; internal int off; internal long ord; /// <summary> /// Sole constructor. </summary> /// <param name="blockSize"> The number of values of a block, must be equal to the /// block size of the <see cref="BlockPackedWriter"/> which has /// been used to write the stream. </param> public BlockPackedReaderIterator(DataInput @in, int packedIntsVersion, int blockSize, long valueCount) { PackedInt32s.CheckBlockSize(blockSize, AbstractBlockPackedWriter.MIN_BLOCK_SIZE, AbstractBlockPackedWriter.MAX_BLOCK_SIZE); this.packedIntsVersion = packedIntsVersion; this.blockSize = blockSize; this.values = new long[blockSize]; this.valuesRef = new Int64sRef(this.values, 0, 0); Reset(@in, valueCount); } /// <summary> /// Reset the current reader to wrap a stream of <paramref name="valueCount"/> /// values contained in <paramref name="in"/>. The block size remains unchanged. /// </summary> public void Reset(DataInput @in, long valueCount) { this.@in = @in; if (Debugging.AssertsEnabled) Debugging.Assert(valueCount >= 0); this.valueCount = valueCount; off = blockSize; ord = 0; } /// <summary> /// Skip exactly <paramref name="count"/> values. </summary> public void Skip(long count) { if (Debugging.AssertsEnabled) Debugging.Assert(count >= 0); if (ord + count > valueCount || ord + count < 0) { throw new EndOfStreamException(); } // 1. skip buffered values int skipBuffer = (int)Math.Min(count, blockSize - off); off += skipBuffer; ord += skipBuffer; count -= skipBuffer; if (count == 0L) { return; } // 2. skip as many blocks as necessary if (Debugging.AssertsEnabled) Debugging.Assert(off == blockSize); while (count >= blockSize) { int token = @in.ReadByte() & 0xFF; int bitsPerValue = (int)((uint)token >> AbstractBlockPackedWriter.BPV_SHIFT); if (bitsPerValue > 64) { throw new IOException("Corrupted"); } if ((token & AbstractBlockPackedWriter.MIN_VALUE_EQUALS_0) == 0) { ReadVInt64(@in); } long blockBytes = PackedInt32s.Format.PACKED.ByteCount(packedIntsVersion, blockSize, bitsPerValue); SkipBytes(blockBytes); ord += blockSize; count -= blockSize; } if (count == 0L) { return; } // 3. skip last values if (Debugging.AssertsEnabled) Debugging.Assert(count < blockSize); Refill(); ord += count; off += (int)count; } private void SkipBytes(long count) { if (@in is IndexInput input) { input.Seek(input.GetFilePointer() + count); } else { if (blocks == null) { blocks = new byte[blockSize]; } long skipped = 0; while (skipped < count) { int toSkip = (int)Math.Min(blocks.Length, count - skipped); @in.ReadBytes(blocks, 0, toSkip); skipped += toSkip; } } } /// <summary> /// Read the next value. </summary> public long Next() { if (ord == valueCount) { throw new EndOfStreamException(); } if (off == blockSize) { Refill(); } long value = values[off++]; ++ord; return value; } /// <summary> /// Read between <c>1</c> and <paramref name="count"/> values. </summary> public Int64sRef Next(int count) { if (Debugging.AssertsEnabled) Debugging.Assert(count > 0); if (ord == valueCount) { throw new EndOfStreamException(); } if (off == blockSize) { Refill(); } count = Math.Min(count, blockSize - off); count = (int)Math.Min(count, valueCount - ord); valuesRef.Offset = off; valuesRef.Length = count; off += count; ord += count; return valuesRef; } private void Refill() { int token = @in.ReadByte() & 0xFF; bool minEquals0 = (token & AbstractBlockPackedWriter.MIN_VALUE_EQUALS_0) != 0; int bitsPerValue = (int)((uint)token >> AbstractBlockPackedWriter.BPV_SHIFT); if (bitsPerValue > 64) { throw new IOException("Corrupted"); } long minValue = minEquals0 ? 0L : ZigZagDecode(1L + ReadVInt64(@in)); if (Debugging.AssertsEnabled) Debugging.Assert(minEquals0 || minValue != 0); if (bitsPerValue == 0) { Arrays.Fill(values, minValue); } else { PackedInt32s.IDecoder decoder = PackedInt32s.GetDecoder(PackedInt32s.Format.PACKED, packedIntsVersion, bitsPerValue); int iterations = blockSize / decoder.ByteValueCount; int blocksSize = iterations * decoder.ByteBlockCount; if (blocks == null || blocks.Length < blocksSize) { blocks = new byte[blocksSize]; } int valueCount = (int)Math.Min(this.valueCount - ord, blockSize); int blocksCount = (int)PackedInt32s.Format.PACKED.ByteCount(packedIntsVersion, valueCount, bitsPerValue); @in.ReadBytes(blocks, 0, blocksCount); decoder.Decode(blocks, 0, values, 0, iterations); if (minValue != 0) { for (int i = 0; i < valueCount; ++i) { values[i] += minValue; } } } off = 0; } /// <summary> /// Return the offset of the next value to read. </summary> public long Ord => ord; } }
using J2N.Threading; using NUnit.Framework; using System; using System.IO; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Store { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestCopyBytes : LuceneTestCase { private byte Value(int idx) { return unchecked((byte)((idx % 256) * (1 + (idx / 256)))); } [Test] public virtual void TestCopyBytesMem() { int num = AtLeast(10); for (int iter = 0; iter < num; iter++) { Directory dir = NewDirectory(); if (Verbose) { Console.WriteLine("TEST: iter=" + iter + " dir=" + dir); } // make random file IndexOutput @out = dir.CreateOutput("test", NewIOContext(Random)); var bytes = new byte[TestUtil.NextInt32(Random, 1, 77777)]; int size = TestUtil.NextInt32(Random, 1, 1777777); int upto = 0; int byteUpto = 0; while (upto < size) { bytes[byteUpto++] = Value(upto); upto++; if (byteUpto == bytes.Length) { @out.WriteBytes(bytes, 0, bytes.Length); byteUpto = 0; } } @out.WriteBytes(bytes, 0, byteUpto); Assert.AreEqual(size, @out.GetFilePointer()); @out.Dispose(); Assert.AreEqual(size, dir.FileLength("test")); // copy from test -> test2 IndexInput @in = dir.OpenInput("test", NewIOContext(Random)); @out = dir.CreateOutput("test2", NewIOContext(Random)); upto = 0; while (upto < size) { if (Random.NextBoolean()) { @out.WriteByte(@in.ReadByte()); upto++; } else { int chunk = Math.Min(TestUtil.NextInt32(Random, 1, bytes.Length), size - upto); @out.CopyBytes(@in, chunk); upto += chunk; } } Assert.AreEqual(size, upto); @out.Dispose(); @in.Dispose(); // verify IndexInput in2 = dir.OpenInput("test2", NewIOContext(Random)); upto = 0; while (upto < size) { if (Random.NextBoolean()) { var v = in2.ReadByte(); Assert.AreEqual(Value(upto), v); upto++; } else { int limit = Math.Min(TestUtil.NextInt32(Random, 1, bytes.Length), size - upto); in2.ReadBytes(bytes, 0, limit); for (int byteIdx = 0; byteIdx < limit; byteIdx++) { Assert.AreEqual(Value(upto), bytes[byteIdx]); upto++; } } } in2.Dispose(); dir.DeleteFile("test"); dir.DeleteFile("test2"); dir.Dispose(); } } // LUCENE-3541 [Test] public virtual void TestCopyBytesWithThreads() { int datalen = TestUtil.NextInt32(Random, 101, 10000); byte[] data = new byte[datalen]; Random.NextBytes(data); Directory d = NewDirectory(); IndexOutput output = d.CreateOutput("data", IOContext.DEFAULT); output.WriteBytes(data, 0, datalen); output.Dispose(); IndexInput input = d.OpenInput("data", IOContext.DEFAULT); IndexOutput outputHeader = d.CreateOutput("header", IOContext.DEFAULT); // copy our 100-byte header outputHeader.CopyBytes(input, 100); outputHeader.Dispose(); // now make N copies of the remaining bytes CopyThread[] copies = new CopyThread[10]; for (int i = 0; i < copies.Length; i++) { copies[i] = new CopyThread((IndexInput)input.Clone(), d.CreateOutput("copy" + i, IOContext.DEFAULT)); } for (int i = 0; i < copies.Length; i++) { copies[i].Start(); } for (int i = 0; i < copies.Length; i++) { copies[i].Join(); } for (int i = 0; i < copies.Length; i++) { IndexInput copiedData = d.OpenInput("copy" + i, IOContext.DEFAULT); byte[] dataCopy = new byte[datalen]; System.Buffer.BlockCopy(data, 0, dataCopy, 0, 100); // copy the header for easy testing copiedData.ReadBytes(dataCopy, 100, datalen - 100); Assert.AreEqual(data, dataCopy); copiedData.Dispose(); } input.Dispose(); d.Dispose(); } internal class CopyThread : ThreadJob { private readonly IndexInput src; private readonly IndexOutput dst; internal CopyThread(IndexInput src, IndexOutput dst) { this.src = src; this.dst = dst; } public override void Run() { try { dst.CopyBytes(src, src.Length - 100); dst.Dispose(); } catch (IOException ex) { throw new Exception(ex.ToString(), ex); } } } } }
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; /// @file /// @addtogroup flatbuffers_csharp_api /// @{ namespace FlatBuffers { /// <summary> /// Responsible for building up and accessing a FlatBuffer formatted byte /// array (via ByteBuffer). /// </summary> public class FlatBufferBuilder { private int _space; private ByteBuffer _bb; private int _minAlign = 1; // The vtable for the current table (if _vtableSize >= 0) private int[] _vtable = new int[16]; // The size of the vtable. -1 indicates no vtable private int _vtableSize = -1; // Starting offset of the current struct/table. private int _objectStart; // List of offsets of all vtables. private int[] _vtables = new int[16]; // Number of entries in `vtables` in use. private int _numVtables = 0; // For the current vector being built. private int _vectorNumElems = 0; /// <summary> /// Create a FlatBufferBuilder with a given initial size. /// </summary> /// <param name="initialSize"> /// The initial size to use for the internal buffer. /// </param> public FlatBufferBuilder(int initialSize) { if (initialSize <= 0) throw new ArgumentOutOfRangeException("initialSize", initialSize, "Must be greater than zero"); _space = initialSize; _bb = new ByteBuffer(new byte[initialSize]); } /// <summary> /// Reset the FlatBufferBuilder by purging all data that it holds. /// </summary> public void Clear() { _space = _bb.Length; _bb.Reset(); _minAlign = 1; while (_vtableSize > 0) _vtable[--_vtableSize] = 0; _vtableSize = -1; _objectStart = 0; _numVtables = 0; _vectorNumElems = 0; } /// <summary> /// Gets and sets a Boolean to disable the optimization when serializing /// default values to a Table. /// /// In order to save space, fields that are set to their default value /// don't get serialized into the buffer. /// </summary> public bool ForceDefaults { get; set; } /// @cond FLATBUFFERS_INTERNAL public int Offset { get { return _bb.Length - _space; } } public void Pad(int size) { _bb.PutByte(_space -= size, 0, size); } // Doubles the size of the ByteBuffer, and copies the old data towards // the end of the new buffer (since we build the buffer backwards). void GrowBuffer() { var oldBuf = _bb.Data; var oldBufSize = oldBuf.Length; if ((oldBufSize & 0xC0000000) != 0) throw new Exception( "FlatBuffers: cannot grow buffer beyond 2 gigabytes."); var newBufSize = oldBufSize << 1; var newBuf = new byte[newBufSize]; Buffer.BlockCopy(oldBuf, 0, newBuf, newBufSize - oldBufSize, oldBufSize); _bb = new ByteBuffer(newBuf, newBufSize); } // Prepare to write an element of `size` after `additional_bytes` // have been written, e.g. if you write a string, you need to align // such the int length field is aligned to SIZEOF_INT, and the string // data follows it directly. // If all you need to do is align, `additional_bytes` will be 0. public void Prep(int size, int additionalBytes) { // Track the biggest thing we've ever aligned to. if (size > _minAlign) _minAlign = size; // Find the amount of alignment needed such that `size` is properly // aligned after `additional_bytes` var alignSize = ((~((int)_bb.Length - _space + additionalBytes)) + 1) & (size - 1); // Reallocate the buffer if needed. while (_space < alignSize + size + additionalBytes) { var oldBufSize = (int)_bb.Length; GrowBuffer(); _space += (int)_bb.Length - oldBufSize; } if (alignSize > 0) Pad(alignSize); } public void PutBool(bool x) { _bb.PutByte(_space -= sizeof(byte), (byte)(x ? 1 : 0)); } public void PutSbyte(sbyte x) { _bb.PutSbyte(_space -= sizeof(sbyte), x); } public void PutByte(byte x) { _bb.PutByte(_space -= sizeof(byte), x); } public void PutShort(short x) { _bb.PutShort(_space -= sizeof(short), x); } public void PutUshort(ushort x) { _bb.PutUshort(_space -= sizeof(ushort), x); } public void PutInt(int x) { _bb.PutInt(_space -= sizeof(int), x); } public void PutUint(uint x) { _bb.PutUint(_space -= sizeof(uint), x); } public void PutLong(long x) { _bb.PutLong(_space -= sizeof(long), x); } public void PutUlong(ulong x) { _bb.PutUlong(_space -= sizeof(ulong), x); } public void PutFloat(float x) { _bb.PutFloat(_space -= sizeof(float), x); } public void PutDouble(double x) { _bb.PutDouble(_space -= sizeof(double), x); } /// @endcond /// <summary> /// Add a `bool` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `bool` to add to the buffer.</param> public void AddBool(bool x) { Prep(sizeof(byte), 0); PutBool(x); } /// <summary> /// Add a `sbyte` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `sbyte` to add to the buffer.</param> public void AddSbyte(sbyte x) { Prep(sizeof(sbyte), 0); PutSbyte(x); } /// <summary> /// Add a `byte` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `byte` to add to the buffer.</param> public void AddByte(byte x) { Prep(sizeof(byte), 0); PutByte(x); } /// <summary> /// Add a `short` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `short` to add to the buffer.</param> public void AddShort(short x) { Prep(sizeof(short), 0); PutShort(x); } /// <summary> /// Add an `ushort` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `ushort` to add to the buffer.</param> public void AddUshort(ushort x) { Prep(sizeof(ushort), 0); PutUshort(x); } /// <summary> /// Add an `int` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `int` to add to the buffer.</param> public void AddInt(int x) { Prep(sizeof(int), 0); PutInt(x); } /// <summary> /// Add an `uint` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `uint` to add to the buffer.</param> public void AddUint(uint x) { Prep(sizeof(uint), 0); PutUint(x); } /// <summary> /// Add a `long` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `long` to add to the buffer.</param> public void AddLong(long x) { Prep(sizeof(long), 0); PutLong(x); } /// <summary> /// Add an `ulong` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `ulong` to add to the buffer.</param> public void AddUlong(ulong x) { Prep(sizeof(ulong), 0); PutUlong(x); } /// <summary> /// Add a `float` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `float` to add to the buffer.</param> public void AddFloat(float x) { Prep(sizeof(float), 0); PutFloat(x); } /// <summary> /// Add a `double` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `double` to add to the buffer.</param> public void AddDouble(double x) { Prep(sizeof(double), 0); PutDouble(x); } /// <summary> /// Adds an offset, relative to where it will be written. /// </summary> /// <param name="off">The offset to add to the buffer.</param> public void AddOffset(int off) { Prep(sizeof(int), 0); // Ensure alignment is already done. if (off > Offset) throw new ArgumentException(); off = Offset - off + sizeof(int); PutInt(off); } /// @cond FLATBUFFERS_INTERNAL public void StartVector(int elemSize, int count, int alignment) { NotNested(); _vectorNumElems = count; Prep(sizeof(int), elemSize * count); Prep(alignment, elemSize * count); // Just in case alignment > int. } /// @endcond /// <summary> /// Writes data necessary to finish a vector construction. /// </summary> public VectorOffset EndVector() { PutInt(_vectorNumElems); return new VectorOffset(Offset); } /// @cond FLATBUFFERS_INTENRAL public void Nested(int obj) { // Structs are always stored inline, so need to be created right // where they are used. You'll get this assert if you created it // elsewhere. if (obj != Offset) throw new Exception( "FlatBuffers: struct must be serialized inline."); } public void NotNested() { // You should not be creating any other objects or strings/vectors // while an object is being constructed if (_vtableSize >= 0) throw new Exception( "FlatBuffers: object serialization must not be nested."); } public void StartObject(int numfields) { if (numfields < 0) throw new ArgumentOutOfRangeException("Flatbuffers: invalid numfields"); NotNested(); if (_vtable.Length < numfields) _vtable = new int[numfields]; _vtableSize = numfields; _objectStart = Offset; } // Set the current vtable at `voffset` to the current location in the // buffer. public void Slot(int voffset) { if (voffset >= _vtableSize) throw new IndexOutOfRangeException("Flatbuffers: invalid voffset"); _vtable[voffset] = Offset; } /// <summary> /// Adds a Boolean to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddBool(int o, bool x, bool d) { if (ForceDefaults || x != d) { AddBool(x); Slot(o); } } /// <summary> /// Adds a SByte to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddSbyte(int o, sbyte x, sbyte d) { if (ForceDefaults || x != d) { AddSbyte(x); Slot(o); } } /// <summary> /// Adds a Byte to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddByte(int o, byte x, byte d) { if (ForceDefaults || x != d) { AddByte(x); Slot(o); } } /// <summary> /// Adds a Int16 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddShort(int o, short x, int d) { if (ForceDefaults || x != d) { AddShort(x); Slot(o); } } /// <summary> /// Adds a UInt16 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUshort(int o, ushort x, ushort d) { if (ForceDefaults || x != d) { AddUshort(x); Slot(o); } } /// <summary> /// Adds an Int32 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddInt(int o, int x, int d) { if (ForceDefaults || x != d) { AddInt(x); Slot(o); } } /// <summary> /// Adds a UInt32 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUint(int o, uint x, uint d) { if (ForceDefaults || x != d) { AddUint(x); Slot(o); } } /// <summary> /// Adds an Int64 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddLong(int o, long x, long d) { if (ForceDefaults || x != d) { AddLong(x); Slot(o); } } /// <summary> /// Adds a UInt64 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUlong(int o, ulong x, ulong d) { if (ForceDefaults || x != d) { AddUlong(x); Slot(o); } } /// <summary> /// Adds a Single to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddFloat(int o, float x, double d) { if (ForceDefaults || x != d) { AddFloat(x); Slot(o); } } /// <summary> /// Adds a Double to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddDouble(int o, double x, double d) { if (ForceDefaults || x != d) { AddDouble(x); Slot(o); } } /// <summary> /// Adds a buffer offset to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddOffset(int o, int x, int d) { if (ForceDefaults || x != d) { AddOffset(x); Slot(o); } } /// @endcond /// <summary> /// Encode the string `s` in the buffer using UTF-8. /// </summary> /// <param name="s">The string to encode.</param> /// <returns> /// The offset in the buffer where the encoded string starts. /// </returns> public StringOffset CreateString(string s) { NotNested(); AddByte(0); var utf8StringLen = Encoding.UTF8.GetByteCount(s); StartVector(1, utf8StringLen, 1); Encoding.UTF8.GetBytes(s, 0, s.Length, _bb.Data, _space -= utf8StringLen); return new StringOffset(EndVector().Value); } /// @cond FLATBUFFERS_INTERNAL // Structs are stored inline, so nothing additional is being added. // `d` is always 0. public void AddStruct(int voffset, int x, int d) { if (x != d) { Nested(x); Slot(voffset); } } public int EndObject() { if (_vtableSize < 0) throw new InvalidOperationException( "Flatbuffers: calling endObject without a startObject"); AddInt((int)0); var vtableloc = Offset; // Write out the current vtable. for (int i = _vtableSize - 1; i >= 0 ; i--) { // Offset relative to the start of the table. short off = (short)(_vtable[i] != 0 ? vtableloc - _vtable[i] : 0); AddShort(off); // clear out written entry _vtable[i] = 0; } const int standardFields = 2; // The fields below: AddShort((short)(vtableloc - _objectStart)); AddShort((short)((_vtableSize + standardFields) * sizeof(short))); // Search for an existing vtable that matches the current one. int existingVtable = 0; for (int i = 0; i < _numVtables; i++) { int vt1 = _bb.Length - _vtables[i]; int vt2 = _space; short len = _bb.GetShort(vt1); if (len == _bb.GetShort(vt2)) { for (int j = sizeof(short); j < len; j += sizeof(short)) { if (_bb.GetShort(vt1 + j) != _bb.GetShort(vt2 + j)) { goto endLoop; } } existingVtable = _vtables[i]; break; } endLoop: { } } if (existingVtable != 0) { // Found a match: // Remove the current vtable. _space = _bb.Length - vtableloc; // Point table to existing vtable. _bb.PutInt(_space, existingVtable - vtableloc); } else { // No match: // Add the location of the current vtable to the list of // vtables. if (_numVtables == _vtables.Length) { // Arrays.CopyOf(vtables num_vtables * 2); var newvtables = new int[ _numVtables * 2]; Array.Copy(_vtables, newvtables, _vtables.Length); _vtables = newvtables; }; _vtables[_numVtables++] = Offset; // Point table to current vtable. _bb.PutInt(_bb.Length - vtableloc, Offset - vtableloc); } _vtableSize = -1; return vtableloc; } // This checks a required field has been set in a given table that has // just been constructed. public void Required(int table, int field) { int table_start = _bb.Length - table; int vtable_start = table_start - _bb.GetInt(table_start); bool ok = _bb.GetShort(vtable_start + field) != 0; // If this fails, the caller will show what field needs to be set. if (!ok) throw new InvalidOperationException("FlatBuffers: field " + field + " must be set"); } /// @endcond /// <summary> /// Finalize a buffer, pointing to the given `root_table`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> public void Finish(int rootTable) { Prep(_minAlign, sizeof(int)); AddOffset(rootTable); _bb.Position = _space; } /// <summary> /// Get the ByteBuffer representing the FlatBuffer. /// </summary> /// <remarks> /// This is typically only called after you call `Finish()`. /// The actual data starts at the ByteBuffer's current position, /// not necessarily at `0`. /// </remarks> /// <returns> /// Returns the ByteBuffer for this FlatBuffer. /// </returns> public ByteBuffer DataBuffer { get { return _bb; } } /// <summary> /// A utility function to copy and return the ByteBuffer data as a /// `byte[]`. /// </summary> /// <returns> /// A full copy of the FlatBuffer data. /// </returns> public byte[] SizedByteArray() { var newArray = new byte[_bb.Data.Length - _bb.Position]; Buffer.BlockCopy(_bb.Data, _bb.Position, newArray, 0, _bb.Data.Length - _bb.Position); return newArray; } /// <summary> /// Finalize a buffer, pointing to the given `rootTable`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="fileIdentifier"> /// A FlatBuffer file identifier to be added to the buffer before /// `root_table`. /// </param> public void Finish(int rootTable, string fileIdentifier) { Prep(_minAlign, sizeof(int) + FlatBufferConstants.FileIdentifierLength); if (fileIdentifier.Length != FlatBufferConstants.FileIdentifierLength) throw new ArgumentException( "FlatBuffers: file identifier must be length " + FlatBufferConstants.FileIdentifierLength, "fileIdentifier"); for (int i = FlatBufferConstants.FileIdentifierLength - 1; i >= 0; i--) { AddByte((byte)fileIdentifier[i]); } Finish(rootTable); } } } /// @}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Debug = System.Diagnostics.Debug; using Internal.IL.Stubs; using Internal.IL; using System.Threading; namespace Internal.TypeSystem.Interop { internal partial class InlineArrayType : MetadataType { public MetadataType ElementType { get; } public uint Length { get; } public override ModuleDesc Module { get; } public override string Name { get { return "_InlineArray__" + ElementType.Name + "__"+ Length; } } public override string Namespace { get { return "Internal.CompilerGenerated"; } } public override Instantiation Instantiation { get { return Instantiation.Empty; } } public override PInvokeStringFormat PInvokeStringFormat { get { return PInvokeStringFormat.AnsiClass; } } public override bool IsExplicitLayout { get { return false; } } public override bool IsSequentialLayout { get { return true; } } public override bool IsBeforeFieldInit { get { return false; } } public override MetadataType MetadataBaseType { get { return (MetadataType)Context.GetWellKnownType(WellKnownType.ValueType); } } public override bool IsSealed { get { return true; } } public override bool IsAbstract { get { return false; } } public override DefType ContainingType { get { return null; } } public override DefType[] ExplicitlyImplementedInterfaces { get { return Array.Empty<DefType>(); } } public override TypeSystemContext Context { get { return ElementType.Context; } } private InteropStateManager _interopStateManager; private MethodDesc [] _methods; public InlineArrayType(ModuleDesc owningModule, MetadataType elementType, uint length, InteropStateManager interopStateManager) { Debug.Assert(elementType.IsTypeDefinition); Debug.Assert(elementType.IsValueType); Debug.Assert(!elementType.IsGenericDefinition); Module = owningModule; ElementType = elementType; Length = length; _interopStateManager = interopStateManager; } public override ClassLayoutMetadata GetClassLayout() { ClassLayoutMetadata result = new ClassLayoutMetadata(); result.PackingSize = 0; result.Size = checked((int)Length * ElementType.GetElementSize().AsInt); return result; } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return false; } public override IEnumerable<MetadataType> GetNestedTypes() { return Array.Empty<MetadataType>(); } public override MetadataType GetNestedType(string name) { return null; } protected override MethodImplRecord[] ComputeVirtualMethodImplsForType() { return Array.Empty<MethodImplRecord>(); } public override MethodImplRecord[] FindMethodsImplWithMatchingDeclName(string name) { return Array.Empty<MethodImplRecord>(); } private int _hashCode; private void InitializeHashCode() { var hashCodeBuilder = new Internal.NativeFormat.TypeHashingAlgorithms.HashCodeBuilder(Namespace); if (Namespace.Length > 0) { hashCodeBuilder.Append("."); } hashCodeBuilder.Append(Name); _hashCode = hashCodeBuilder.ToHashCode(); } public override int GetHashCode() { if (_hashCode == 0) { InitializeHashCode(); } return _hashCode; } protected override TypeFlags ComputeTypeFlags(TypeFlags mask) { TypeFlags flags = 0; if ((mask & TypeFlags.HasGenericVarianceComputed) != 0) { flags |= TypeFlags.HasGenericVarianceComputed; } if ((mask & TypeFlags.CategoryMask) != 0) { flags |= TypeFlags.ValueType; } flags |= TypeFlags.HasFinalizerComputed; flags |= TypeFlags.IsByRefLikeComputed; return flags; } private void InitializeMethods() { MethodDesc[] methods = new MethodDesc[] { new InlineArrayMethod(this, InlineArrayMethodKind.Getter), new InlineArrayMethod(this, InlineArrayMethodKind.Setter), }; Interlocked.CompareExchange(ref _methods, methods, null); } public override IEnumerable<MethodDesc> GetMethods() { if (_methods == null) { InitializeMethods(); } return _methods; } public MethodDesc GetInlineArrayMethod(InlineArrayMethodKind kind) { if (_methods == null) { InitializeMethods(); } return _methods[(int)kind]; } public override IEnumerable<FieldDesc> GetFields() { return Array.Empty<FieldDesc>(); } private partial class InlineArrayMethod : ILStubMethod { private InlineArrayType _owningType; private InlineArrayMethodKind _kind; private MethodSignature _signature; public InlineArrayMethod(InlineArrayType owningType, InlineArrayMethodKind kind) { _owningType = owningType; _kind = kind; } public override TypeDesc OwningType { get { return _owningType; } } public override TypeSystemContext Context { get { return _owningType.Context; } } public override string Name { get { if (_kind == InlineArrayMethodKind.Getter) { return "get_Item"; } else { return "set_Item"; } } } public override MethodSignature Signature { get { if (_signature == null) { if (_kind == InlineArrayMethodKind.Getter) { _signature = new MethodSignature(MethodSignatureFlags.None, genericParameterCount: 0, returnType: _owningType.ElementType, parameters: new TypeDesc[] { Context.GetWellKnownType(WellKnownType.Int32) }); } else { _signature = new MethodSignature(MethodSignatureFlags.None, genericParameterCount: 0, returnType: Context.GetWellKnownType(WellKnownType.Void), parameters: new TypeDesc[] { Context.GetWellKnownType(WellKnownType.Int32), _owningType.ElementType }); } } return _signature; } } public override MethodIL EmitIL() { var emitter = new ILEmitter(); var codeStream = emitter.NewCodeStream(); var lIntermediate = emitter.NewCodeLabel(); var lCheck = emitter.NewCodeLabel(); var lValid = emitter.NewCodeLabel(); var vFlag = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Boolean)); var elementType = _owningType.ElementType; // Getter: // return ((ElementType*)(&this))[index]; // // Setter: // fixed (InlineArray* pThis = &this) //{ // ((ElementType*)pThis)[(ulong)index] = (ElementType)value; //} var vThis = emitter.NewLocal(_owningType.MakeByRefType()); codeStream.EmitLdArg(0); codeStream.EmitStLoc(vThis); codeStream.EmitLdLoc(vThis); codeStream.EmitLdArg(1); codeStream.Emit(ILOpcode.conv_i4); codeStream.Emit(ILOpcode.sizeof_, emitter.NewToken(elementType)); codeStream.Emit(ILOpcode.conv_i4); codeStream.Emit(ILOpcode.mul); codeStream.Emit(ILOpcode.conv_i); codeStream.Emit(ILOpcode.add); if (_kind == InlineArrayMethodKind.Getter) { codeStream.EmitLdInd(elementType); } else { codeStream.EmitLdArg(2); codeStream.EmitStInd(elementType); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.conv_u); codeStream.EmitStLoc(vThis); } codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } } } public enum InlineArrayMethodKind : byte { Getter = 0, Setter = 1 } }
using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using System.ComponentModel.Design; using System.Runtime.InteropServices; namespace WeifenLuo.WinFormsUI.Docking { partial class DockPanel { // This class comes from Jacob Slusser's MdiClientController class: // http://www.codeproject.com/cs/miscctrl/mdiclientcontroller.asp private class MdiClientController : NativeWindow, IComponent, IDisposable { private bool m_autoScroll = true; private BorderStyle m_borderStyle = BorderStyle.Fixed3D; private MdiClient m_mdiClient = null; private Form m_parentForm = null; private ISite m_site = null; public MdiClientController() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (Site != null && Site.Container != null) Site.Container.Remove(this); if (Disposed != null) Disposed(this, EventArgs.Empty); } } public bool AutoScroll { get { return m_autoScroll; } set { // By default the MdiClient control scrolls. It can appear though that // there are no scrollbars by turning them off when the non-client // area is calculated. I decided to expose this method following // the .NET vernacular of an AutoScroll property. m_autoScroll = value; if (MdiClient != null) UpdateStyles(); } } public BorderStyle BorderStyle { set { // Error-check the enum. if (!Enum.IsDefined(typeof(BorderStyle), value)) throw new InvalidEnumArgumentException(); m_borderStyle = value; if (MdiClient == null) return; // This property can actually be visible in design-mode, // but to keep it consistent with the others, // prevent this from being show at design-time. if (Site != null && Site.DesignMode) return; // There is no BorderStyle property exposed by the MdiClient class, // but this can be controlled by Win32 functions. A Win32 ExStyle // of WS_EX_CLIENTEDGE is equivalent to a Fixed3D border and a // Style of WS_BORDER is equivalent to a FixedSingle border. // This code is inspired Jason Dori's article: // "Adding designable borders to user controls". // http://www.codeproject.com/cs/miscctrl/CsAddingBorders.asp if (!Win32Helper.IsRunningOnMono) { // Get styles using Win32 calls int style = NativeMethods.GetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_STYLE); int exStyle = NativeMethods.GetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE); // Add or remove style flags as necessary. switch (m_borderStyle) { case BorderStyle.Fixed3D: exStyle |= (int)Win32.WindowExStyles.WS_EX_CLIENTEDGE; style &= ~((int)Win32.WindowStyles.WS_BORDER); break; case BorderStyle.FixedSingle: exStyle &= ~((int)Win32.WindowExStyles.WS_EX_CLIENTEDGE); style |= (int)Win32.WindowStyles.WS_BORDER; break; case BorderStyle.None: style &= ~((int)Win32.WindowStyles.WS_BORDER); exStyle &= ~((int)Win32.WindowExStyles.WS_EX_CLIENTEDGE); break; } // Set the styles using Win32 calls NativeMethods.SetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_STYLE, style); NativeMethods.SetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE, exStyle); } // Cause an update of the non-client area. UpdateStyles(); } } public MdiClient MdiClient { get { return m_mdiClient; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Form ParentForm { get { return m_parentForm; } set { // If the ParentForm has previously been set, // unwire events connected to the old parent. if (m_parentForm != null) { m_parentForm.HandleCreated -= new EventHandler(ParentFormHandleCreated); m_parentForm.MdiChildActivate -= new EventHandler(ParentFormMdiChildActivate); } m_parentForm = value; if (m_parentForm == null) return; // If the parent form has not been created yet, // wait to initialize the MDI client until it is. if (m_parentForm.IsHandleCreated) { InitializeMdiClient(); RefreshProperties(); } else m_parentForm.HandleCreated += new EventHandler(ParentFormHandleCreated); m_parentForm.MdiChildActivate += new EventHandler(ParentFormMdiChildActivate); } } public ISite Site { get { return m_site; } set { m_site = value; if (m_site == null) return; // If the component is dropped onto a form during design-time, // set the ParentForm property. IDesignerHost host = (value.GetService(typeof(IDesignerHost)) as IDesignerHost); if (host != null) { Form parent = host.RootComponent as Form; if (parent != null) ParentForm = parent; } } } public void RenewMdiClient() { // Reinitialize the MdiClient and its properties. InitializeMdiClient(); RefreshProperties(); } public event EventHandler Disposed; public event EventHandler HandleAssigned; public event EventHandler MdiChildActivate; public event LayoutEventHandler Layout; protected virtual void OnHandleAssigned(EventArgs e) { // Raise the HandleAssigned event. if (HandleAssigned != null) HandleAssigned(this, e); } protected virtual void OnMdiChildActivate(EventArgs e) { // Raise the MdiChildActivate event if (MdiChildActivate != null) MdiChildActivate(this, e); } protected virtual void OnLayout(LayoutEventArgs e) { // Raise the Layout event if (Layout != null) Layout(this, e); } public event PaintEventHandler Paint; protected virtual void OnPaint(PaintEventArgs e) { // Raise the Paint event. if (Paint != null) Paint(this, e); } protected override void WndProc(ref Message m) { switch (m.Msg) { case (int)Win32.Msgs.WM_NCCALCSIZE: // If AutoScroll is set to false, hide the scrollbars when the control // calculates its non-client area. if (!AutoScroll) { if (!Win32Helper.IsRunningOnMono) { NativeMethods.ShowScrollBar(m.HWnd, (int)Win32.ScrollBars.SB_BOTH, 0 /*false*/); } } break; } base.WndProc(ref m); } private void ParentFormHandleCreated(object sender, EventArgs e) { // The form has been created, unwire the event, and initialize the MdiClient. this.m_parentForm.HandleCreated -= new EventHandler(ParentFormHandleCreated); InitializeMdiClient(); RefreshProperties(); } private void ParentFormMdiChildActivate(object sender, EventArgs e) { OnMdiChildActivate(e); } private void MdiClientLayout(object sender, LayoutEventArgs e) { OnLayout(e); } private void MdiClientHandleDestroyed(object sender, EventArgs e) { // If the MdiClient handle has been released, drop the reference and // release the handle. if (m_mdiClient != null) { m_mdiClient.HandleDestroyed -= new EventHandler(MdiClientHandleDestroyed); m_mdiClient = null; } ReleaseHandle(); } private void InitializeMdiClient() { // If the mdiClient has previously been set, unwire events connected // to the old MDI. if (MdiClient != null) { MdiClient.HandleDestroyed -= new EventHandler(MdiClientHandleDestroyed); MdiClient.Layout -= new LayoutEventHandler(MdiClientLayout); } if (ParentForm == null) return; // Get the MdiClient from the parent form. foreach (Control control in ParentForm.Controls) { // If the form is an MDI container, it will contain an MdiClient control // just as it would any other control. m_mdiClient = control as MdiClient; if (m_mdiClient == null) continue; // Assign the MdiClient Handle to the NativeWindow. ReleaseHandle(); AssignHandle(MdiClient.Handle); // Raise the HandleAssigned event. OnHandleAssigned(EventArgs.Empty); // Monitor the MdiClient for when its handle is destroyed. MdiClient.HandleDestroyed += new EventHandler(MdiClientHandleDestroyed); MdiClient.Layout += new LayoutEventHandler(MdiClientLayout); break; } } private void RefreshProperties() { // Refresh all the properties BorderStyle = m_borderStyle; AutoScroll = m_autoScroll; } private void UpdateStyles() { // To show style changes, the non-client area must be repainted. Using the // control's Invalidate method does not affect the non-client area. // Instead use a Win32 call to signal the style has changed. if (!Win32Helper.IsRunningOnMono) NativeMethods.SetWindowPos(MdiClient.Handle, IntPtr.Zero, 0, 0, 0, 0, Win32.FlagsSetWindowPos.SWP_NOACTIVATE | Win32.FlagsSetWindowPos.SWP_NOMOVE | Win32.FlagsSetWindowPos.SWP_NOSIZE | Win32.FlagsSetWindowPos.SWP_NOZORDER | Win32.FlagsSetWindowPos.SWP_NOOWNERZORDER | Win32.FlagsSetWindowPos.SWP_FRAMECHANGED); } } private MdiClientController m_mdiClientController = null; private MdiClientController GetMdiClientController() { if (m_mdiClientController == null) { m_mdiClientController = new MdiClientController(); m_mdiClientController.HandleAssigned += new EventHandler(MdiClientHandleAssigned); m_mdiClientController.MdiChildActivate += new EventHandler(ParentFormMdiChildActivate); m_mdiClientController.Layout += new LayoutEventHandler(MdiClient_Layout); } return m_mdiClientController; } private void ParentFormMdiChildActivate(object sender, EventArgs e) { if (GetMdiClientController().ParentForm == null) return; IDockContent content = GetMdiClientController().ParentForm.ActiveMdiChild as IDockContent; if (content == null) return; if (content.DockHandler.DockPanel == this && content.DockHandler.Pane != null) content.DockHandler.Pane.ActiveContent = content; } private bool MdiClientExists { get { return GetMdiClientController().MdiClient != null; } } private void SetMdiClientBounds(Rectangle bounds) { GetMdiClientController().MdiClient.Bounds = bounds; } private void SuspendMdiClientLayout() { if (GetMdiClientController().MdiClient != null) GetMdiClientController().MdiClient.SuspendLayout(); } private void ResumeMdiClientLayout(bool perform) { if (GetMdiClientController().MdiClient != null) GetMdiClientController().MdiClient.ResumeLayout(perform); } private void PerformMdiClientLayout() { if (GetMdiClientController().MdiClient != null) GetMdiClientController().MdiClient.PerformLayout(); } // Called when: // 1. DockPanel.DocumentStyle changed // 2. DockPanel.Visible changed // 3. MdiClientController.Handle assigned private void SetMdiClient() { MdiClientController controller = GetMdiClientController(); if (this.DocumentStyle == DocumentStyle.DockingMdi) { controller.AutoScroll = false; controller.BorderStyle = BorderStyle.None; if (MdiClientExists) controller.MdiClient.Dock = DockStyle.Fill; } else if (DocumentStyle == DocumentStyle.DockingSdi || DocumentStyle == DocumentStyle.DockingWindow) { controller.AutoScroll = true; controller.BorderStyle = BorderStyle.Fixed3D; if (MdiClientExists) controller.MdiClient.Dock = DockStyle.Fill; } else if (this.DocumentStyle == DocumentStyle.SystemMdi) { controller.AutoScroll = true; controller.BorderStyle = BorderStyle.Fixed3D; if (controller.MdiClient != null) { controller.MdiClient.Dock = DockStyle.None; controller.MdiClient.Bounds = SystemMdiClientBounds; } } } internal Rectangle RectangleToMdiClient(Rectangle rect) { if (MdiClientExists) return GetMdiClientController().MdiClient.RectangleToClient(rect); else return Rectangle.Empty; } } }
// // System.Messaging // // Authors: // Peter Van Isacker (sclytrack@planetinternet.be) // // (C) 2003 Peter Van Isacker // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.ComponentModel; using System.ComponentModel.Design; namespace System.Messaging { [TypeConverter (typeof(ExpandableObjectConverter))] public class DefaultPropertiesToSend { [MonoTODO] public DefaultPropertiesToSend() { } [DefaultValue (AcknowledgeTypes.None)] [MessagingDescription ("MsgAcknowledgeType")] public AcknowledgeTypes AcknowledgeType { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (null)] [MessagingDescription ("MsgAdministrationQueue")] public MessageQueue AdministrationQueue { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (0)] [MessagingDescription ("MsgAppSpecific")] public int AppSpecific { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (true)] [MessagingDescription ("MsgAttachSenderId")] public bool AttachSenderId { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (EncryptionAlgorithm.Rc2)] [MessagingDescription ("MsgEncryptionAlgorithm")] public EncryptionAlgorithm EncryptionAlgorithm { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [Editor ("System.ComponentModel.Design.ArrayEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)] [MessagingDescription ("MsgExtension")] public byte[] Extension { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (HashAlgorithm.Md5)] [MessagingDescription ("MsgHashAlgorithm")] public HashAlgorithm HashAlgorithm { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue ("")] [MessagingDescription ("MsgLabel")] public string Label { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (MessagePriority.Normal)] [MessagingDescription ("MsgPriority")] public MessagePriority Priority { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (false)] [MessagingDescription ("MsgRecoverable")] public bool Recoverable { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (null)] [MessagingDescription ("MsgResponseQueue")] public MessageQueue ResponseQueue { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [TypeConverter (typeof(TimeoutConverter))] [MessagingDescription ("MsgTimeToBeReceived")] public TimeSpan TimeToBeReceived { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [TypeConverter (typeof(TimeoutConverter))] [MessagingDescription ("MsgTimeToReachQueue")] public TimeSpan TimeToReachQueue { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (null)] [MessagingDescription ("MsgTransactionStatusQueue")] public MessageQueue TransactionStatusQueue { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (false)] [MessagingDescription ("MsgUseAuthentication")] public bool UseAuthentication { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (false)] [MessagingDescription ("MsgUseDeadLetterQueue")] public bool UseDeadLetterQueue { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (false)] [MessagingDescription ("MsgUseEncryption")] public bool UseEncryption { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (false)] [MessagingDescription ("MsgUseJournalQueue")] public bool UseJournalQueue { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } [DefaultValue (false)] [MessagingDescription ("MsgUseTracing")] public bool UseTracing { [MonoTODO] get {throw new NotImplementedException();} [MonoTODO] set {throw new NotImplementedException();} } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using Microsoft.Phone.Controls; using Xamarin.Forms.Internals; using Xamarin.Forms.Platform.WinPhone; using Expression = System.Linq.Expressions.Expression; namespace Xamarin.Forms { public static class Forms { static bool s_isInitialized; public static UIElement ConvertPageToUIElement(this Page page, PhoneApplicationPage applicationPage) { var application = new DefaultApplication(); application.MainPage = page; var result = new Platform.WinPhone.Platform(applicationPage); result.SetPage(page); return result.GetCanvas(); } public static void Init() { if (s_isInitialized) return; // Needed to prevent stripping of System.Windows.Interactivity // which is current only referenced in the XAML DataTemplates var eventTrigger = new System.Windows.Interactivity.EventTrigger(); string assemblyName = Assembly.GetExecutingAssembly().GetName().Name; System.Windows.Application.Current.Resources.MergedDictionaries.Add(new System.Windows.ResourceDictionary { Source = new Uri(string.Format("/{0};component/WPResources.xaml", assemblyName), UriKind.Relative) }); var accent = System.Windows.Application.Current.Resources["PhoneAccentBrush"] as SolidColorBrush; System.Windows.Media.Color color = accent.Color; Color.Accent = Color.FromRgba(color.R, color.G, color.B, color.A); Log.Listeners.Add(new DelegateLogListener((c, m) => Console.WriteLine("[{0}] {1}", m, c))); Device.PlatformServices = new WP8PlatformServices(); Device.Info = new WP8DeviceInfo(); Registrar.RegisterAll(new[] { typeof(ExportRendererAttribute), typeof(ExportCellAttribute), typeof(ExportImageSourceHandlerAttribute) }); Ticker.Default = new WinPhoneTicker(); Device.Idiom = TargetIdiom.Phone; ExpressionSearch.Default = new WinPhoneExpressionSearch(); s_isInitialized = true; } class DefaultApplication : Application { } internal class WP8DeviceInfo : DeviceInfo { internal const string BWPorientationChangedName = "Xamarin.WP8.OrientationChanged"; readonly double _scalingFactor; public WP8DeviceInfo() { MessagingCenter.Subscribe(this, BWPorientationChangedName, (FormsApplicationPage page, DeviceOrientation orientation) => { CurrentOrientation = orientation; }); Content content = System.Windows.Application.Current.Host.Content; // Scaling Factor for Windows Phone 8 is relative to WVGA: https://msdn.microsoft.com/en-us/library/windows/apps/jj206974(v=vs.105).aspx _scalingFactor = content.ScaleFactor / 100d; PixelScreenSize = new Size(content.ActualWidth * _scalingFactor, content.ActualHeight * _scalingFactor); ScaledScreenSize = new Size(content.ActualWidth, content.ActualHeight); } public override Size PixelScreenSize { get; } public override Size ScaledScreenSize { get; } public override double ScalingFactor { get { return _scalingFactor; } } protected override void Dispose(bool disposing) { MessagingCenter.Unsubscribe<FormsApplicationPage, DeviceOrientation>(this, BWPorientationChangedName); base.Dispose(disposing); } } sealed class WinPhoneExpressionSearch : IExpressionSearch { List<object> _results; Type _targeType; public List<T> FindObjects<T>(Expression expression) where T : class { _results = new List<object>(); _targeType = typeof(T); Visit(expression); return _results.Select(o => o as T).ToList(); } void Visit(Expression expression) { if (expression == null) return; switch (expression.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: case ExpressionType.UnaryPlus: Visit(((UnaryExpression)expression).Operand); break; case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.Power: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: var binary = (BinaryExpression)expression; Visit(binary.Left); Visit(binary.Right); Visit(binary.Conversion); break; case ExpressionType.TypeIs: Visit(((TypeBinaryExpression)expression).Expression); break; case ExpressionType.Conditional: var conditional = (ConditionalExpression)expression; Visit(conditional.Test); Visit(conditional.IfTrue); Visit(conditional.IfFalse); break; case ExpressionType.MemberAccess: VisitMemberAccess((MemberExpression)expression); break; case ExpressionType.Call: var methodCall = (MethodCallExpression)expression; Visit(methodCall.Object); VisitList(methodCall.Arguments, Visit); break; case ExpressionType.Lambda: Visit(((LambdaExpression)expression).Body); break; case ExpressionType.New: VisitList(((NewExpression)expression).Arguments, Visit); break; case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: VisitList(((NewArrayExpression)expression).Expressions, Visit); break; case ExpressionType.Invoke: var invocation = (InvocationExpression)expression; VisitList(invocation.Arguments, Visit); Visit(invocation.Expression); break; case ExpressionType.MemberInit: var init = (MemberInitExpression)expression; VisitList(init.NewExpression.Arguments, Visit); VisitList(init.Bindings, VisitBinding); break; case ExpressionType.ListInit: var init1 = (ListInitExpression)expression; VisitList(init1.NewExpression.Arguments, Visit); VisitList(init1.Initializers, initializer => VisitList(initializer.Arguments, Visit)); break; case ExpressionType.Constant: break; default: throw new ArgumentException(string.Format("Unhandled expression type: '{0}'", expression.NodeType)); } } void VisitBinding(MemberBinding binding) { switch (binding.BindingType) { case MemberBindingType.Assignment: Visit(((MemberAssignment)binding).Expression); break; case MemberBindingType.MemberBinding: VisitList(((MemberMemberBinding)binding).Bindings, VisitBinding); break; case MemberBindingType.ListBinding: VisitList(((MemberListBinding)binding).Initializers, initializer => VisitList(initializer.Arguments, Visit)); break; default: throw new ArgumentException(string.Format("Unhandled binding type '{0}'", binding.BindingType)); } } static void VisitList<TList>(IEnumerable<TList> list, Action<TList> visitor) { foreach (TList element in list) visitor(element); } void VisitMemberAccess(MemberExpression member) { if (member.Expression is ConstantExpression && member.Member is FieldInfo) { object container = ((ConstantExpression)member.Expression).Value; object value = ((FieldInfo)member.Member).GetValue(container); if (_targeType.IsInstanceOfType(value)) _results.Add(value); } Visit(member.Expression); } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- datablock SFXProfile(cheetahEngine) { preload = "1"; description = "AudioCloseLoop3D"; fileName = "art/sound/cheetah/cheetah_engine.ogg"; }; datablock SFXProfile(cheetahSqueal) { preload = "1"; description = "AudioDefault3D"; fileName = "art/sound/cheetah/cheetah_squeal.ogg"; }; datablock SFXProfile(hardImpact) { preload = "1"; description = "AudioDefault3D"; fileName = "art/sound/cheetah/hardImpact.ogg"; }; datablock SFXProfile(softImpact) { preload = "1"; description = "AudioDefault3D"; fileName = "art/sound/cheetah/softImpact.ogg"; }; datablock SFXProfile(DirtKickup) { preload = "1"; description = "AudioDefault3D"; fileName = "art/sound/cheetah/softImpact.ogg"; }; datablock SFXProfile(CheetahTurretFireSound) { filename = "art/sound/cheetah/turret_firing.wav"; description = BulletFireDesc; preload = true; }; datablock ParticleData(CheetahTireParticle) { textureName = "art/shapes/buggy/dustParticle"; dragCoefficient = "1.99902"; gravityCoefficient = "-0.100122"; inheritedVelFactor = "0.0998043"; constantAcceleration = 0.0; lifetimeMS = 1000; lifetimeVarianceMS = 400; colors[0] = "0.456693 0.354331 0.259843 1"; colors[1] = "0.456693 0.456693 0.354331 0"; sizes[0] = "0.997986"; sizes[1] = "3.99805"; sizes[2] = "1.0"; sizes[3] = "1.0"; times[0] = "0.0"; times[1] = "1"; times[2] = "1"; times[3] = "1"; }; datablock ParticleEmitterData(CheetahTireEmitter) { ejectionPeriodMS = 20; periodVarianceMS = 10; ejectionVelocity = "14.57"; velocityVariance = 1.0; ejectionOffset = 0.0; thetaMin = 0; thetaMax = 60; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; particles = "CheetahTireParticle"; blendStyle = "ADDITIVE"; }; datablock ProjectileData(TurretProjectile) { projectileShapeName = "art/shapes/weapons/SwarmGun/rocket.dts"; directDamage = 10; radiusDamage = 15; damageRadius = 3; areaImpulse = 1200; explosion = RocketLauncherExplosion; waterExplosion = RocketLauncherWaterExplosion; decal = ScorchRXDecal; splash = RocketSplash; muzzleVelocity = 250; velInheritFactor = 0.7; armingDelay = 0; lifetime = 5000; fadeDelay = 4500; bounceElasticity = 0; bounceFriction = 0; isBallistic = false; gravityMod = 0.80; damageType = "RocketDamage"; }; datablock ParticleEmitterData(TurretFireSmokeEmitter) { ejectionPeriodMS = 10; periodVarianceMS = 5; ejectionVelocity = 6.5; velocityVariance = 1.0; thetaMin = "0"; thetaMax = "0"; lifetimeMS = 350; particles = "GunFireSmoke"; blendStyle = "NORMAL"; softParticles = "0"; alignParticles = "0"; orientParticles = "0"; }; datablock ShapeBaseImageData(TurretImage) { // Basic Item properties shapeFile = "art/shapes/Cheetah/Cheetah_Turret.DAE"; emap = true; // Specify mount point & offset for 3rd person, and eye offset // for first person rendering. mountPoint = 1; firstPerson = false; // When firing from a point offset from the eye, muzzle correction // will adjust the muzzle vector to point to the eye LOS point. // Since this weapon doesn't actually fire from the muzzle point, // we need to turn this off. correctMuzzleVector = false; // Add the WeaponImage namespace as a parent, WeaponImage namespace // provides some hooks into the inventory system. className = "WeaponImage"; class = "WeaponImage"; // Projectile and Ammo ammo = BulletAmmo; projectile = TurretProjectile; projectileType = Projectile; projectileSpread = "0.01"; // Weapon lights up while firing lightColor = "0.992126 0.968504 0.708661 1"; lightRadius = "4"; lightDuration = "100"; lightType = "WeaponFireLight"; lightBrightness = 2; // Shake camera while firing. shakeCamera = false; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. useRemainderDT = true; // Initial start up state stateName[0] = "Preactivate"; stateTransitionOnLoaded[0] = "Activate"; stateTransitionOnNoAmmo[0] = "NoAmmo"; // Activating the gun. Called when the weapon is first // mounted and there is ammo. stateName[1] = "Activate"; stateTransitionOnTimeout[1] = "Ready"; stateTimeoutValue[1] = 0.5; stateSequence[1] = "Activate"; // Ready to fire, just waiting for the trigger stateName[2] = "Ready"; stateTransitionOnNoAmmo[2] = "NoAmmo"; stateTransitionOnTriggerDown[2] = "Fire"; // Fire the weapon. Calls the fire script which does // the actual work. stateName[3] = "Fire"; stateTransitionOnTimeout[3] = "Reload"; stateTimeoutValue[3] = 0.1; stateFire[3] = true; stateRecoil[3] = ""; stateAllowImageChange[3] = false; stateSequence[3] = "Fire"; stateSequenceRandomFlash[3] = true; // use muzzle flash sequence stateScript[3] = "onFire"; stateSound[3] = CheetahTurretFireSound; stateEmitter[3] = TurretFireSmokeEmitter; stateEmitterTime[3] = 0.025; // Play the reload animation, and transition into stateName[4] = "Reload"; stateTransitionOnNoAmmo[4] = "NoAmmo"; stateWaitForTimeout[4] = "0"; stateTransitionOnTimeout[4] = "Ready"; stateTimeoutValue[4] = 1.2; stateAllowImageChange[4] = false; stateSequence[4] = "Reload"; //stateEjectShell[4] = true; // No ammo in the weapon, just idle until something // shows up. Play the dry fire sound if the trigger is // pulled. stateName[5] = "NoAmmo"; stateTransitionOnAmmo[5] = "Reload"; stateSequence[5] = "NoAmmo"; stateTransitionOnTriggerDown[5] = "DryFire"; // No ammo dry fire stateName[6] = "DryFire"; stateTimeoutValue[6] = 1.0; stateTransitionOnTimeout[6] = "NoAmmo"; stateScript[6] = "onDryFire"; }; //----------------------------------------------------------------------------- // Information extacted from the shape. // // Wheel Sequences // spring# Wheel spring motion: time 0 = wheel fully extended, // the hub must be displaced, but not directly animated // as it will be rotated in code. // Other Sequences // steering Wheel steering: time 0 = full right, 0.5 = center // breakLight Break light, time 0 = off, 1 = breaking // // Wheel Nodes // hub# Wheel hub, the hub must be in it's upper position // from which the springs are mounted. // // The steering and animation sequences are optional. // The center of the shape acts as the center of mass for the car. //----------------------------------------------------------------------------- datablock WheeledVehicleTire(CheetahCarTire) { // Tires act as springs and generate lateral and longitudinal // forces to move the vehicle. These distortion/spring forces // are what convert wheel angular velocity into forces that // act on the rigid body. shapeFile = "art/shapes/Cheetah/wheel.DAE"; staticFriction = 4.2; kineticFriction = "1"; // Spring that generates lateral tire forces lateralForce = 18000; lateralDamping = 6000; lateralRelaxation = 1; // Spring that generates longitudinal tire forces longitudinalForce = 18000; longitudinalDamping = 4000; longitudinalRelaxation = 1; radius = "0.609998"; }; datablock WheeledVehicleTire(CheetahCarTireRear) { // Tires act as springs and generate lateral and longitudinal // forces to move the vehicle. These distortion/spring forces // are what convert wheel angular velocity into forces that // act on the rigid body. shapeFile = "art/shapes/Cheetah/wheelBack.DAE"; staticFriction = "7.2"; kineticFriction = "1"; // Spring that generates lateral tire forces lateralForce = "19000"; lateralDamping = 6000; lateralRelaxation = 1; // Spring that generates longitudinal tire forces longitudinalForce = 18000; longitudinalDamping = 4000; longitudinalRelaxation = 1; radius = "0.840293"; }; datablock WheeledVehicleSpring(CheetahCarSpring) { // Wheel suspension properties length = 0.5; // Suspension travel force = 2800; // Spring force damping = 3600; // Spring damping antiSwayForce = 3; // Lateral anti-sway force }; datablock WheeledVehicleData(CheetahCar) { category = "Vehicles"; shapeFile = "art/shapes/Cheetah/Cheetah_Body.DAE"; emap = 1; mountPose[0] = sitting; numMountPoints = 6; useEyePoint = true; // Use the vehicle's camera node rather than the player's maxSteeringAngle = 0.585; // Maximum steering angle, should match animation // 3rd person camera settings cameraRoll = false; // Roll the camera with the vehicle cameraMaxDist = 7.8; // Far distance from vehicle cameraOffset = 1.0; // Vertical offset from camera mount point cameraLag = "0.3"; // Velocity lag of camera cameraDecay = 1.25; // Decay per sec. rate of velocity lag // Rigid Body mass = "400"; massCenter = "0 0.5 0"; // Center of mass for rigid body massBox = "0 0 0"; // Size of box used for moment of inertia, // if zero it defaults to object bounding box drag = 0.6; // Drag coefficient bodyFriction = 0.6; bodyRestitution = 0.4; minImpactSpeed = 5; // Impacts over this invoke the script callback softImpactSpeed = 5; // Play SoftImpact Sound hardImpactSpeed = 15; // Play HardImpact Sound integration = 8; // Physics integration: TickSec/Rate collisionTol = "0.1"; // Collision distance tolerance contactTol = "0.4"; // Contact velocity tolerance // Engine engineTorque = 4300; // Engine power engineBrake = "5000"; // Braking when throttle is 0 brakeTorque = "10000"; // When brakes are applied maxWheelSpeed = 50; // Engine scale by current speed / max speed // Energy maxEnergy = 100; jetForce = 3000; minJetEnergy = 30; jetEnergyDrain = 2; // Sounds engineSound = cheetahEngine; //squealSound = cheetahSqueal; softImpactSound = softImpact; hardImpactSound = hardImpact; // Dynamic fields accessed via script nameTag = 'Cheetah'; maxDismountSpeed = 10; maxMountSpeed = 5; mountPose0 = "sitting"; tireEmitter = "CheetahTireEmitter"; dustEmitter = "CheetahTireEmitter"; dustHeight = "1"; // Mount slots turretSlot = 1; rightBrakeSlot = 2; leftBrakeSlot = 3; };
//------------------------------------------------------------------------------ // <copyright file="BaseValidator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Schema { using System.IO; using System.Diagnostics; using System.Xml; using System.Text; using System.Collections; #pragma warning disable 618 internal class BaseValidator { XmlSchemaCollection schemaCollection; IValidationEventHandling eventHandling; XmlNameTable nameTable; SchemaNames schemaNames; PositionInfo positionInfo; XmlResolver xmlResolver; Uri baseUri; protected SchemaInfo schemaInfo; protected XmlValidatingReaderImpl reader; protected XmlQualifiedName elementName; protected ValidationState context; protected StringBuilder textValue; protected string textString; protected bool hasSibling; protected bool checkDatatype; public BaseValidator(BaseValidator other) { reader = other.reader; schemaCollection = other.schemaCollection; eventHandling = other.eventHandling; nameTable = other.nameTable; schemaNames = other.schemaNames; positionInfo = other.positionInfo; xmlResolver = other.xmlResolver; baseUri = other.baseUri; elementName = other.elementName; } public BaseValidator(XmlValidatingReaderImpl reader, XmlSchemaCollection schemaCollection, IValidationEventHandling eventHandling) { Debug.Assert(schemaCollection == null || schemaCollection.NameTable == reader.NameTable); this.reader = reader; this.schemaCollection = schemaCollection; this.eventHandling = eventHandling; nameTable = reader.NameTable; positionInfo = PositionInfo.GetPositionInfo(reader); elementName = new XmlQualifiedName(); } public XmlValidatingReaderImpl Reader { get { return reader; } } public XmlSchemaCollection SchemaCollection { get { return schemaCollection; } } public XmlNameTable NameTable { get { return nameTable; } } public SchemaNames SchemaNames { get { if (schemaNames != null) { return schemaNames; } if (schemaCollection != null) { schemaNames = schemaCollection.GetSchemaNames(nameTable); } else { schemaNames = new SchemaNames(nameTable); } return schemaNames; } } public PositionInfo PositionInfo { get { return positionInfo; } } public XmlResolver XmlResolver { get { return xmlResolver; } set { xmlResolver = value; } } public Uri BaseUri { get { return baseUri; } set { baseUri = value; } } public ValidationEventHandler EventHandler { get { return (ValidationEventHandler)eventHandling.EventHandler; } } public SchemaInfo SchemaInfo { get { return schemaInfo; } set { schemaInfo = value; } } public IDtdInfo DtdInfo { get { return schemaInfo; } set { SchemaInfo tmpSchemaInfo = value as SchemaInfo; if (tmpSchemaInfo == null) { throw new XmlException(Res.Xml_InternalError, string.Empty); } this.schemaInfo = tmpSchemaInfo; } } public virtual bool PreserveWhitespace { get { return false; } } public virtual void Validate() { } public virtual void CompleteValidation() { } public virtual object FindId(string name) { return null; } public void ValidateText() { if (context.NeedValidateChildren) { if (context.IsNill) { SendValidationEvent(Res.Sch_ContentInNill, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace)); return; } ContentValidator contentValidator = context.ElementDecl.ContentValidator; XmlSchemaContentType contentType = contentValidator.ContentType; if (contentType == XmlSchemaContentType.ElementOnly) { ArrayList names = contentValidator.ExpectedElements(context, false); if (names == null) { SendValidationEvent(Res.Sch_InvalidTextInElement, XmlSchemaValidator.BuildElementName(context.LocalName, context.Namespace)); } else { Debug.Assert(names.Count > 0); SendValidationEvent(Res.Sch_InvalidTextInElementExpecting, new string[] { XmlSchemaValidator.BuildElementName(context.LocalName, context.Namespace), XmlSchemaValidator.PrintExpectedElements(names, false) }); } } else if (contentType == XmlSchemaContentType.Empty) { SendValidationEvent(Res.Sch_InvalidTextInEmpty, string.Empty); } if (checkDatatype) { SaveTextValue(reader.Value); } } } public void ValidateWhitespace() { if (context.NeedValidateChildren) { XmlSchemaContentType contentType = context.ElementDecl.ContentValidator.ContentType; if (context.IsNill) { SendValidationEvent(Res.Sch_ContentInNill, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace)); } if (contentType == XmlSchemaContentType.Empty) { SendValidationEvent(Res.Sch_InvalidWhitespaceInEmpty, string.Empty); } if (checkDatatype) { SaveTextValue(reader.Value); } } } private void SaveTextValue(string value) { if (textString.Length == 0) { textString = value; } else { if (!hasSibling) { textValue.Append(textString); hasSibling = true; } textValue.Append(value); } } protected void SendValidationEvent(string code) { SendValidationEvent(code, string.Empty); } protected void SendValidationEvent(string code, string[] args) { SendValidationEvent(new XmlSchemaException(code, args, reader.BaseURI, positionInfo.LineNumber, positionInfo.LinePosition)); } protected void SendValidationEvent(string code, string arg) { SendValidationEvent(new XmlSchemaException(code, arg, reader.BaseURI, positionInfo.LineNumber, positionInfo.LinePosition)); } protected void SendValidationEvent(string code, string arg1, string arg2) { SendValidationEvent(new XmlSchemaException(code, new string[] { arg1, arg2 }, reader.BaseURI, positionInfo.LineNumber, positionInfo.LinePosition)); } protected void SendValidationEvent(XmlSchemaException e) { SendValidationEvent(e, XmlSeverityType.Error); } protected void SendValidationEvent(string code, string msg, XmlSeverityType severity) { SendValidationEvent(new XmlSchemaException(code, msg, reader.BaseURI, positionInfo.LineNumber, positionInfo.LinePosition), severity); } protected void SendValidationEvent(string code, string[] args, XmlSeverityType severity) { SendValidationEvent(new XmlSchemaException(code, args, reader.BaseURI, positionInfo.LineNumber, positionInfo.LinePosition), severity); } protected void SendValidationEvent(XmlSchemaException e, XmlSeverityType severity) { if (eventHandling != null) { eventHandling.SendEvent(e, severity); } else if (severity == XmlSeverityType.Error) { throw e; } } protected static void ProcessEntity(SchemaInfo sinfo, string name, object sender, ValidationEventHandler eventhandler, string baseUri, int lineNumber, int linePosition) { SchemaEntity en; XmlSchemaException e = null; if (!sinfo.GeneralEntities.TryGetValue(new XmlQualifiedName(name), out en)) { // validation error, see xml spec [68] e = new XmlSchemaException(Res.Sch_UndeclaredEntity, name, baseUri, lineNumber, linePosition); } else if (en.NData.IsEmpty) { e = new XmlSchemaException(Res.Sch_UnparsedEntityRef, name, baseUri, lineNumber, linePosition); } if (e != null) { if (eventhandler != null) { eventhandler(sender, new ValidationEventArgs(e)); } else { throw e; } } } protected static void ProcessEntity(SchemaInfo sinfo, string name, IValidationEventHandling eventHandling, string baseUriStr, int lineNumber, int linePosition) { SchemaEntity en; string errorResId = null; if (!sinfo.GeneralEntities.TryGetValue(new XmlQualifiedName(name), out en)) { // validation error, see xml spec [68] errorResId = Res.Sch_UndeclaredEntity; } else if (en.NData.IsEmpty) { errorResId = Res.Sch_UnparsedEntityRef; } if (errorResId != null) { XmlSchemaException e = new XmlSchemaException(errorResId, name, baseUriStr, lineNumber, linePosition); if (eventHandling != null) { eventHandling.SendEvent(e, XmlSeverityType.Error); } else { throw e; } } } public static BaseValidator CreateInstance(ValidationType valType, XmlValidatingReaderImpl reader, XmlSchemaCollection schemaCollection, IValidationEventHandling eventHandling, bool processIdentityConstraints) { switch(valType) { case ValidationType.XDR: return new XdrValidator(reader, schemaCollection, eventHandling); case ValidationType.Schema: return new XsdValidator(reader, schemaCollection, eventHandling); case ValidationType.DTD: return new DtdValidator(reader, eventHandling, processIdentityConstraints); case ValidationType.Auto: return new AutoValidator(reader, schemaCollection, eventHandling); case ValidationType.None: return new BaseValidator(reader, schemaCollection, eventHandling); default: break; } return null; } } #pragma warning restore 618 }
// // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. //using System; using System.Collections.Generic; using Couchbase.Lite.Support; using Couchbase.Lite.Util; using Sharpen; namespace Couchbase.Lite.Support { /// <summary> /// Utility that queues up objects until the queue fills up or a time interval elapses, /// then passes objects, in groups of its capacity, to a client-supplied processor block. /// </summary> /// <remarks> /// Utility that queues up objects until the queue fills up or a time interval elapses, /// then passes objects, in groups of its capacity, to a client-supplied processor block. /// </remarks> public class Batcher<T> { private ScheduledExecutorService workExecutor; private ScheduledFuture<object> flushFuture; private int capacity; private int delay; private int scheduledDelay; private LinkedHashSet<T> inbox; private BatchProcessor<T> processor; private bool scheduled = false; private long lastProcessedTime; private sealed class _Runnable_31 : Runnable { public _Runnable_31(Batcher<T> _enclosing) { this._enclosing = _enclosing; } public void Run() { try { this._enclosing.ProcessNow(); } catch (Exception e) { // we don't want this to crash the batcher Log.E(Log.TagSync, this + ": BatchProcessor throw exception", e); } } private readonly Batcher<T> _enclosing; } private Runnable processNowRunnable; /// <summary>Initializes a batcher.</summary> /// <remarks>Initializes a batcher.</remarks> /// <param name="workExecutor">the work executor that performs actual work</param> /// <param name="capacity">The maximum number of objects to batch up. If the queue reaches this size, the queued objects will be sent to the processor immediately. /// </param> /// <param name="delay">The maximum waiting time to collect objects before processing them. In some circumstances objects will be processed sooner. /// </param> /// <param name="processor">The callback/block that will be called to process the objects. /// </param> public Batcher(ScheduledExecutorService workExecutor, int capacity, int delay, BatchProcessor <T> processor) { processNowRunnable = new _Runnable_31(this); this.workExecutor = workExecutor; this.capacity = capacity; this.delay = delay; this.processor = processor; } /// <summary>Adds multiple objects to the queue.</summary> /// <remarks>Adds multiple objects to the queue.</remarks> public virtual void QueueObjects(IList<T> objects) { lock (this) { Log.V(Log.TagSync, "%s: queueObjects called with %d objects. ", this, objects.Count ); if (objects.Count == 0) { return; } if (inbox == null) { inbox = new LinkedHashSet<T>(); } Log.V(Log.TagSync, "%s: inbox size before adding objects: %d", this, inbox.Count); Sharpen.Collections.AddAll(inbox, objects); ScheduleWithDelay(DelayToUse()); } } /// <summary>Adds an object to the queue.</summary> /// <remarks>Adds an object to the queue.</remarks> public virtual void QueueObject(T @object) { IList<T> objects = Arrays.AsList(@object); QueueObjects(objects); } /// <summary>Sends queued objects to the processor block (up to the capacity).</summary> /// <remarks>Sends queued objects to the processor block (up to the capacity).</remarks> public virtual void Flush() { ScheduleWithDelay(DelayToUse()); } /// <summary>Sends _all_ the queued objects at once to the processor block.</summary> /// <remarks> /// Sends _all_ the queued objects at once to the processor block. /// After this method returns, the queue is guaranteed to be empty. /// </remarks> public virtual void FlushAll() { while (inbox.Count > 0) { Unschedule(); IList<T> toProcess = new AList<T>(); Sharpen.Collections.AddAll(toProcess, inbox); processor.Process(toProcess); lastProcessedTime = Runtime.CurrentTimeMillis(); } } /// <summary>Empties the queue without processing any of the objects in it.</summary> /// <remarks>Empties the queue without processing any of the objects in it.</remarks> public virtual void Clear() { Log.V(Log.TagSync, "%s: clear() called, setting inbox to null", this); Unschedule(); inbox = null; } public virtual int Count() { lock (this) { if (inbox == null) { return 0; } return inbox.Count; } } private void ProcessNow() { Log.V(Log.TagSync, this + ": processNow() called"); scheduled = false; IList<T> toProcess = new AList<T>(); lock (this) { if (inbox == null || inbox.Count == 0) { Log.V(Log.TagSync, this + ": processNow() called, but inbox is empty"); return; } else { if (inbox.Count <= capacity) { Log.V(Log.TagSync, "%s: inbox.size() <= capacity, adding %d items from inbox -> toProcess" , this, inbox.Count); Sharpen.Collections.AddAll(toProcess, inbox); inbox = null; } else { Log.V(Log.TagSync, "%s: processNow() called, inbox size: %d", this, inbox.Count); int i = 0; foreach (T item in inbox) { toProcess.AddItem(item); i += 1; if (i >= capacity) { break; } } foreach (T item_1 in toProcess) { Log.V(Log.TagSync, "%s: processNow() removing %s from inbox", this, item_1); inbox.Remove(item_1); } Log.V(Log.TagSync, "%s: inbox.size() > capacity, moving %d items from inbox -> toProcess array" , this, toProcess.Count); // There are more objects left, so schedule them Real Soon: ScheduleWithDelay(DelayToUse()); } } } if (toProcess != null && toProcess.Count > 0) { Log.V(Log.TagSync, "%s: invoking processor with %d items ", this, toProcess.Count ); processor.Process(toProcess); } else { Log.V(Log.TagSync, "%s: nothing to process", this); } lastProcessedTime = Runtime.CurrentTimeMillis(); } private void ScheduleWithDelay(int suggestedDelay) { Log.V(Log.TagSync, "%s: scheduleWithDelay called with delay: %d ms", this, suggestedDelay ); if (scheduled && (suggestedDelay < scheduledDelay)) { Log.V(Log.TagSync, "%s: already scheduled and: %d < %d --> unscheduling", this, suggestedDelay , scheduledDelay); Unschedule(); } if (!scheduled) { Log.V(Log.TagSync, "not already scheduled"); scheduled = true; scheduledDelay = suggestedDelay; Log.V(Log.TagSync, "workExecutor.schedule() with delay: %d ms", suggestedDelay); flushFuture = workExecutor.Schedule(processNowRunnable, suggestedDelay, TimeUnit. Milliseconds); } } private void Unschedule() { Log.V(Log.TagSync, this + ": unschedule() called"); scheduled = false; if (flushFuture != null) { bool didCancel = flushFuture.Cancel(false); Log.V(Log.TagSync, "tried to cancel flushFuture, result: %s", didCancel); } else { Log.V(Log.TagSync, "flushFuture was null, doing nothing"); } } private int DelayToUse() { //initially set the delay to the default value for this Batcher int delayToUse = delay; //get the time interval since the last batch completed to the current system time long delta = (Runtime.CurrentTimeMillis() - lastProcessedTime); //if the time interval is greater or equal to the default delay then set the // delay so that the next batch gets scheduled to process immediately if (delta >= delay) { delayToUse = 0; } Log.V(Log.TagSync, "%s: delayToUse() delta: %d, delayToUse: %d, delay: %d", this, delta, delayToUse, delta); return delayToUse; } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // /* * Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DynamoDBv2.Model { /// <summary> /// Represents the data for an attribute. You can set one, and only one, of the elements. /// /// /// <para> /// Each attribute in an item is a name-value pair. An attribute can be single-valued /// or multi-valued set. For example, a book item can have title and authors attributes. /// Each book has one title but can have many authors. The multi-valued attribute is a /// set; duplicate values are not allowed. /// </para> /// </summary> public partial class AttributeValue { private MemoryStream _b; private bool? _bool; private List<MemoryStream> _bs = new List<MemoryStream>(); private List<AttributeValue> _l = new List<AttributeValue>(); private Dictionary<string, AttributeValue> _m = new Dictionary<string, AttributeValue>(); private string _n; private List<string> _ns = new List<string>(); private bool? _null; private string _s; private List<string> _ss = new List<string>(); /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public AttributeValue() { } /// <summary> /// Instantiates AttributeValue with the parameterized properties /// </summary> /// <param name="s">A String data type.</param> public AttributeValue(string s) { _s = s; } /// <summary> /// Instantiates AttributeValue with the parameterized properties /// </summary> /// <param name="ss">A String Set data type.</param> public AttributeValue(List<string> ss) { _ss = ss; } /// <summary> /// Gets and sets the property B. /// <para> /// A Binary data type. /// </para> /// </summary> public MemoryStream B { get { return this._b; } set { this._b = value; } } // Check to see if B property is set internal bool IsSetB() { return this._b != null; } /// <summary> /// Gets and sets the property BOOL. /// <para> /// A Boolean data type. /// </para> /// </summary> public bool BOOL { get { return this._bool.GetValueOrDefault(); } set { this._bool = value; } } /// <summary> /// This property is set to true if the property <seealso cref="BOOL"/> /// is set; false otherwise. /// This property can be used to determine if the related property /// was returned by a service response or if the related property /// should be sent to the service during a service call. /// </summary> /// <returns> /// True if the related property was set or will be sent to a service; false otherwise. /// </returns> public bool IsBOOLSet { get { return Amazon.Util.Internal.InternalSDKUtils.GetIsSet(this._bool); } set { Amazon.Util.Internal.InternalSDKUtils.SetIsSet(value, ref this._bool); } } // Check to see if BOOL property is set internal bool IsSetBOOL() { return this.IsBOOLSet; } /// <summary> /// Gets and sets the property BS. /// <para> /// A Binary Set data type. /// </para> /// </summary> public List<MemoryStream> BS { get { return this._bs; } set { this._bs = value; } } // Check to see if BS property is set internal bool IsSetBS() { return this._bs != null && this._bs.Count > 0; } /// <summary> /// Gets and sets the property L. /// <para> /// A List of attribute values. /// </para> /// </summary> public List<AttributeValue> L { get { return this._l; } set { this._l = value; } } /// <summary> /// This property is set to true if the property <seealso cref="L"/> /// is set; false otherwise. /// This property can be used to determine if the related property /// was returned by a service response or if the related property /// should be sent to the service during a service call. /// </summary> /// <returns> /// True if the related property was set or will be sent to a service; false otherwise. /// </returns> public bool IsLSet { get { return Amazon.Util.Internal.InternalSDKUtils.GetIsSet(this._l); } set { Amazon.Util.Internal.InternalSDKUtils.SetIsSet(value, ref this._l); } } // Check to see if L property is set internal bool IsSetL() { return this.IsLSet; } /// <summary> /// Gets and sets the property M. /// <para> /// A Map of attribute values. /// </para> /// </summary> public Dictionary<string, AttributeValue> M { get { return this._m; } set { this._m = value; } } /// <summary> /// This property is set to true if the property <seealso cref="M"/> /// is set; false otherwise. /// This property can be used to determine if the related property /// was returned by a service response or if the related property /// should be sent to the service during a service call. /// </summary> /// <returns> /// True if the related property was set or will be sent to a service; false otherwise. /// </returns> public bool IsMSet { get { return Amazon.Util.Internal.InternalSDKUtils.GetIsSet(this._m); } set { Amazon.Util.Internal.InternalSDKUtils.SetIsSet(value, ref this._m); } } // Check to see if M property is set internal bool IsSetM() { return this.IsMSet; } /// <summary> /// Gets and sets the property N. /// <para> /// A Number data type. /// </para> /// </summary> public string N { get { return this._n; } set { this._n = value; } } // Check to see if N property is set internal bool IsSetN() { return this._n != null; } /// <summary> /// Gets and sets the property NS. /// <para> /// A Number Set data type. /// </para> /// </summary> public List<string> NS { get { return this._ns; } set { this._ns = value; } } // Check to see if NS property is set internal bool IsSetNS() { return this._ns != null && this._ns.Count > 0; } /// <summary> /// Gets and sets the property NULL. /// <para> /// A Null data type. /// </para> /// </summary> public bool NULL { get { return this._null.GetValueOrDefault(); } set { this._null = value; } } // Check to see if NULL property is set internal bool IsSetNULL() { return this._null.HasValue; } /// <summary> /// Gets and sets the property S. /// <para> /// A String data type. /// </para> /// </summary> public string S { get { return this._s; } set { this._s = value; } } // Check to see if S property is set internal bool IsSetS() { return this._s != null; } /// <summary> /// Gets and sets the property SS. /// <para> /// A String Set data type. /// </para> /// </summary> public List<string> SS { get { return this._ss; } set { this._ss = value; } } // Check to see if SS property is set internal bool IsSetSS() { return this._ss != null && this._ss.Count > 0; } } }
using System; using System.IO; using UOArchitectInterface; using Server.Targeting; using System.Collections; using Server.Items; using Server.Mobiles; using Server.Multis; using System.Threading; using OrbServerSDK; using Server.Commands; namespace Server.Engines.UOArchitect { public class ExtractItemsRequest : BaseOrbToolRequest { private BoundingBoxPickerEx _picker; private Rect2DCol _rects = new Rect2DCol(); private Map _map = null; private DesignItemCol _items = new DesignItemCol(); private ExtractRequestArgs _args; private ArrayList _extractedMultiIds = new ArrayList(); public static void Initialize() { OrbRemoteServer.OrbServer.Register("UOAR_ExtractDesign", typeof(ExtractItemsRequest), AccessLevel.GameMaster, true); } public override void OnRequest(OrbClientInfo client, OrbRequestArgs args) { FindOnlineMobile(client); if(args == null) SendResponse(null); else if(!(args is ExtractRequestArgs)) SendResponse(null); else if(!this.IsOnline) SendResponse(null); _args = args as ExtractRequestArgs; if(_args.ItemSerials == null) { _picker = new BoundingBoxPickerEx(); _picker.OnCancelled += new BoundingBoxExCancelled(OnTargetCancelled); _picker.Begin( this.Mobile, new BoundingBoxCallback( BoundingBox_Callback ), null ); } else { ExtractItems(_args.ItemSerials); } } private void BoundingBox_Callback( Mobile from, Map map, Point3D start, Point3D end, object state ) { Utility.FixPoints( ref start, ref end ); Rectangle2D rect = new Rectangle2D(start, end); _map = map; _rects.Add(new Rect2D(rect.Start.X, rect.Start.Y, rect.Width, rect.Height)); if(_args.MultipleRects) { _picker.Begin( this.Mobile, new BoundingBoxCallback( BoundingBox_Callback ), null ); } else { ExtractItems(); } } private void ExtractItems(int[] itemSerials) { for(int i=0; i < itemSerials.Length; ++i) { Item item = World.FindItem(itemSerials[i]); if ( item != null && !(item is BaseMulti) ) { DesignItem designItem = new DesignItem(); designItem.ItemID = (short)item.ItemID; designItem.X = item.X; designItem.Y = item.Y; designItem.Z = item.Z; designItem.Hue = (short)item.Hue; _items.Add(designItem); } } ExtractResponse resp = null; if(_items.Count > 0) resp = new ExtractResponse(_items); else resp = null; SendResponse(resp); } private void ExtractItems() { foreach(Rect2D rect in _rects) { #region MobileSaver Rectangle2D realrectangle = new Rectangle2D( rect.TopX, rect.TopY, rect.Width, rect.Height ); foreach ( Mobile m in _map.GetMobilesInBounds( realrectangle ) ) { if ( m != null && m is BaseCreature ) { int saveflag = MobileSaver.GetSaveFlag( m ); if ( saveflag > 0 ) { DesignItem designItem = new DesignItem(); designItem.ItemID = (short)0x1; designItem.X = m.X; designItem.Y = m.Y; designItem.Z = m.Z + saveflag; designItem.Hue = (short)m.Hue; } } } #endregion for ( int x = 0; x <= rect.Width; ++x ) { for ( int y = 0; y <= rect.Height; ++y ) { int tileX = rect.TopX + x; int tileY = rect.TopY + y; Sector sector = _map.GetSector( tileX, tileY ); if (_args.NonStatic || _args.Static) { for ( int i = 0; i < sector.Items.Count; ++i ) { Item item = (Item)sector.Items[i]; if(!item.Visible) continue; else if( (!_args.NonStatic) && !(item is Static) ) continue; else if( (!_args.Static) && (item is Static) ) continue; else if( _args.MinZSet && item.Z < _args.MinZ) continue; else if( _args.MaxZSet && item.Z > _args.MaxZ) continue; int hue = 0; if(_args.ExtractHues) hue = item.Hue; if ( item.X == tileX && item.Y == tileY && !((item is BaseMulti) || (item is HouseSign))) { DesignItem designItem = new DesignItem(); designItem.ItemID = (short)item.ItemID; designItem.X = item.X; designItem.Y = item.Y; designItem.Z = item.Z; designItem.Hue = (short)hue; _items.Add(designItem); } // extract multi if(item is HouseFoundation) { HouseFoundation house = (HouseFoundation)item; if(_extractedMultiIds.IndexOf(house.Serial.Value) == -1) ExtractCustomMulti(house); } } } } } } ExtractResponse response = new ExtractResponse(_items); if(_args.Frozen) { response.Rects = _rects; response.Map = _map.Name; } // send response back to the UOAR tool SendResponse(response); } private void ExtractCustomMulti(HouseFoundation house) { _extractedMultiIds.Add(house.Serial.Value); for(int x=0; x < house.Components.Width; ++x) { for(int y=0; y < house.Components.Height; ++y) { StaticTile[] tiles = house.Components.Tiles[x][y]; for ( int i = 0; i < tiles.Length; ++i ) { DesignItem designItem = new DesignItem(); designItem.ItemID = (short)tiles[i].ID; designItem.X = x + house.Sign.Location.X; designItem.Y = (y + house.Sign.Location.Y) - (house.Components.Height - 1); designItem.Z = house.Location.Z + tiles[i].Z; _items.Add(designItem); } } } DesignItem sign = new DesignItem(); sign.ItemID = (short)(house.Sign.ItemID); sign.X = house.Sign.Location.X; sign.Y = house.Sign.Location.Y; sign.Z = house.Sign.Location.Z; _items.Add(sign); } private void OnTargetCancelled() { if(_rects.Count > 0) ExtractItems(); else SendResponse(null); } // private void GetFrozenItems( Map map, IPoint2D start, IPoint2D end, ref ArrayList designItems) // { // start = map.Bound( new Point2D(start) ); // end = map.Bound( new Point2D(end) ); // // int xStartBlock = start.X >> 3; // int yStartBlock = start.Y >> 3; // int xEndBlock = end.X >> 3; // int yEndBlock = end.Y >> 3; // // int xTileStart = start.X, yTileStart = start.Y; // int xTileWidth = end.X - start.X + 1, yTileHeight = end.Y - start.Y + 1; // // TileMatrix matrix = map.Tiles; // // using ( FileStream idxStream = OpenFile(matrix.IndexStream) ) // { // using ( FileStream mulStream = OpenFile(matrix.DataStream) ) // { // if ( idxStream == null || mulStream == null ) // { // return; // } // // BinaryReader idxReader = new BinaryReader( idxStream ); // // //for ( int x = xStartBlock; x <= xEndBlock; ++x ) // for ( int x = xTileStart; x <= xTileWidth; ++x ) // { // //for ( int y = yStartBlock; y <= yEndBlock; ++y ) // for ( int y = yTileStart; y <= yTileHeight; ++y ) // { // int tileCount; // StaticTile[] staticTiles = ReadStaticBlock( idxReader, mulStream, x, y, matrix.BlockWidth, matrix.BlockHeight, out tileCount ); // // if ( tileCount < 0 ) // continue; // // for(int i = 0; i < tileCount; ++i) // { // StaticTile tile = staticTiles[i]; // DesignItem item = new DesignItem(); // // item.X = x; // item.Y = y; // item.Z = tile.m_Z; // item.Hue = _args.ExtractHues ? (short)tile.m_Hue : (short)0; // // designItems.Add(item); // } // } // } // } // } // } // private byte[] m_Buffer; // private StaticTile[] m_TileBuffer = new StaticTile[128]; // // private StaticTile[] ReadStaticBlock( BinaryReader idxReader, FileStream mulStream, int x, int y, int width, int height, out int count ) // { // try // { // if ( x < 0 || x >= width || y < 0 || y >= height ) // { // count = -1; // return m_TileBuffer; // } // // idxReader.BaseStream.Seek( ((x * height) + y) * 12, SeekOrigin.Begin ); // // int lookup = idxReader.ReadInt32(); // int length = idxReader.ReadInt32(); // // if ( lookup < 0 || length <= 0 ) // { // count = 0; // } // else // { // count = length / 7; // // mulStream.Seek( lookup, SeekOrigin.Begin ); // // if ( m_TileBuffer.Length < count ) // m_TileBuffer = new StaticTile[count]; // // StaticTile[] staTiles = m_TileBuffer; // // if ( m_Buffer == null || length > m_Buffer.Length ) // m_Buffer = new byte[length]; // // mulStream.Read( m_Buffer, 0, length ); // // int index = 0; // // for ( int i = 0; i < count; ++i ) // { // staTiles[i].m_ID = (short)(m_Buffer[index++] | (m_Buffer[index++] << 8)); // staTiles[i].m_X = m_Buffer[index++]; // staTiles[i].m_Y = m_Buffer[index++]; // staTiles[i].m_Z = (sbyte)m_Buffer[index++]; // staTiles[i].m_Hue = (short)(m_Buffer[index++] | (m_Buffer[index++] << 8)); // } // } // } // catch // { // count = -1; // } // // return m_TileBuffer; // } // // private FileStream OpenFile( FileStream orig ) // { // if ( orig == null ) // return null; // // try{ return new FileStream( orig.Name, FileMode.Open, FileAccess.Read, FileShare.Read ); } // catch{ return null; } // } } }
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf.Logging { using System; using System.Globalization; using Topshelf.Logging; public class Log4NetLogWriter : LogWriter { readonly log4net.ILog _log; public Log4NetLogWriter(log4net.ILog log) { _log = log; } public void Debug(object message) { _log.Debug(message); } public void Debug(object message, Exception exception) { _log.Debug(message, exception); } public void Debug(LogWriterOutputProvider messageProvider) { if (!IsDebugEnabled) return; _log.Debug(messageProvider()); } public void DebugFormat(string format, params object[] args) { _log.DebugFormat(format, args); } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { _log.DebugFormat(provider, format, args); } public void Info(object message) { _log.Info(message); } public void Info(object message, Exception exception) { _log.Info(message, exception); } public void Info(LogWriterOutputProvider messageProvider) { if (!IsInfoEnabled) return; _log.Info(messageProvider()); } public void InfoFormat(string format, params object[] args) { _log.InfoFormat(format, args); } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { _log.InfoFormat(provider, format, args); } public void Warn(object message) { _log.Warn(message); } public void Warn(object message, Exception exception) { _log.Warn(message, exception); } public void Warn(LogWriterOutputProvider messageProvider) { if (!IsWarnEnabled) return; _log.Warn(messageProvider()); } public void WarnFormat(string format, params object[] args) { _log.WarnFormat(format, args); } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { _log.WarnFormat(provider, format, args); } public void Error(object message) { _log.Error(message); } public void Error(object message, Exception exception) { _log.Error(message, exception); } public void Error(LogWriterOutputProvider messageProvider) { if (!IsErrorEnabled) return; _log.Error(messageProvider()); } public void ErrorFormat(string format, params object[] args) { _log.ErrorFormat(format, args); } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { _log.ErrorFormat(provider, format, args); } public void Fatal(object message) { _log.Fatal(message); } public void Fatal(object message, Exception exception) { _log.Fatal(message, exception); } public void Fatal(LogWriterOutputProvider messageProvider) { if (!IsFatalEnabled) return; _log.Fatal(messageProvider()); } public void FatalFormat(string format, params object[] args) { _log.FatalFormat(format, args); } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { _log.FatalFormat(provider, format, args); } public bool IsDebugEnabled { get { return _log.IsDebugEnabled; } } public bool IsInfoEnabled { get { return _log.IsInfoEnabled; } } public bool IsWarnEnabled { get { return _log.IsWarnEnabled; } } public bool IsErrorEnabled { get { return _log.IsErrorEnabled; } } public bool IsFatalEnabled { get { return _log.IsFatalEnabled; } } public void Log(LoggingLevel level, object obj) { if (level == LoggingLevel.Fatal) Fatal(obj); else if (level == LoggingLevel.Error) Error(obj); else if (level == LoggingLevel.Warn) Warn(obj); else if (level == LoggingLevel.Info) Info(obj); else if (level >= LoggingLevel.Debug) Debug(obj); } public void Log(LoggingLevel level, object obj, Exception exception) { if (level == LoggingLevel.Fatal) Fatal(obj, exception); else if (level == LoggingLevel.Error) Error(obj, exception); else if (level == LoggingLevel.Warn) Warn(obj, exception); else if (level == LoggingLevel.Info) Info(obj, exception); else if (level >= LoggingLevel.Debug) Debug(obj, exception); } public void Log(LoggingLevel level, LogWriterOutputProvider messageProvider) { if (level == LoggingLevel.Fatal) Fatal(messageProvider); else if (level == LoggingLevel.Error) Error(messageProvider); else if (level == LoggingLevel.Warn) Warn(messageProvider); else if (level == LoggingLevel.Info) Info(messageProvider); else if (level >= LoggingLevel.Debug) Debug(messageProvider); } public void LogFormat(LoggingLevel level, string format, params object[] args) { if (level == LoggingLevel.Fatal) FatalFormat(CultureInfo.InvariantCulture, format, args); else if (level == LoggingLevel.Error) ErrorFormat(CultureInfo.InvariantCulture, format, args); else if (level == LoggingLevel.Warn) WarnFormat(CultureInfo.InvariantCulture, format, args); else if (level == LoggingLevel.Info) InfoFormat(CultureInfo.InvariantCulture, format, args); else if (level >= LoggingLevel.Debug) DebugFormat(CultureInfo.InvariantCulture, format, args); } public void LogFormat(LoggingLevel level, IFormatProvider formatProvider, string format, params object[] args) { if (level == LoggingLevel.Fatal) FatalFormat(formatProvider, format, args); else if (level == LoggingLevel.Error) ErrorFormat(formatProvider, format, args); else if (level == LoggingLevel.Warn) WarnFormat(formatProvider, format, args); else if (level == LoggingLevel.Info) InfoFormat(formatProvider, format, args); else if (level >= LoggingLevel.Debug) DebugFormat(formatProvider, format, args); } } }
// // RedirectFS-FH.cs: Port of // http://fuse.cvs.sourceforge.net/fuse/fuse/example/fusexmp_fh.c?view=log // // Authors: // Jonathan Pryor (jonpryor@vt.edu) // // (C) 2006 Jonathan Pryor // // Mono.Fuse example program // // // 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.Diagnostics; using System.Runtime.InteropServices; using System.Text; using Mono.Fuse; using Mono.Unix.Native; namespace Mono.Fuse.Samples { class RedirectFHFS : FileSystem { private string basedir; public RedirectFHFS () { } protected override Errno OnGetPathStatus (string path, out Stat buf) { int r = Syscall.lstat (basedir+path, out buf); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnGetHandleStatus (string path, OpenedPathInfo info, out Stat buf) { int r = Syscall.fstat ((int) info.Handle, out buf); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnAccessPath (string path, AccessModes mask) { int r = Syscall.access (basedir+path, mask); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnReadSymbolicLink (string path, out string target) { target = null; StringBuilder buf = new StringBuilder (256); do { int r = Syscall.readlink (basedir+path, buf); if (r < 0) { return Stdlib.GetLastError (); } else if (r == buf.Capacity) { buf.Capacity *= 2; } else { target = buf.ToString (0, r); return 0; } } while (true); } protected override Errno OnOpenDirectory (string path, OpenedPathInfo info) { IntPtr dp = Syscall.opendir (basedir+path); if (dp == IntPtr.Zero) return Stdlib.GetLastError (); info.Handle = dp; return 0; } protected override Errno OnReadDirectory (string path, OpenedPathInfo fi, out IEnumerable<DirectoryEntry> paths) { IntPtr dp = (IntPtr) fi.Handle; paths = ReadDirectory (dp); return 0; } private IEnumerable<DirectoryEntry> ReadDirectory (IntPtr dp) { Dirent de; while ((de = Syscall.readdir (dp)) != null) { DirectoryEntry e = new DirectoryEntry (de.d_name); e.Stat.st_ino = de.d_ino; e.Stat.st_mode = (FilePermissions) (de.d_type << 12); yield return e; } } protected override Errno OnReleaseDirectory (string path, OpenedPathInfo info) { IntPtr dp = (IntPtr) info.Handle; Syscall.closedir (dp); return 0; } protected override Errno OnCreateSpecialFile (string path, FilePermissions mode, ulong rdev) { int r; // On Linux, this could just be `mknod(basedir+path, mode, rdev)' but // this is more portable. if ((mode & FilePermissions.S_IFMT) == FilePermissions.S_IFREG) { r = Syscall.open (basedir+path, OpenFlags.O_CREAT | OpenFlags.O_EXCL | OpenFlags.O_WRONLY, mode); if (r >= 0) r = Syscall.close (r); } else if ((mode & FilePermissions.S_IFMT) == FilePermissions.S_IFIFO) { r = Syscall.mkfifo (basedir+path, mode); } else { r = Syscall.mknod (basedir+path, mode, rdev); } if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnCreateDirectory (string path, FilePermissions mode) { int r = Syscall.mkdir (basedir+path, mode); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnRemoveFile (string path) { int r = Syscall.unlink (basedir+path); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnRemoveDirectory (string path) { int r = Syscall.rmdir (basedir+path); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnCreateSymbolicLink (string from, string to) { int r = Syscall.symlink (from, basedir+to); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnRenamePath (string from, string to) { int r = Syscall.rename (basedir+from, basedir+to); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnCreateHardLink (string from, string to) { int r = Syscall.link (basedir+from, basedir+to); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnChangePathPermissions (string path, FilePermissions mode) { int r = Syscall.chmod (basedir+path, mode); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnChangePathOwner (string path, long uid, long gid) { int r = Syscall.lchown (basedir+path, (uint) uid, (uint) gid); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnTruncateFile (string path, long size) { int r = Syscall.truncate (basedir+path, size); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnTruncateHandle (string path, OpenedPathInfo info, long size) { int r = Syscall.ftruncate ((int) info.Handle, size); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnChangePathTimes (string path, ref Utimbuf buf) { int r = Syscall.utime (basedir+path, ref buf); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnCreateHandle (string path, OpenedPathInfo info, FilePermissions mode) { int fd = Syscall.open (basedir+path, info.OpenFlags, mode); if (fd == -1) return Stdlib.GetLastError (); info.Handle = (IntPtr) fd; return 0; } protected override Errno OnOpenHandle (string path, OpenedPathInfo info) { int fd = Syscall.open (basedir+path, info.OpenFlags); if (fd == -1) return Stdlib.GetLastError (); info.Handle = (IntPtr) fd; return 0; } protected override unsafe Errno OnReadHandle (string path, OpenedPathInfo info, byte[] buf, long offset, out int bytesRead) { int r; fixed (byte *pb = buf) { r = bytesRead = (int) Syscall.pread ((int) info.Handle, pb, (ulong) buf.Length, offset); } if (r == -1) return Stdlib.GetLastError (); return 0; } protected override unsafe Errno OnWriteHandle (string path, OpenedPathInfo info, byte[] buf, long offset, out int bytesWritten) { int r; fixed (byte *pb = buf) { r = bytesWritten = (int) Syscall.pwrite ((int) info.Handle, pb, (ulong) buf.Length, offset); } if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnGetFileSystemStatus (string path, out Statvfs stbuf) { int r = Syscall.statvfs (basedir+path, out stbuf); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnFlushHandle (string path, OpenedPathInfo info) { /* This is called from every close on an open file, so call the close on the underlying filesystem. But since flush may be called multiple times for an open file, this must not really close the file. This is important if used on a network filesystem like NFS which flush the data/metadata on close() */ int r = Syscall.close (Syscall.dup ((int) info.Handle)); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnReleaseHandle (string path, OpenedPathInfo info) { int r = Syscall.close ((int) info.Handle); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnSynchronizeHandle (string path, OpenedPathInfo info, bool onlyUserData) { int r; if (onlyUserData) r = Syscall.fdatasync ((int) info.Handle); else r = Syscall.fsync ((int) info.Handle); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnSetPathExtendedAttribute (string path, string name, byte[] value, XattrFlags flags) { int r = Syscall.lsetxattr (basedir+path, name, value, (ulong) value.Length, flags); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnGetPathExtendedAttribute (string path, string name, byte[] value, out int bytesWritten) { int r = bytesWritten = (int) Syscall.lgetxattr (basedir+path, name, value, (ulong) value.Length); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnListPathExtendedAttributes (string path, out string[] names) { int r = (int) Syscall.llistxattr (basedir+path, out names); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnRemovePathExtendedAttribute (string path, string name) { int r = Syscall.lremovexattr (basedir+path, name); if (r == -1) return Stdlib.GetLastError (); return 0; } protected override Errno OnLockHandle (string file, OpenedPathInfo info, FcntlCommand cmd, ref Flock @lock) { int r = Syscall.fcntl ((int) info.Handle, cmd, ref @lock); if (r == -1) return Stdlib.GetLastError (); return 0; } private bool ParseArguments (string[] args) { for (int i = 0; i < args.Length; ++i) { switch (args [i]) { case "-h": case "--help": ShowHelp (); return false; default: if (base.MountPoint == null) base.MountPoint = args [i]; else basedir = args [i]; break; } } if (base.MountPoint == null) { return Error ("missing mountpoint"); } if (basedir == null) { return Error ("missing basedir"); } return true; } private static void ShowHelp () { Console.Error.WriteLine ("usage: redirectfs [options] mountpoint:"); FileSystem.ShowFuseHelp ("redirectfs-fh"); Console.Error.WriteLine (); Console.Error.WriteLine ("redirectfs-fh options"); Console.Error.WriteLine (" basedir Directory to mirror"); } private static bool Error (string message) { Console.Error.WriteLine ("redirectfs-fh: error: {0}", message); return false; } public static void Main (string[] args) { using (RedirectFHFS fs = new RedirectFHFS ()) { string[] unhandled = fs.ParseFuseArguments (args); if (!fs.ParseArguments (unhandled)) return; fs.Start (); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { /// <content> /// Contains the inner <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableDictionary<TKey, TValue> { /// <summary> /// A dictionary that mutates with little or no memory allocations, /// can produce and/or build on immutable dictionary instances very efficiently. /// </summary> /// <remarks> /// <para> /// While <see cref="ImmutableDictionary{TKey, TValue}.AddRange(IEnumerable{KeyValuePair{TKey, TValue}})"/> /// and other bulk change methods already provide fast bulk change operations on the collection, this class allows /// multiple combinations of changes to be made to a set with equal efficiency. /// </para> /// <para> /// Instance members of this class are <em>not</em> thread-safe. /// </para> /// </remarks> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableDictionaryBuilderDebuggerProxy<,>))] public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary { /// <summary> /// The root of the binary tree that stores the collection. Contents are typically not entirely frozen. /// </summary> private SortedInt32KeyNode<HashBucket> _root = SortedInt32KeyNode<HashBucket>.EmptyNode; /// <summary> /// The comparers. /// </summary> private Comparers _comparers; /// <summary> /// The number of elements in this collection. /// </summary> private int _count; /// <summary> /// Caches an immutable instance that represents the current state of the collection. /// </summary> /// <value>Null if no immutable view has been created for the current version.</value> private ImmutableDictionary<TKey, TValue> _immutable; /// <summary> /// A number that increments every time the builder changes its contents. /// </summary> private int _version; /// <summary> /// The object callers may use to synchronize access to this collection. /// </summary> private object _syncRoot; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class. /// </summary> /// <param name="map">The map that serves as the basis for this Builder.</param> internal Builder(ImmutableDictionary<TKey, TValue> map) { Requires.NotNull(map, nameof(map)); _root = map._root; _count = map._count; _comparers = map._comparers; _immutable = map; } /// <summary> /// Gets or sets the key comparer. /// </summary> /// <value> /// The key comparer. /// </value> public IEqualityComparer<TKey> KeyComparer { get { return _comparers.KeyComparer; } set { Requires.NotNull(value, nameof(value)); if (value != this.KeyComparer) { var comparers = Comparers.Get(value, this.ValueComparer); var input = new MutationInput(SortedInt32KeyNode<HashBucket>.EmptyNode, comparers); var result = ImmutableDictionary<TKey, TValue>.AddRange(this, input); _immutable = null; _comparers = comparers; _count = result.CountAdjustment; // offset from 0 this.Root = result.Root; } } } /// <summary> /// Gets or sets the value comparer. /// </summary> /// <value> /// The value comparer. /// </value> public IEqualityComparer<TValue> ValueComparer { get { return _comparers.ValueComparer; } set { Requires.NotNull(value, nameof(value)); if (value != this.ValueComparer) { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. _comparers = _comparers.WithValueComparer(value); _immutable = null; // invalidate cached immutable } } } #region IDictionary<TKey, TValue> Properties /// <summary> /// Gets the number of elements contained in the <see cref="ICollection{T}"/>. /// </summary> /// <returns>The number of elements contained in the <see cref="ICollection{T}"/>.</returns> public int Count { get { return _count; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.</returns> bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TKey> Keys { get { foreach (KeyValuePair<TKey, TValue> item in this) { yield return item.Key; } } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns>An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns> ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return this.Keys.ToArray(this.Count); } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TValue> Values { get { foreach (KeyValuePair<TKey, TValue> item in this) { yield return item.Value; } } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns>An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns> ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return this.Values.ToArray(this.Count); } } #endregion #region IDictionary Properties /// <summary> /// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size. /// </summary> /// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns> bool IDictionary.IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool IDictionary.IsReadOnly { get { return false; } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Keys { get { return this.Keys.ToArray(this.Count); } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Values { get { return this.Values.ToArray(this.Count); } } #endregion #region ICollection Properties /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new object(), null); } return _syncRoot; } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return false; } } #endregion #region IDictionary Methods /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param> /// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param> void IDictionary.Add(object key, object value) { this.Add((TKey)key, (TValue)value); } /// <summary> /// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param> /// <returns> /// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false. /// </returns> bool IDictionary.Contains(object key) { return this.ContainsKey((TKey)key); } /// <summary> /// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </summary> /// <returns> /// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </returns> IDictionaryEnumerator IDictionary.GetEnumerator() { return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator()); } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The key of the element to remove.</param> void IDictionary.Remove(object key) { this.Remove((TKey)key); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> object IDictionary.this[object key] { get { return this[(TKey)key]; } set { this[(TKey)key] = (TValue)value; } } #endregion #region ICollection methods /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex)); foreach (var item in this) { array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++); } } #endregion /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return _version; } } /// <summary> /// Gets the initial data to pass to a query or mutation method. /// </summary> private MutationInput Origin { get { return new MutationInput(this.Root, _comparers); } } /// <summary> /// Gets or sets the root of this data structure. /// </summary> private SortedInt32KeyNode<HashBucket> Root { get { return _root; } set { // We *always* increment the version number because some mutations // may not create a new value of root, although the existing root // instance may have mutated. _version++; if (_root != value) { _root = value; // Clear any cached value for the immutable view since it is now invalidated. _immutable = null; } } } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <returns>The element with the specified key.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// <exception cref="KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception> /// <exception cref="NotSupportedException">The property is set and the <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public TValue this[TKey key] { get { TValue value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); } set { var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.SetValue, this.Origin); this.Apply(result); } } #region Public Methods /// <summary> /// Adds a sequence of values to this collection. /// </summary> /// <param name="items">The items.</param> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items) { var result = ImmutableDictionary<TKey, TValue>.AddRange(items, this.Origin); this.Apply(result); } /// <summary> /// Removes any entries from the dictionaries with keys that match those found in the specified sequence. /// </summary> /// <param name="keys">The keys for entries to remove from the dictionary.</param> public void RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, nameof(keys)); foreach (var key in keys) { this.Remove(key); } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(_root, this); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <returns>The value for the key, or the default value of type <typeparamref name="TValue"/> if no matching key was found.</returns> [Pure] public TValue GetValueOrDefault(TKey key) { return this.GetValueOrDefault(key, default(TValue)); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param> /// <returns> /// The value for the key, or <paramref name="defaultValue"/> if no matching key was found. /// </returns> [Pure] public TValue GetValueOrDefault(TKey key, TValue defaultValue) { Requires.NotNullAllowStructs(key, nameof(key)); TValue value; if (this.TryGetValue(key, out value)) { return value; } return defaultValue; } /// <summary> /// Creates an immutable dictionary based on the contents of this instance. /// </summary> /// <returns>An immutable map.</returns> /// <remarks> /// This method is an O(n) operation, and approaches O(1) time as the number of /// actual mutations to the set since the last call to this method approaches 0. /// </remarks> public ImmutableDictionary<TKey, TValue> ToImmutable() { // Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. if (_immutable == null) { _immutable = ImmutableDictionary<TKey, TValue>.Wrap(_root, _comparers, _count); } return _immutable; } #endregion #region IDictionary<TKey, TValue> Members /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The object to use as the key of the element to add.</param> /// <param name="value">The object to use as the value of the element to add.</param> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>.</exception> /// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public void Add(TKey key, TValue value) { var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, this.Origin); this.Apply(result); } /// <summary> /// Determines whether the <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary{TKey, TValue}"/>.</param> /// <returns> /// true if the <see cref="IDictionary{TKey, TValue}"/> contains an element with the key; otherwise, false. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> public bool ContainsKey(TKey key) { return ImmutableDictionary<TKey, TValue>.ContainsKey(key, this.Origin); } /// <summary> /// Determines whether the <see cref="ImmutableDictionary{TKey, TValue}"/> /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the <see cref="ImmutableDictionary{TKey, TValue}"/>. /// The value can be null for reference types. /// </param> /// <returns> /// true if the <see cref="ImmutableDictionary{TKey, TValue}"/> contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) { foreach (KeyValuePair<TKey, TValue> item in this) { if (this.ValueComparer.Equals(value, item.Value)) { return true; } } return false; } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// /// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public bool Remove(TKey key) { var result = ImmutableDictionary<TKey, TValue>.Remove(key, this.Origin); return this.Apply(result); } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key whose value to get.</param> /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value of the type <typeparamref name="TValue"/>. This parameter is passed uninitialized.</param> /// <returns> /// true if the object that implements <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key; otherwise, false. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> public bool TryGetValue(TKey key, out TValue value) { return ImmutableDictionary<TKey, TValue>.TryGetValue(key, this.Origin, out value); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { return ImmutableDictionary<TKey, TValue>.TryGetKey(equalKey, this.Origin, out actualKey); } /// <summary> /// Adds an item to the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception> public void Add(KeyValuePair<TKey, TValue> item) { this.Add(item.Key, item.Value); } /// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. /// </summary> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only. </exception> public void Clear() { this.Root = SortedInt32KeyNode<HashBucket>.EmptyNode; _count = 0; } /// <summary> /// Determines whether the <see cref="ICollection{T}"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false. /// </returns> public bool Contains(KeyValuePair<TKey, TValue> item) { return ImmutableDictionary<TKey, TValue>.Contains(item, this.Origin); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { Requires.NotNull(array, nameof(array)); foreach (var item in this) { array[arrayIndex++] = item; } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members /// <summary> /// Removes the first occurrence of a specific object from the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="ICollection{T}"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="ICollection{T}"/>. /// </returns> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception> public bool Remove(KeyValuePair<TKey, TValue> item) { // Before removing based on the key, check that the key (if it exists) has the value given in the parameter as well. if (this.Contains(item)) { return this.Remove(item.Key); } return false; } #endregion #region IEnumerator<T> methods /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Applies the result of some mutation operation to this instance. /// </summary> /// <param name="result">The result.</param> private bool Apply(MutationResult result) { this.Root = result.Root; _count += result.CountAdjustment; return result.CountAdjustment != 0; } } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal class ImmutableDictionaryBuilderDebuggerProxy<TKey, TValue> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableDictionary<TKey, TValue>.Builder _map; /// <summary> /// The simple view of the collection. /// </summary> private KeyValuePair<TKey, TValue>[] _contents; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class. /// </summary> /// <param name="map">The collection to display in the debugger</param> public ImmutableDictionaryBuilderDebuggerProxy(ImmutableDictionary<TKey, TValue>.Builder map) { Requires.NotNull(map, nameof(map)); _map = map; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair<TKey, TValue>[] Contents { get { if (_contents == null) { _contents = _map.ToArray(_map.Count); } return _contents; } } } }
/* * Language Binding for BaseX. * Works with BaseX 7.0 and later * * Documentation: http://docs.basex.org/wiki/Clients * * (C) BaseX Team 2005-12, BSD License */ using System; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.IO; using System.Threading; using System.Collections; using System.Collections.Generic; namespace BaseXClient { class Session { private byte[] cache = new byte[4096]; public NetworkStream stream; private TcpClient socket; private string info = ""; private string ehost; private int bpos; private int bsize; private TcpClient esocket; private NetworkStream estream; private Dictionary<string, EventNotification> en; public Session(string host, int port, string username, string pw) { socket = new TcpClient(host, port); stream = socket.GetStream(); ehost = host; string[] response = Receive().Split(':'); string nonce; string code; if (response.Length > 1) { code = username + ":" + response[0] + ":" + pw; nonce = response[1]; } else { code = pw; nonce = response[0]; } Send(username); Send(MD5(MD5(code) + nonce)); if (stream.ReadByte() != 0) { throw new IOException("Access denied."); } } public void Execute(string com, Stream ms) { Send(com); Init(); Receive(ms); info = Receive(); if(!Ok()) { throw new IOException(info); } } public String Execute(string com) { MemoryStream ms = new MemoryStream(); Execute(com, ms); return System.Text.Encoding.UTF8.GetString(ms.ToArray()); } public Query Query(string q) { return new Query(this, q); } public void Create(string name, Stream s) { stream.WriteByte(8); Send(name); Send(s); } public void Add(string path, Stream s) { stream.WriteByte(9); Send(path); Send(s); } public void Replace(string path, Stream s) { stream.WriteByte(12); Send(path); Send(s); } public void Store(string path, Stream s) { stream.WriteByte(13); Send(path); Send(s); } /* Watches an event. */ public void Watch(string name, EventNotification notify) { stream.WriteByte(10); if(esocket == null) { int eport = Convert.ToInt32(Receive()); en = new Dictionary<string, EventNotification>(); esocket = new TcpClient(ehost, eport); estream = esocket.GetStream(); string id = Receive(); byte[] msg = System.Text.Encoding.UTF8.GetBytes(id); estream.Write(msg, 0, msg.Length); estream.WriteByte(0); estream.ReadByte(); new Thread(Listen).Start(); } Send(name); info = Receive(); if(!Ok()) { throw new IOException(info); } en.Add(name, notify); } private void Listen() { while (true) { String name = readS(); String val = readS(); en[name].Update(val); } } private string readS() { MemoryStream ms = new MemoryStream(); while (true) { int b = estream.ReadByte(); if (b == 0) break; ms.WriteByte((byte) b); } return System.Text.Encoding.UTF8.GetString(ms.ToArray()); } /* Unwatches an event. */ public void Unwatch(string name) { stream.WriteByte(11); Send(name); info = Receive(); if(!Ok()) { throw new IOException(info); } en.Remove(name); } public string Info { get { return info; } } public void Close() { Send("exit"); if (esocket != null) { esocket.Close(); } socket.Close(); } private void Init() { bpos = 0; bsize = 0; } public byte Read() { if (bpos == bsize) { bsize = stream.Read(cache, 0, 4096); bpos = 0; } return cache[bpos++]; } private void Receive(Stream ms) { while (true) { byte b = Read(); if (b == 0) break; // read next byte if 0xFF is received ms.WriteByte(b == 0xFF ? Read() : b); } } public string Receive() { MemoryStream ms = new MemoryStream(); Receive(ms); return System.Text.Encoding.UTF8.GetString(ms.ToArray()); } public void Send(string message) { byte[] msg = System.Text.Encoding.UTF8.GetBytes(message); stream.Write(msg, 0, msg.Length); stream.WriteByte(0); } private void Send(Stream s) { while (true) { int t = s.ReadByte(); if (t == -1) break; if (t == 0x00 || t == 0xFF) stream.WriteByte(Convert.ToByte(0xFF)); stream.WriteByte(Convert.ToByte(t)); } stream.WriteByte(0); info = Receive(); if(!Ok()) { throw new IOException(info); } } public bool Ok() { return Read() == 0; } private string MD5(string input) { MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider(); byte[] hash = MD5.ComputeHash(Encoding.UTF8.GetBytes(input)); StringBuilder sb = new StringBuilder(); foreach (byte h in hash) { sb.Append(h.ToString("x2")); } return sb.ToString(); } } class Query { private Session session; private string id; private ArrayList cache; private int pos; public Query(Session s, string query) { session = s; id = Exec(0, query); } public void Bind(string name, string value) { Bind(name, value, ""); } public void Bind(string name, string value, string type) { cache = null; Exec(3, id + '\0' + name + '\0' + value + '\0' + type); } public void Context(string value) { Context(value, ""); } public void Context(string value, string type) { cache = null; Exec(14, id + '\0' + value + '\0' + type); } public bool More() { if(cache == null) { session.stream.WriteByte(4); session.Send(id); cache = new ArrayList(); while (session.Read() > 0) { cache.Add(session.Receive()); } if(!session.Ok()) { throw new IOException(session.Receive()); } pos = 0; } if(pos < cache.Count) return true; cache = null; return false; } public string Next() { if(More()) { return cache[pos++] as string; } else { return null; } } public string Execute() { return Exec(5, id); } public string Info() { return Exec(6, id); } public string Options() { return Exec(7, id); } public void Close() { Exec(2, id); } private string Exec(byte cmd, string arg) { session.stream.WriteByte(cmd); session.Send(arg); string s = session.Receive(); bool ok = session.Ok(); if(!ok) { throw new IOException(session.Receive()); } return s; } } interface EventNotification { void Update(string data); } }
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; namespace NUnit.Constraints.Constraints { /// <summary> /// The Numerics class contains common operations on numeric values. /// </summary> public class Numerics { #region Numeric Type Recognition /// <summary> /// Checks the type of the object, returning true if /// the object is a numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a numeric type</returns> public static bool IsNumericType(Object obj) { return IsFloatingPointNumeric( obj ) || IsFixedPointNumeric( obj ); } /// <summary> /// Checks the type of the object, returning true if /// the object is a floating point numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a floating point numeric type</returns> public static bool IsFloatingPointNumeric(Object obj) { if (null != obj) { if (obj is System.Double) return true; if (obj is System.Single) return true; } return false; } /// <summary> /// Checks the type of the object, returning true if /// the object is a fixed point numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a fixed point numeric type</returns> public static bool IsFixedPointNumeric(Object obj) { if (null != obj) { if (obj is System.Byte) return true; if (obj is System.SByte) return true; if (obj is System.Decimal) return true; if (obj is System.Int32) return true; if (obj is System.UInt32) return true; if (obj is System.Int64) return true; if (obj is System.UInt64) return true; if (obj is System.Int16) return true; if (obj is System.UInt16) return true; } return false; } #endregion #region Numeric Equality /// <summary> /// Test two numeric values for equality, performing the usual numeric /// conversions and using a provided or default tolerance. If the tolerance /// provided is Empty, this method may set it to a default tolerance. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <param name="tolerance">A reference to the tolerance in effect</param> /// <returns>True if the values are equal</returns> public static bool AreEqual( object expected, object actual, ref Tolerance tolerance ) { if ( expected is double || actual is double ) return AreEqual( Convert.ToDouble(expected), Convert.ToDouble(actual), ref tolerance ); if ( expected is float || actual is float ) return AreEqual( Convert.ToSingle(expected), Convert.ToSingle(actual), ref tolerance ); if (tolerance.Mode == ToleranceMode.Ulps) throw new InvalidOperationException("Ulps may only be specified for floating point arguments"); if ( expected is decimal || actual is decimal ) return AreEqual( Convert.ToDecimal(expected), Convert.ToDecimal(actual), tolerance ); if (expected is ulong || actual is ulong) return AreEqual(Convert.ToUInt64(expected), Convert.ToUInt64(actual), tolerance ); if ( expected is long || actual is long ) return AreEqual( Convert.ToInt64(expected), Convert.ToInt64(actual), tolerance ); if ( expected is uint || actual is uint ) return AreEqual( Convert.ToUInt32(expected), Convert.ToUInt32(actual), tolerance ); return AreEqual( Convert.ToInt32(expected), Convert.ToInt32(actual), tolerance ); } private static bool AreEqual( double expected, double actual, ref Tolerance tolerance ) { if (double.IsNaN(expected) && double.IsNaN(actual)) return true; // Handle infinity specially since subtracting two infinite values gives // NaN and the following test fails. mono also needs NaN to be handled // specially although ms.net could use either method. Also, handle // situation where no tolerance is used. if (double.IsInfinity(expected) || double.IsNaN(expected) || double.IsNaN(actual)) { return expected.Equals(actual); } if (tolerance.IsEmpty && GlobalSettings.DefaultFloatingPointTolerance > 0.0d) tolerance = new Tolerance(GlobalSettings.DefaultFloatingPointTolerance); switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value); case ToleranceMode.Percent: if (expected == 0.0) return expected.Equals(actual); double relativeError = Math.Abs((expected - actual) / expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); #if !NETCF_1_0 case ToleranceMode.Ulps: return FloatingPointNumerics.AreAlmostEqualUlps( expected, actual, Convert.ToInt64(tolerance.Value)); #endif default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( float expected, float actual, ref Tolerance tolerance ) { if ( float.IsNaN(expected) && float.IsNaN(actual) ) return true; // handle infinity specially since subtracting two infinite values gives // NaN and the following test fails. mono also needs NaN to be handled // specially although ms.net could use either method. if (float.IsInfinity(expected) || float.IsNaN(expected) || float.IsNaN(actual)) { return expected.Equals(actual); } if (tolerance.IsEmpty && GlobalSettings.DefaultFloatingPointTolerance > 0.0d) tolerance = new Tolerance(GlobalSettings.DefaultFloatingPointTolerance); switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value); case ToleranceMode.Percent: if (expected == 0.0f) return expected.Equals(actual); float relativeError = Math.Abs((expected - actual) / expected); return (relativeError <= Convert.ToSingle(tolerance.Value) / 100.0f); #if !NETCF_1_0 case ToleranceMode.Ulps: return FloatingPointNumerics.AreAlmostEqualUlps( expected, actual, Convert.ToInt32(tolerance.Value)); #endif default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( decimal expected, decimal actual, Tolerance tolerance ) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: decimal decimalTolerance = Convert.ToDecimal(tolerance.Value); if(decimalTolerance > 0m) return Math.Abs(expected - actual) <= decimalTolerance; return expected.Equals( actual ); case ToleranceMode.Percent: if(expected == 0m) return expected.Equals(actual); double relativeError = Math.Abs( (double)(expected - actual) / (double)expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( ulong expected, ulong actual, Tolerance tolerance ) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: ulong ulongTolerance = Convert.ToUInt64(tolerance.Value); if(ulongTolerance > 0ul) { ulong diff = expected >= actual ? expected - actual : actual - expected; return diff <= ulongTolerance; } return expected.Equals( actual ); case ToleranceMode.Percent: if (expected == 0ul) return expected.Equals(actual); // Can't do a simple Math.Abs() here since it's unsigned ulong difference = Math.Max(expected, actual) - Math.Min(expected, actual); double relativeError = Math.Abs( (double)difference / (double)expected ); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( long expected, long actual, Tolerance tolerance ) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: long longTolerance = Convert.ToInt64(tolerance.Value); if(longTolerance > 0L) return Math.Abs(expected - actual) <= longTolerance; return expected.Equals( actual ); case ToleranceMode.Percent: if(expected == 0L) return expected.Equals(actual); double relativeError = Math.Abs( (double)(expected - actual) / (double)expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( uint expected, uint actual, Tolerance tolerance ) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: uint uintTolerance = Convert.ToUInt32(tolerance.Value); if(uintTolerance > 0) { uint diff = expected >= actual ? expected - actual : actual - expected; return diff <= uintTolerance; } return expected.Equals( actual ); case ToleranceMode.Percent: if(expected == 0u) return expected.Equals(actual); // Can't do a simple Math.Abs() here since it's unsigned uint difference = Math.Max(expected, actual) - Math.Min(expected, actual); double relativeError = Math.Abs((double)difference / (double)expected ); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual( int expected, int actual, Tolerance tolerance ) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: int intTolerance = Convert.ToInt32(tolerance.Value); if (intTolerance > 0) return Math.Abs(expected - actual) <= intTolerance; return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0) return expected.Equals(actual); double relativeError = Math.Abs( (double)(expected - actual) / (double)expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } #endregion #region Numeric Comparisons /// <summary> /// Compare two numeric values, performing the usual numeric conversions. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <returns>The relationship of the values to each other</returns> public static int Compare( object expected, object actual ) { if( !IsNumericType( expected ) || !IsNumericType( actual ) ) throw new ArgumentException( "Both arguments must be numeric"); if ( IsFloatingPointNumeric(expected) || IsFloatingPointNumeric(actual) ) return Convert.ToDouble(expected).CompareTo(Convert.ToDouble(actual)); if ( expected is decimal || actual is decimal ) return Convert.ToDecimal(expected).CompareTo(Convert.ToDecimal(actual)); if ( expected is ulong || actual is ulong ) return Convert.ToUInt64(expected).CompareTo(Convert.ToUInt64(actual)); if ( expected is long || actual is long ) return Convert.ToInt64(expected).CompareTo(Convert.ToInt64(actual)); if ( expected is uint || actual is uint ) return Convert.ToUInt32(expected).CompareTo(Convert.ToUInt32(actual)); return Convert.ToInt32(expected).CompareTo(Convert.ToInt32(actual)); } #endregion private Numerics() { } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- if ( isObject( moveMap ) ) moveMap.delete(); new ActionMap(moveMap); //------------------------------------------------------------------------------ // Non-remapable binds //------------------------------------------------------------------------------ function escapeFromGame() { if ( $Server::ServerType $= "SinglePlayer" ) MessageBoxYesNo( "Exit", "Exit from this Mission?", "disconnect();", ""); else MessageBoxYesNo( "Disconnect", "Disconnect from the server?", "disconnect();", ""); } moveMap.bindCmd(keyboard, "escape", "", "handleEscape();"); //------------------------------------------------------------------------------ // Movement Keys //------------------------------------------------------------------------------ $movementSpeed = 1; // m/s function setSpeed(%speed) { if(%speed) $movementSpeed = %speed; } function moveleft(%val) { $mvLeftAction = %val * $movementSpeed; } function moveright(%val) { $mvRightAction = %val * $movementSpeed; } function moveforward(%val) { $mvForwardAction = %val * $movementSpeed; } function movebackward(%val) { $mvBackwardAction = %val * $movementSpeed; } function moveup(%val) { %object = ServerConnection.getControlObject(); if(%object.isInNamespaceHierarchy("Camera")) $mvUpAction = %val * $movementSpeed; } function movedown(%val) { %object = ServerConnection.getControlObject(); if(%object.isInNamespaceHierarchy("Camera")) $mvDownAction = %val * $movementSpeed; } function turnLeft( %val ) { $mvYawRightSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0; } function turnRight( %val ) { $mvYawLeftSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0; } function panUp( %val ) { $mvPitchDownSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0; } function panDown( %val ) { $mvPitchUpSpeed = %val ? $Pref::Input::KeyboardTurnSpeed : 0; } function getMouseAdjustAmount(%val) { // based on a default camera FOV of 90' return(%val * ($cameraFov / 90) * 0.01) * $pref::Input::LinkMouseSensitivity; } function getGamepadAdjustAmount(%val) { // based on a default camera FOV of 90' return(%val * ($cameraFov / 90) * 0.01) * 10.0; } function yaw(%val) { %yawAdj = getMouseAdjustAmount(%val); if(ServerConnection.isControlObjectRotDampedCamera()) { // Clamp and scale %yawAdj = mClamp(%yawAdj, -m2Pi()+0.01, m2Pi()-0.01); %yawAdj *= 0.5; } $mvYaw += %yawAdj; } function pitch(%val) { %pitchAdj = getMouseAdjustAmount(%val); if(ServerConnection.isControlObjectRotDampedCamera()) { // Clamp and scale %pitchAdj = mClamp(%pitchAdj, -m2Pi()+0.01, m2Pi()-0.01); %pitchAdj *= 0.5; } $mvPitch += %pitchAdj; } function jump(%val) { $mvTriggerCount2++; } function gamePadMoveX( %val ) { $mvXAxis_L = %val; } function gamePadMoveY( %val ) { $mvYAxis_L = %val; } function gamepadYaw(%val) { %yawAdj = getGamepadAdjustAmount(%val); if(ServerConnection.isControlObjectRotDampedCamera()) { // Clamp and scale %yawAdj = mClamp(%yawAdj, -m2Pi()+0.01, m2Pi()-0.01); %yawAdj *= 0.5; } if(%yawAdj > 0) { $mvYawLeftSpeed = %yawAdj; $mvYawRightSpeed = 0; } else { $mvYawLeftSpeed = 0; $mvYawRightSpeed = -%yawAdj; } } function gamepadPitch(%val) { %pitchAdj = getGamepadAdjustAmount(%val); if(ServerConnection.isControlObjectRotDampedCamera()) { // Clamp and scale %pitchAdj = mClamp(%pitchAdj, -m2Pi()+0.01, m2Pi()-0.01); %pitchAdj *= 0.5; } if(%pitchAdj > 0) { $mvPitchDownSpeed = %pitchAdj; $mvPitchUpSpeed = 0; } else { $mvPitchDownSpeed = 0; $mvPitchUpSpeed = -%pitchAdj; } } moveMap.bind( keyboard, a, moveleft ); moveMap.bind( keyboard, d, moveright ); moveMap.bind( keyboard, left, moveleft ); moveMap.bind( keyboard, right, moveright ); moveMap.bind( keyboard, w, moveforward ); moveMap.bind( keyboard, s, movebackward ); moveMap.bind( keyboard, up, moveforward ); moveMap.bind( keyboard, down, movebackward ); moveMap.bind( keyboard, e, moveup ); moveMap.bind( keyboard, c, movedown ); moveMap.bind( keyboard, space, jump ); moveMap.bind( mouse, xaxis, yaw ); moveMap.bind( mouse, yaxis, pitch ); moveMap.bind( gamepad, thumbrx, "D", "-0.23 0.23", gamepadYaw ); moveMap.bind( gamepad, thumbry, "D", "-0.23 0.23", gamepadPitch ); moveMap.bind( gamepad, thumblx, "D", "-0.23 0.23", gamePadMoveX ); moveMap.bind( gamepad, thumbly, "D", "-0.23 0.23", gamePadMoveY ); moveMap.bind( gamepad, btn_a, jump ); moveMap.bindCmd( gamepad, btn_back, "disconnect();", "" ); moveMap.bindCmd(gamepad, dpadl, "toggleLightColorViz();", ""); moveMap.bindCmd(gamepad, dpadu, "toggleDepthViz();", ""); moveMap.bindCmd(gamepad, dpadd, "toggleNormalsViz();", ""); moveMap.bindCmd(gamepad, dpadr, "toggleLightSpecularViz();", ""); //------------------------------------------------------------------------------ // Mouse Trigger //------------------------------------------------------------------------------ function mouseFire(%val) { $mvTriggerCount0++; } function altTrigger(%val) { $mvTriggerCount1++; } moveMap.bind( mouse, button0, mouseFire ); moveMap.bind( mouse, button1, altTrigger ); //------------------------------------------------------------------------------ // Gamepad Trigger //------------------------------------------------------------------------------ function gamepadFire(%val) { if(%val > 0.1 && !$gamepadFireTriggered) { $gamepadFireTriggered = true; $mvTriggerCount0++; } else if(%val <= 0.1 && $gamepadFireTriggered) { $gamepadFireTriggered = false; $mvTriggerCount0++; } } function gamepadAltTrigger(%val) { if(%val > 0.1 && !$gamepadAltTriggerTriggered) { $gamepadAltTriggerTriggered = true; $mvTriggerCount1++; } else if(%val <= 0.1 && $gamepadAltTriggerTriggered) { $gamepadAltTriggerTriggered = false; $mvTriggerCount1++; } } moveMap.bind(gamepad, triggerr, gamepadFire); moveMap.bind(gamepad, triggerl, gamepadAltTrigger); //------------------------------------------------------------------------------ // Zoom and FOV functions //------------------------------------------------------------------------------ if($Player::CurrentFOV $= "") $Player::CurrentFOV = $pref::Player::DefaultFOV / 2; // toggleZoomFOV() works by dividing the CurrentFOV by 2. Each time that this // toggle is hit it simply divides the CurrentFOV by 2 once again. If the // FOV is reduced below a certain threshold then it resets to equal half of the // DefaultFOV value. This gives us 4 zoom levels to cycle through. function toggleZoomFOV() { $Player::CurrentFOV = $Player::CurrentFOV / 2; if($Player::CurrentFOV < 5) resetCurrentFOV(); if(ServerConnection.zoomed) setFOV($Player::CurrentFOV); else { setFov(ServerConnection.getControlCameraDefaultFov()); } } function resetCurrentFOV() { $Player::CurrentFOV = ServerConnection.getControlCameraDefaultFov() / 2; } function turnOffZoom() { ServerConnection.zoomed = false; setFov(ServerConnection.getControlCameraDefaultFov()); // Rather than just disable the DOF effect, we want to set it to the level's // preset values. //DOFPostEffect.disable(); ppOptionsUpdateDOFSettings(); } function setZoomFOV(%val) { if(%val) toggleZoomFOV(); } function toggleZoom(%val) { if (%val) { ServerConnection.zoomed = true; setFov($Player::CurrentFOV); DOFPostEffect.setAutoFocus( true ); DOFPostEffect.setFocusParams( 0.5, 0.5, 50, 500, -5, 5 ); DOFPostEffect.enable(); } else { turnOffZoom(); } } moveMap.bind(keyboard, f, setZoomFOV); moveMap.bind(keyboard, r, toggleZoom); moveMap.bind( gamepad, btn_b, toggleZoom ); //------------------------------------------------------------------------------ // Camera & View functions //------------------------------------------------------------------------------ function toggleFreeLook( %val ) { if ( %val ) $mvFreeLook = true; else $mvFreeLook = false; } function toggleFirstPerson(%val) { if (%val) { ServerConnection.setFirstPerson(!ServerConnection.isFirstPerson()); } } function toggleCamera(%val) { if (%val) commandToServer('ToggleCamera'); } moveMap.bind( keyboard, z, toggleFreeLook ); moveMap.bind(keyboard, tab, toggleFirstPerson ); moveMap.bind(keyboard, "alt c", toggleCamera); moveMap.bind( gamepad, btn_back, toggleCamera ); //------------------------------------------------------------------------------ // Demo recording functions //------------------------------------------------------------------------------ function startRecordingDemo( %val ) { if ( %val ) startDemoRecord(); } function stopRecordingDemo( %val ) { if ( %val ) stopDemoRecord(); } moveMap.bind( keyboard, F3, startRecordingDemo ); moveMap.bind( keyboard, F4, stopRecordingDemo ); //------------------------------------------------------------------------------ // Helper Functions //------------------------------------------------------------------------------ function dropCameraAtPlayer(%val) { if (%val) commandToServer('dropCameraAtPlayer'); } function dropPlayerAtCamera(%val) { if (%val) commandToServer('DropPlayerAtCamera'); } moveMap.bind(keyboard, "F8", dropCameraAtPlayer); moveMap.bind(keyboard, "F7", dropPlayerAtCamera); function bringUpOptions(%val) { if (%val) Canvas.pushDialog(OptionsDlg); } GlobalActionMap.bind(keyboard, "ctrl o", bringUpOptions); //------------------------------------------------------------------------------ // Debugging Functions //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // // Start profiler by pressing ctrl f3 // ctrl f3 - starts profile that will dump to console and file // function doProfile(%val) { if (%val) { // key down -- start profile echo("Starting profile session..."); profilerReset(); profilerEnable(true); } else { // key up -- finish off profile echo("Ending profile session..."); profilerDumpToFile("profilerDumpToFile" @ getSimTime() @ ".txt"); profilerEnable(false); } } GlobalActionMap.bind(keyboard, "ctrl F3", doProfile); //------------------------------------------------------------------------------ // Misc. //------------------------------------------------------------------------------ GlobalActionMap.bind(keyboard, "tilde", toggleConsole); GlobalActionMap.bindCmd(keyboard, "alt k", "cls();",""); GlobalActionMap.bindCmd(keyboard, "alt enter", "", "Canvas.attemptFullscreenToggle();");
namespace OpenQA.Selenium.DevTools.Emulation { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Represents an adapter for the Emulation domain to simplify the command interface. /// </summary> public class EmulationAdapter { private readonly DevToolsSession m_session; private readonly string m_domainName = "Emulation"; private Dictionary<string, DevToolsEventData> m_eventMap = new Dictionary<string, DevToolsEventData>(); public EmulationAdapter(DevToolsSession session) { m_session = session ?? throw new ArgumentNullException(nameof(session)); m_session.DevToolsEventReceived += OnDevToolsEventReceived; m_eventMap["virtualTimeBudgetExpired"] = new DevToolsEventData(typeof(VirtualTimeBudgetExpiredEventArgs), OnVirtualTimeBudgetExpired); } /// <summary> /// Gets the DevToolsSession associated with the adapter. /// </summary> public DevToolsSession Session { get { return m_session; } } /// <summary> /// Notification sent after the virtual time budget for the current VirtualTimePolicy has run out. /// </summary> public event EventHandler<VirtualTimeBudgetExpiredEventArgs> VirtualTimeBudgetExpired; /// <summary> /// Tells whether emulation is supported. /// </summary> public async Task<CanEmulateCommandResponse> CanEmulate(CanEmulateCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<CanEmulateCommandSettings, CanEmulateCommandResponse>(command ?? new CanEmulateCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Clears the overriden device metrics. /// </summary> public async Task<ClearDeviceMetricsOverrideCommandResponse> ClearDeviceMetricsOverride(ClearDeviceMetricsOverrideCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<ClearDeviceMetricsOverrideCommandSettings, ClearDeviceMetricsOverrideCommandResponse>(command ?? new ClearDeviceMetricsOverrideCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Clears the overriden Geolocation Position and Error. /// </summary> public async Task<ClearGeolocationOverrideCommandResponse> ClearGeolocationOverride(ClearGeolocationOverrideCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<ClearGeolocationOverrideCommandSettings, ClearGeolocationOverrideCommandResponse>(command ?? new ClearGeolocationOverrideCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Requests that page scale factor is reset to initial values. /// </summary> public async Task<ResetPageScaleFactorCommandResponse> ResetPageScaleFactor(ResetPageScaleFactorCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<ResetPageScaleFactorCommandSettings, ResetPageScaleFactorCommandResponse>(command ?? new ResetPageScaleFactorCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Enables or disables simulating a focused and active page. /// </summary> public async Task<SetFocusEmulationEnabledCommandResponse> SetFocusEmulationEnabled(SetFocusEmulationEnabledCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetFocusEmulationEnabledCommandSettings, SetFocusEmulationEnabledCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Enables CPU throttling to emulate slow CPUs. /// </summary> public async Task<SetCPUThrottlingRateCommandResponse> SetCPUThrottlingRate(SetCPUThrottlingRateCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetCPUThrottlingRateCommandSettings, SetCPUThrottlingRateCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Sets or clears an override of the default background color of the frame. This override is used /// if the content does not specify one. /// </summary> public async Task<SetDefaultBackgroundColorOverrideCommandResponse> SetDefaultBackgroundColorOverride(SetDefaultBackgroundColorOverrideCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetDefaultBackgroundColorOverrideCommandSettings, SetDefaultBackgroundColorOverrideCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Overrides the values of device screen dimensions (window.screen.width, window.screen.height, /// window.innerWidth, window.innerHeight, and "device-width"/"device-height"-related CSS media /// query results). /// </summary> public async Task<SetDeviceMetricsOverrideCommandResponse> SetDeviceMetricsOverride(SetDeviceMetricsOverrideCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetDeviceMetricsOverrideCommandSettings, SetDeviceMetricsOverrideCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// setScrollbarsHidden /// </summary> public async Task<SetScrollbarsHiddenCommandResponse> SetScrollbarsHidden(SetScrollbarsHiddenCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetScrollbarsHiddenCommandSettings, SetScrollbarsHiddenCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// setDocumentCookieDisabled /// </summary> public async Task<SetDocumentCookieDisabledCommandResponse> SetDocumentCookieDisabled(SetDocumentCookieDisabledCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetDocumentCookieDisabledCommandSettings, SetDocumentCookieDisabledCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// setEmitTouchEventsForMouse /// </summary> public async Task<SetEmitTouchEventsForMouseCommandResponse> SetEmitTouchEventsForMouse(SetEmitTouchEventsForMouseCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetEmitTouchEventsForMouseCommandSettings, SetEmitTouchEventsForMouseCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Emulates the given media for CSS media queries. /// </summary> public async Task<SetEmulatedMediaCommandResponse> SetEmulatedMedia(SetEmulatedMediaCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetEmulatedMediaCommandSettings, SetEmulatedMediaCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Overrides the Geolocation Position or Error. Omitting any of the parameters emulates position /// unavailable. /// </summary> public async Task<SetGeolocationOverrideCommandResponse> SetGeolocationOverride(SetGeolocationOverrideCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetGeolocationOverrideCommandSettings, SetGeolocationOverrideCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Overrides value returned by the javascript navigator object. /// </summary> public async Task<SetNavigatorOverridesCommandResponse> SetNavigatorOverrides(SetNavigatorOverridesCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetNavigatorOverridesCommandSettings, SetNavigatorOverridesCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Sets a specified page scale factor. /// </summary> public async Task<SetPageScaleFactorCommandResponse> SetPageScaleFactor(SetPageScaleFactorCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetPageScaleFactorCommandSettings, SetPageScaleFactorCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Switches script execution in the page. /// </summary> public async Task<SetScriptExecutionDisabledCommandResponse> SetScriptExecutionDisabled(SetScriptExecutionDisabledCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetScriptExecutionDisabledCommandSettings, SetScriptExecutionDisabledCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Enables touch on platforms which do not support them. /// </summary> public async Task<SetTouchEmulationEnabledCommandResponse> SetTouchEmulationEnabled(SetTouchEmulationEnabledCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetTouchEmulationEnabledCommandSettings, SetTouchEmulationEnabledCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Turns on virtual time for all frames (replacing real-time with a synthetic time source) and sets /// the current virtual time policy. Note this supersedes any previous time budget. /// </summary> public async Task<SetVirtualTimePolicyCommandResponse> SetVirtualTimePolicy(SetVirtualTimePolicyCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetVirtualTimePolicyCommandSettings, SetVirtualTimePolicyCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Resizes the frame/viewport of the page. Note that this does not affect the frame's container /// (e.g. browser window). Can be used to produce screenshots of the specified size. Not supported /// on Android. /// </summary> public async Task<SetVisibleSizeCommandResponse> SetVisibleSize(SetVisibleSizeCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetVisibleSizeCommandSettings, SetVisibleSizeCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Allows overriding user agent with the given string. /// </summary> public async Task<SetUserAgentOverrideCommandResponse> SetUserAgentOverride(SetUserAgentOverrideCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetUserAgentOverrideCommandSettings, SetUserAgentOverrideCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } private void OnDevToolsEventReceived(object sender, DevToolsEventReceivedEventArgs e) { if (e.DomainName == m_domainName) { if (m_eventMap.ContainsKey(e.EventName)) { var eventData = m_eventMap[e.EventName]; var eventArgs = e.EventData.ToObject(eventData.EventArgsType); eventData.EventInvoker(eventArgs); } } } private void OnVirtualTimeBudgetExpired(object rawEventArgs) { VirtualTimeBudgetExpiredEventArgs e = rawEventArgs as VirtualTimeBudgetExpiredEventArgs; if (e != null && VirtualTimeBudgetExpired != null) { VirtualTimeBudgetExpired(this, e); } } } }
// // RevisionInternal.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections.Generic; using Couchbase.Lite; using Couchbase.Lite.Internal; using Sharpen; namespace Couchbase.Lite.Internal { /// <summary>Stores information about a revision -- its docID, revID, and whether it's deleted. /// </summary> /// <remarks> /// Stores information about a revision -- its docID, revID, and whether it's deleted. /// It can also store the sequence number and document contents (they can be added after creation). /// </remarks> public class RevisionInternal { private string docId; private string revId; private bool deleted; private bool missing; private Body body; private long sequence = -1; private Database database; public RevisionInternal(String docId, String revId, Boolean deleted, Database database) { // TODO: get rid of this field! this.docId = docId; this.revId = revId; this.deleted = deleted; this.database = database; } public RevisionInternal(Body body, Database database) : this((string)body.GetPropertyForKey("_id"), (string)body.GetPropertyForKey("_rev"), (body.HasValueForKey("_deleted") && (bool)body.GetPropertyForKey("_deleted")), database) { this.body = body; } public RevisionInternal(IDictionary<String, Object> properties, Database database) : this(new Body(properties), database) { } public IDictionary<String, Object> GetProperties() { IDictionary<string, object> result = null; if (body != null) { IDictionary<string, object> prop; try { prop = body.GetProperties(); } catch (InvalidOperationException) { // handle when both object and json are null for this body return null; } if (result == null) { result = new Dictionary<string, object>(); } result.PutAll(prop); } return result; } public object GetPropertyForKey(string key) { var prop = GetProperties(); if (prop == null) { return null; } return GetProperties().Get(key); } public void SetProperties(IDictionary<string, object> properties) { body = new Body(properties); } public IEnumerable<Byte> GetJson() { IEnumerable<Byte> result = null; if (body != null) { result = body.GetJson(); } return result; } public void SetJson(IEnumerable<Byte> json) { body = new Body(json); } public override bool Equals(object o) { var result = false; if (o is RevisionInternal) { RevisionInternal other = (RevisionInternal)o; if (docId.Equals(other.docId) && revId.Equals(other.revId)) { result = true; } } return result; } public override int GetHashCode() { return docId.GetHashCode() ^ revId.GetHashCode(); } public string GetDocId() { return docId; } public void SetDocId(string docId) { this.docId = docId; } public string GetRevId() { return revId; } public void SetRevId(string revId) { this.revId = revId; } public bool IsDeleted() { return deleted; } public void SetDeleted(bool deleted) { this.deleted = deleted; } public Body GetBody() { return body; } public void SetBody(Body body) { this.body = body; } public Boolean IsMissing() { return missing; } public void SetMissing(Boolean isMissing) { missing = isMissing; } public RevisionInternal CopyWithDocID(String docId, String revId) { System.Diagnostics.Debug.Assert(((docId != null) && (revId != null))); System.Diagnostics.Debug.Assert(((this.docId == null) || (this.docId.Equals(docId)))); var result = new RevisionInternal(docId, revId, deleted, database); var unmodifiableProperties = GetProperties(); var properties = new Dictionary<string, object>(); if (unmodifiableProperties != null) { properties.PutAll(unmodifiableProperties); } properties["_id"] = docId; properties["_rev"] = revId; result.SetProperties(properties); return result; } public void SetSequence(long sequence) { this.sequence = sequence; } public long GetSequence() { return sequence; } public override string ToString() { return "{" + this.docId + " #" + this.revId + (deleted ? "DEL" : string.Empty) + "}"; } /// <summary>Generation number: 1 for a new document, 2 for the 2nd revision, ...</summary> /// <remarks> /// Generation number: 1 for a new document, 2 for the 2nd revision, ... /// Extracted from the numeric prefix of the revID. /// </remarks> public int GetGeneration() { return GenerationFromRevID(revId); } public static int GenerationFromRevID(string revID) { var generation = 0; var dashPos = revID.IndexOf("-", StringComparison.InvariantCultureIgnoreCase); if (dashPos > 0) { generation = Convert.ToInt32(revID.Substring(0, dashPos)); } return generation; } public static int CBLCollateRevIDs(string revId1, string revId2) { string rev1GenerationStr = null; string rev2GenerationStr = null; string rev1Hash = null; string rev2Hash = null; var st1 = new StringTokenizer(revId1, "-"); try { rev1GenerationStr = st1.NextToken(); rev1Hash = st1.NextToken(); } catch (Exception) { } StringTokenizer st2 = new StringTokenizer(revId2, "-"); try { rev2GenerationStr = st2.NextToken(); rev2Hash = st2.NextToken(); } catch (Exception) { } // improper rev IDs; just compare as plain text: if (rev1GenerationStr == null || rev2GenerationStr == null) { return revId1.CompareToIgnoreCase(revId2); } int rev1Generation; int rev2Generation; try { rev1Generation = System.Convert.ToInt32(rev1GenerationStr); rev2Generation = System.Convert.ToInt32(rev2GenerationStr); } catch (FormatException) { // improper rev IDs; just compare as plain text: return revId1.CompareToIgnoreCase(revId2); } // Compare generation numbers; if they match, compare suffixes: if (rev1Generation.CompareTo(rev2Generation) != 0) { return rev1Generation.CompareTo(rev2Generation); } else { if (rev1Hash != null && rev2Hash != null) { // compare suffixes if possible return Sharpen.Runtime.CompareOrdinal(rev1Hash, rev2Hash); } else { // just compare as plain text: return revId1.CompareToIgnoreCase(revId2); } } } public static int CBLCompareRevIDs(string revId1, string revId2) { System.Diagnostics.Debug.Assert((revId1 != null)); System.Diagnostics.Debug.Assert((revId2 != null)); return CBLCollateRevIDs(revId1, revId2); } } }
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Runtime; using System.Runtime.Diagnostics; using System.ServiceModel; using System.ServiceModel.Diagnostics; using System.ServiceModel.Diagnostics.Application; // code that pools items and closes/aborts them as necessary. // shared by IConnection and IChannel users abstract class CommunicationPool<TKey, TItem> where TKey : class where TItem : class { Dictionary<TKey, EndpointConnectionPool> endpointPools; int maxCount; int openCount; // need to make sure we prune over a certain number of endpoint pools int pruneAccrual; const int pruneThreshold = 30; protected CommunicationPool(int maxCount) { this.maxCount = maxCount; this.endpointPools = new Dictionary<TKey, EndpointConnectionPool>(); this.openCount = 1; } public int MaxIdleConnectionPoolCount { get { return this.maxCount; } } protected object ThisLock { get { return this; } } protected abstract void AbortItem(TItem item); [Fx.Tag.Throws(typeof(CommunicationException), "A communication exception occurred closing this item")] [Fx.Tag.Throws(typeof(TimeoutException), "Timed out trying to close this item")] protected abstract void CloseItem(TItem item, TimeSpan timeout); protected abstract void CloseItemAsync(TItem item, TimeSpan timeout); protected abstract TKey GetPoolKey(EndpointAddress address, Uri via); protected virtual EndpointConnectionPool CreateEndpointConnectionPool(TKey key) { return new EndpointConnectionPool(this, key); } public bool Close(TimeSpan timeout) { lock (ThisLock) { if (openCount <= 0) { return true; } openCount--; if (openCount == 0) { this.OnClose(timeout); return true; } return false; } } List<TItem> PruneIfNecessary() { List<TItem> itemsToClose = null; pruneAccrual++; if (pruneAccrual > pruneThreshold) { pruneAccrual = 0; itemsToClose = new List<TItem>(); // first prune the connection pool contents foreach (EndpointConnectionPool pool in endpointPools.Values) { pool.Prune(itemsToClose); } // figure out which connection pools are now empty List<TKey> endpointKeysToRemove = null; foreach (KeyValuePair<TKey, EndpointConnectionPool> poolEntry in endpointPools) { if (poolEntry.Value.CloseIfEmpty()) { if (endpointKeysToRemove == null) { endpointKeysToRemove = new List<TKey>(); } endpointKeysToRemove.Add(poolEntry.Key); } } // and then prune the connection pools themselves if (endpointKeysToRemove != null) { for (int i = 0; i < endpointKeysToRemove.Count; i++) { endpointPools.Remove(endpointKeysToRemove[i]); } } } return itemsToClose; } EndpointConnectionPool GetEndpointPool(TKey key, TimeSpan timeout) { EndpointConnectionPool result = null; List<TItem> itemsToClose = null; lock (ThisLock) { if (!endpointPools.TryGetValue(key, out result)) { itemsToClose = PruneIfNecessary(); result = CreateEndpointConnectionPool(key); endpointPools.Add(key, result); } } Fx.Assert(result != null, "EndpointPool must be non-null at this point"); if (itemsToClose != null && itemsToClose.Count > 0) { // allocate half the remaining timeout for our g----ful shutdowns TimeoutHelper timeoutHelper = new TimeoutHelper(TimeoutHelper.Divide(timeout, 2)); for (int i = 0; i < itemsToClose.Count; i++) { result.CloseIdleConnection(itemsToClose[i], timeoutHelper.RemainingTime()); } } return result; } public bool TryOpen() { lock (ThisLock) { if (openCount <= 0) { // can't reopen connection pools since the registry purges them on close return false; } else { openCount++; return true; } } } protected virtual void OnClosed() { } void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); foreach (EndpointConnectionPool pool in endpointPools.Values) { try { pool.Close(timeoutHelper.RemainingTime()); } catch (CommunicationException exception) { if (DiagnosticUtility.ShouldTraceError) { TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.ConnectionPoolCloseException, SR.GetString(SR.TraceCodeConnectionPoolCloseException), this, exception); } } catch (TimeoutException exception) { if (TD.CloseTimeoutIsEnabled()) { TD.CloseTimeout(exception.Message); } if (DiagnosticUtility.ShouldTraceError) { TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.ConnectionPoolCloseException, SR.GetString(SR.TraceCodeConnectionPoolCloseException), this, exception); } } } endpointPools.Clear(); } public void AddConnection(TKey key, TItem connection, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime()); endpointPool.AddConnection(connection, timeoutHelper.RemainingTime()); } public TItem TakeConnection(EndpointAddress address, Uri via, TimeSpan timeout, out TKey key) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); key = this.GetPoolKey(address, via); EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime()); return endpointPool.TakeConnection(timeoutHelper.RemainingTime()); } public void ReturnConnection(TKey key, TItem connection, bool connectionIsStillGood, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime()); endpointPool.ReturnConnection(connection, connectionIsStillGood, timeoutHelper.RemainingTime()); } // base class for our collection of Idle connections protected abstract class IdleConnectionPool { public abstract int Count { get; } public abstract bool Add(TItem item); public abstract bool Return(TItem item); public abstract TItem Take(out bool closeItem); } protected class EndpointConnectionPool { TKey key; List<TItem> busyConnections; bool closed; IdleConnectionPool idleConnections; CommunicationPool<TKey, TItem> parent; public EndpointConnectionPool(CommunicationPool<TKey, TItem> parent, TKey key) { this.key = key; this.parent = parent; this.busyConnections = new List<TItem>(); } protected TKey Key { get { return this.key; } } IdleConnectionPool IdleConnections { get { if (idleConnections == null) { idleConnections = GetIdleConnectionPool(); } return idleConnections; } } protected CommunicationPool<TKey, TItem> Parent { get { return this.parent; } } protected object ThisLock { get { return this; } } // close down the pool if empty public bool CloseIfEmpty() { lock (ThisLock) { if (!closed) { if (busyConnections.Count > 0) { return false; } if (idleConnections != null && idleConnections.Count > 0) { return false; } closed = true; } } return true; } protected virtual void AbortItem(TItem item) { parent.AbortItem(item); } [Fx.Tag.Throws(typeof(CommunicationException), "A communication exception occurred closing this item")] [Fx.Tag.Throws(typeof(TimeoutException), "Timed out trying to close this item")] protected virtual void CloseItem(TItem item, TimeSpan timeout) { parent.CloseItem(item, timeout); } protected virtual void CloseItemAsync(TItem item, TimeSpan timeout) { parent.CloseItemAsync(item, timeout); } public void Abort() { if (closed) { return; } List<TItem> idleItemsToClose = null; lock (ThisLock) { if (closed) return; closed = true; idleItemsToClose = SnapshotIdleConnections(); } AbortConnections(idleItemsToClose); } [Fx.Tag.Throws(typeof(CommunicationException), "A communication exception occurred closing this item")] [Fx.Tag.Throws(typeof(TimeoutException), "Timed out trying to close this item")] public void Close(TimeSpan timeout) { List<TItem> itemsToClose = null; lock (ThisLock) { if (closed) return; closed = true; itemsToClose = SnapshotIdleConnections(); } try { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (int i = 0; i < itemsToClose.Count; i++) { this.CloseItem(itemsToClose[i], timeoutHelper.RemainingTime()); } itemsToClose.Clear(); } finally { AbortConnections(itemsToClose); } } void AbortConnections(List<TItem> idleItemsToClose) { for (int i = 0; i < idleItemsToClose.Count; i++) { this.AbortItem(idleItemsToClose[i]); } for (int i = 0; i < busyConnections.Count; i++) { this.AbortItem(busyConnections[i]); } busyConnections.Clear(); } // must call under lock (ThisLock) since we are calling IdleConnections.Take() List<TItem> SnapshotIdleConnections() { List<TItem> itemsToClose = new List<TItem>(); bool dummy; for (;;) { TItem item = IdleConnections.Take(out dummy); if (item == null) break; itemsToClose.Add(item); } return itemsToClose; } public void AddConnection(TItem connection, TimeSpan timeout) { bool closeConnection = false; lock (ThisLock) { if (!closed) { if (!IdleConnections.Add(connection)) { closeConnection = true; } } else { closeConnection = true; } } if (closeConnection) { CloseIdleConnection(connection, timeout); } } protected virtual IdleConnectionPool GetIdleConnectionPool() { return new PoolIdleConnectionPool(parent.MaxIdleConnectionPoolCount); } public virtual void Prune(List<TItem> itemsToClose) { } public TItem TakeConnection(TimeSpan timeout) { TItem item = null; List<TItem> itemsToClose = null; lock (ThisLock) { if (closed) return null; bool closeItem; while (true) { item = IdleConnections.Take(out closeItem); if (item == null) { break; } if (!closeItem) { busyConnections.Add(item); break; } if (itemsToClose == null) { itemsToClose = new List<TItem>(); } itemsToClose.Add(item); } } // cleanup any stale items accrued from IdleConnections if (itemsToClose != null) { // and only allocate half the timeout passed in for our g----ful shutdowns TimeoutHelper timeoutHelper = new TimeoutHelper(TimeoutHelper.Divide(timeout, 2)); for (int i = 0; i < itemsToClose.Count; i++) { CloseIdleConnection(itemsToClose[i], timeoutHelper.RemainingTime()); } } if (TD.ConnectionPoolMissIsEnabled()) { if (item == null && busyConnections != null) { TD.ConnectionPoolMiss(key != null ? key.ToString() : string.Empty, busyConnections.Count); } } return item; } public void ReturnConnection(TItem connection, bool connectionIsStillGood, TimeSpan timeout) { bool closeConnection = false; bool abortConnection = false; lock (ThisLock) { if (!closed) { if (busyConnections.Remove(connection) && connectionIsStillGood) { if (!IdleConnections.Return(connection)) { closeConnection = true; } } else { abortConnection = true; } } else { abortConnection = true; } } if (closeConnection) { CloseIdleConnection(connection, timeout); } else if (abortConnection) { this.AbortItem(connection); OnConnectionAborted(); } } public void CloseIdleConnection(TItem connection, TimeSpan timeout) { bool throwing = true; try { this.CloseItemAsync(connection, timeout); throwing = false; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } finally { if (throwing) { this.AbortItem(connection); } } } protected virtual void OnConnectionAborted() { } protected class PoolIdleConnectionPool : IdleConnectionPool { Pool<TItem> idleConnections; int maxCount; public PoolIdleConnectionPool(int maxCount) { this.idleConnections = new Pool<TItem>(maxCount); this.maxCount = maxCount; } public override int Count { get { return idleConnections.Count; } } public override bool Add(TItem connection) { return ReturnToPool(connection); } public override bool Return(TItem connection) { return ReturnToPool(connection); } bool ReturnToPool(TItem connection) { bool result = this.idleConnections.Return(connection); if (!result) { if (TD.MaxOutboundConnectionsPerEndpointExceededIsEnabled()) { TD.MaxOutboundConnectionsPerEndpointExceeded(SR.GetString(SR.TraceCodeConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached, maxCount)); } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached, SR.GetString(SR.TraceCodeConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached, maxCount), this); } } else if (TD.OutboundConnectionsPerEndpointRatioIsEnabled()) { TD.OutboundConnectionsPerEndpointRatio(this.idleConnections.Count, maxCount); } return result; } public override TItem Take(out bool closeItem) { closeItem = false; TItem ret = this.idleConnections.Take(); if (TD.OutboundConnectionsPerEndpointRatioIsEnabled()) { TD.OutboundConnectionsPerEndpointRatio(this.idleConnections.Count, maxCount); } return ret; } } } } // all our connection pools support Idling out of connections and lease timeout // (though Named Pipes doesn't leverage the lease timeout) abstract class ConnectionPool : IdlingCommunicationPool<string, IConnection> { int connectionBufferSize; TimeSpan maxOutputDelay; string name; protected ConnectionPool(IConnectionOrientedTransportChannelFactorySettings settings, TimeSpan leaseTimeout) : base(settings.MaxOutboundConnectionsPerEndpoint, settings.IdleTimeout, leaseTimeout) { this.connectionBufferSize = settings.ConnectionBufferSize; this.maxOutputDelay = settings.MaxOutputDelay; this.name = settings.ConnectionPoolGroupName; } public string Name { get { return this.name; } } protected override void AbortItem(IConnection item) { item.Abort(); } protected override void CloseItem(IConnection item, TimeSpan timeout) { item.Close(timeout, false); } protected override void CloseItemAsync(IConnection item, TimeSpan timeout) { item.Close(timeout, true); } public virtual bool IsCompatible(IConnectionOrientedTransportChannelFactorySettings settings) { return ( (this.name == settings.ConnectionPoolGroupName) && (this.connectionBufferSize == settings.ConnectionBufferSize) && (this.MaxIdleConnectionPoolCount == settings.MaxOutboundConnectionsPerEndpoint) && (this.IdleTimeout == settings.IdleTimeout) && (this.maxOutputDelay == settings.MaxOutputDelay) ); } } // Helper class used to manage the lifetime of a connection relative to its pool. abstract class ConnectionPoolHelper { IConnectionInitiator connectionInitiator; ConnectionPool connectionPool; Uri via; bool closed; // key for rawConnection in the connection pool string connectionKey; // did rawConnection originally come from connectionPool? bool isConnectionFromPool; // the "raw" connection that should be stored in the pool IConnection rawConnection; // the "upgraded" connection built on top of the "raw" connection to be used for I/O IConnection upgradedConnection; EventTraceActivity eventTraceActivity; public ConnectionPoolHelper(ConnectionPool connectionPool, IConnectionInitiator connectionInitiator, Uri via) { this.connectionInitiator = connectionInitiator; this.connectionPool = connectionPool; this.via = via; } object ThisLock { get { return this; } } protected EventTraceActivity EventTraceActivity { get { if (this.eventTraceActivity == null) { this.eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate(); } return this.eventTraceActivity; } } protected abstract IConnection AcceptPooledConnection(IConnection connection, ref TimeoutHelper timeoutHelper); protected abstract IAsyncResult BeginAcceptPooledConnection(IConnection connection, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state); protected abstract IConnection EndAcceptPooledConnection(IAsyncResult result); protected abstract TimeoutException CreateNewConnectionTimeoutException(TimeSpan timeout, TimeoutException innerException); public IAsyncResult BeginEstablishConnection(TimeSpan timeout, AsyncCallback callback, object state) { return new EstablishConnectionAsyncResult(this, timeout, callback, state); } public IConnection EndEstablishConnection(IAsyncResult result) { return EstablishConnectionAsyncResult.End(result); } IConnection TakeConnection(TimeSpan timeout) { return this.connectionPool.TakeConnection(null, this.via, timeout, out this.connectionKey); } public IConnection EstablishConnection(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); IConnection localRawConnection = null; IConnection localUpgradedConnection = null; bool localIsConnectionFromPool = true; EventTraceActivity localEventTraceActivity = this.EventTraceActivity; if (TD.EstablishConnectionStartIsEnabled()) { TD.EstablishConnectionStart(localEventTraceActivity, this.via != null ? this.via.AbsoluteUri : string.Empty); } // first try and use a connection from our pool (and use it if we successfully receive an ACK) while (localIsConnectionFromPool) { localRawConnection = this.TakeConnection(timeoutHelper.RemainingTime()); if (localRawConnection == null) { localIsConnectionFromPool = false; } else { bool preambleSuccess = false; try { localUpgradedConnection = AcceptPooledConnection(localRawConnection, ref timeoutHelper); preambleSuccess = true; break; } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); // CommmunicationException is ok since it was a cached connection of unknown state } catch (TimeoutException e) { if (TD.OpenTimeoutIsEnabled()) { TD.OpenTimeout(e.Message); } DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); // ditto for TimeoutException } finally { if (!preambleSuccess) { if (TD.ConnectionPoolPreambleFailedIsEnabled()) { TD.ConnectionPoolPreambleFailed(localEventTraceActivity); } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.FailedAcceptFromPool, SR.GetString( SR.TraceCodeFailedAcceptFromPool, timeoutHelper.RemainingTime())); } // This cannot throw TimeoutException since isConnectionStillGood is false (doesn't attempt a Close). this.connectionPool.ReturnConnection(connectionKey, localRawConnection, false, TimeSpan.Zero); } } } } // if there isn't anything in the pool, we need to use a new connection if (!localIsConnectionFromPool) { bool success = false; TimeSpan connectTimeout = timeoutHelper.RemainingTime(); try { try { localRawConnection = this.connectionInitiator.Connect(this.via, connectTimeout); } catch (TimeoutException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateNewConnectionTimeoutException( connectTimeout, e)); } this.connectionInitiator = null; localUpgradedConnection = AcceptPooledConnection(localRawConnection, ref timeoutHelper); success = true; } finally { if (!success) { connectionKey = null; if (localRawConnection != null) { localRawConnection.Abort(); } } } } SnapshotConnection(localUpgradedConnection, localRawConnection, localIsConnectionFromPool); if (TD.EstablishConnectionStopIsEnabled()) { TD.EstablishConnectionStop(localEventTraceActivity); } return localUpgradedConnection; } void SnapshotConnection(IConnection upgradedConnection, IConnection rawConnection, bool isConnectionFromPool) { lock (ThisLock) { if (closed) { upgradedConnection.Abort(); // cleanup our pool if necessary if (isConnectionFromPool) { this.connectionPool.ReturnConnection(this.connectionKey, rawConnection, false, TimeSpan.Zero); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CommunicationObjectAbortedException( SR.GetString(SR.OperationAbortedDuringConnectionEstablishment, this.via))); } else { this.upgradedConnection = upgradedConnection; this.rawConnection = rawConnection; this.isConnectionFromPool = isConnectionFromPool; } } } public void Abort() { ReleaseConnection(true, TimeSpan.Zero); } public void Close(TimeSpan timeout) { ReleaseConnection(false, timeout); } void ReleaseConnection(bool abort, TimeSpan timeout) { string localConnectionKey; IConnection localUpgradedConnection; IConnection localRawConnection; lock (ThisLock) { this.closed = true; localConnectionKey = this.connectionKey; localUpgradedConnection = this.upgradedConnection; localRawConnection = this.rawConnection; this.upgradedConnection = null; this.rawConnection = null; } if (localUpgradedConnection == null) { return; } try { if (this.isConnectionFromPool) { this.connectionPool.ReturnConnection(localConnectionKey, localRawConnection, !abort, timeout); } else { if (abort) { localUpgradedConnection.Abort(); } else { this.connectionPool.AddConnection(localConnectionKey, localRawConnection, timeout); } } } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); localUpgradedConnection.Abort(); } } class EstablishConnectionAsyncResult : AsyncResult { ConnectionPoolHelper parent; TimeoutHelper timeoutHelper; IConnection currentConnection; IConnection rawConnection; bool newConnection; bool cleanupConnection; TimeSpan connectTimeout; static AsyncCallback onConnect; static AsyncCallback onProcessConnection = Fx.ThunkCallback(new AsyncCallback(OnProcessConnection)); EventTraceActivity eventTraceActivity; public EstablishConnectionAsyncResult(ConnectionPoolHelper parent, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.parent = parent; this.timeoutHelper = new TimeoutHelper(timeout); bool success = false; bool completeSelf = false; try { completeSelf = Begin(); success = true; } finally { if (!success) { Cleanup(); } } if (completeSelf) { Cleanup(); base.Complete(true); } } EventTraceActivity EventTraceActivity { get { if (this.eventTraceActivity == null) { this.eventTraceActivity = new EventTraceActivity(); } return this.eventTraceActivity; } } public static IConnection End(IAsyncResult result) { EstablishConnectionAsyncResult thisPtr = AsyncResult.End<EstablishConnectionAsyncResult>(result); if (TD.EstablishConnectionStopIsEnabled()) { TD.EstablishConnectionStop(thisPtr.EventTraceActivity); } return thisPtr.currentConnection; } bool Begin() { if (TD.EstablishConnectionStartIsEnabled()) { TD.EstablishConnectionStart(this.EventTraceActivity, this.parent.connectionKey); } IConnection connection = parent.TakeConnection(timeoutHelper.RemainingTime()); TrackConnection(connection); // first try and use a connection from our pool bool openingFromPool; if (OpenUsingConnectionPool(out openingFromPool)) { return true; } if (openingFromPool) { return false; } else { // if there isn't anything in the pool, we need to use a new connection return OpenUsingNewConnection(); } } bool OpenUsingConnectionPool(out bool openingFromPool) { openingFromPool = true; while (this.currentConnection != null) { bool snapshotCollection = false; try { if (ProcessConnection()) { snapshotCollection = true; } else { return false; } } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); // CommunicationException is allowed for cached channels, as the connection // could be stale Cleanup(); // remove residual state } catch (TimeoutException e) { if (TD.OpenTimeoutIsEnabled()) { TD.OpenTimeout(e.Message); } DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); // ditto for TimeoutException Cleanup(); // remove residual state } if (snapshotCollection) // connection succeeded. Snapshot and return { SnapshotConnection(); return true; } // previous connection failed, try again IConnection connection = parent.TakeConnection(timeoutHelper.RemainingTime()); TrackConnection(connection); } openingFromPool = false; return false; } bool OpenUsingNewConnection() { this.newConnection = true; IAsyncResult result; try { this.connectTimeout = timeoutHelper.RemainingTime(); if (onConnect == null) { onConnect = Fx.ThunkCallback(new AsyncCallback(OnConnect)); } result = parent.connectionInitiator.BeginConnect( parent.via, this.connectTimeout, onConnect, this); } catch (TimeoutException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( parent.CreateNewConnectionTimeoutException(connectTimeout, e)); } if (!result.CompletedSynchronously) { return false; } return HandleConnect(result); } bool HandleConnect(IAsyncResult connectResult) { try { TrackConnection(parent.connectionInitiator.EndConnect(connectResult)); } catch (TimeoutException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( parent.CreateNewConnectionTimeoutException(connectTimeout, e)); } if (ProcessConnection()) { // success. Snapshot and return SnapshotConnection(); return true; } else { return false; } } bool ProcessConnection() { IAsyncResult result = parent.BeginAcceptPooledConnection(this.rawConnection, ref timeoutHelper, onProcessConnection, this); if (!result.CompletedSynchronously) { return false; } return HandleProcessConnection(result); } bool HandleProcessConnection(IAsyncResult result) { this.currentConnection = parent.EndAcceptPooledConnection(result); this.cleanupConnection = false; return true; } void SnapshotConnection() { parent.SnapshotConnection(this.currentConnection, this.rawConnection, !this.newConnection); } void TrackConnection(IConnection connection) { this.cleanupConnection = true; this.rawConnection = connection; this.currentConnection = connection; } void Cleanup() { if (this.cleanupConnection) { if (this.newConnection) { if (this.currentConnection != null) { this.currentConnection.Abort(); this.currentConnection = null; } } else if (this.rawConnection != null) { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent( TraceEventType.Information, TraceCode.FailedAcceptFromPool, SR.GetString( SR.TraceCodeFailedAcceptFromPool, this.timeoutHelper.RemainingTime())); } // This cannot throw TimeoutException since isConnectionStillGood is false (doesn't attempt a Close). parent.connectionPool.ReturnConnection(parent.connectionKey, this.rawConnection, false, timeoutHelper.RemainingTime()); this.currentConnection = null; this.rawConnection = null; } this.cleanupConnection = false; } } static void OnConnect(IAsyncResult result) { if (result.CompletedSynchronously) { return; } EstablishConnectionAsyncResult thisPtr = (EstablishConnectionAsyncResult)result.AsyncState; Exception completionException = null; bool completeSelf; try { completeSelf = thisPtr.HandleConnect(result); } #pragma warning suppress 56500 // [....], transferring exception to another thread catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completeSelf = true; completionException = e; } if (completeSelf) { thisPtr.Cleanup(); thisPtr.Complete(false, completionException); } } static void OnProcessConnection(IAsyncResult result) { if (result.CompletedSynchronously) { return; } EstablishConnectionAsyncResult thisPtr = (EstablishConnectionAsyncResult)result.AsyncState; Exception completionException = null; bool completeSelf; try { bool snapshotCollection = false; try { completeSelf = thisPtr.HandleProcessConnection(result); if (completeSelf) { snapshotCollection = true; } } catch (CommunicationException communicationException) { if (!thisPtr.newConnection) // CommunicationException is ok from our cache { DiagnosticUtility.TraceHandledException(communicationException, TraceEventType.Information); thisPtr.Cleanup(); completeSelf = thisPtr.Begin(); } else { completeSelf = true; completionException = communicationException; } } catch (TimeoutException timeoutException) { if (!thisPtr.newConnection) // TimeoutException is ok from our cache { if (TD.OpenTimeoutIsEnabled()) { TD.OpenTimeout(timeoutException.Message); } DiagnosticUtility.TraceHandledException(timeoutException, TraceEventType.Information); thisPtr.Cleanup(); completeSelf = thisPtr.Begin(); } else { completeSelf = true; completionException = timeoutException; } } if (snapshotCollection) { thisPtr.SnapshotConnection(); } } #pragma warning suppress 56500 // [....], transferring exception to another thread catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completeSelf = true; completionException = e; } if (completeSelf) { thisPtr.Cleanup(); thisPtr.Complete(false, completionException); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AddByte() { var test = new SimpleBinaryOpTest__AddByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Byte> _fld1; public Vector64<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddByte testClass) { var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddByte testClass) { fixed (Vector64<Byte>* pFld1 = &_fld1) fixed (Vector64<Byte>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector64<Byte> _clsVar1; private static Vector64<Byte> _clsVar2; private Vector64<Byte> _fld1; private Vector64<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); } public SimpleBinaryOpTest__AddByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Add( Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Add( AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Byte>* pClsVar1 = &_clsVar1) fixed (Vector64<Byte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((Byte*)(pClsVar1)), AdvSimd.LoadVector64((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddByte(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AddByte(); fixed (Vector64<Byte>* pFld1 = &test._fld1) fixed (Vector64<Byte>* pFld2 = &test._fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Byte>* pFld1 = &_fld1) fixed (Vector64<Byte>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((Byte*)(pFld1)), AdvSimd.LoadVector64((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Add( AdvSimd.LoadVector64((Byte*)(&test._fld1)), AdvSimd.LoadVector64((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Byte> op1, Vector64<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((byte)(left[0] + right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((byte)(left[i] + right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<Byte>(Vector64<Byte>, Vector64<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
namespace java.nio { [global::MonoJavaBridge.JavaClass(typeof(global::java.nio.ByteBuffer_))] public abstract partial class ByteBuffer : java.nio.Buffer, java.lang.Comparable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ByteBuffer() { InitJNI(); } protected ByteBuffer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _get14000; public abstract byte get(); internal static global::MonoJavaBridge.MethodId _get14001; public virtual global::java.nio.ByteBuffer get(byte[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer._get14001, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._get14001, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _get14002; public virtual global::java.nio.ByteBuffer get(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer._get14002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._get14002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _get14003; public abstract byte get(int arg0); internal static global::MonoJavaBridge.MethodId _put14004; public virtual global::java.nio.ByteBuffer put(java.nio.ByteBuffer arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer._put14004, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._put14004, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _put14005; public virtual global::java.nio.ByteBuffer put(byte[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer._put14005, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._put14005, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _put14006; public abstract global::java.nio.ByteBuffer put(byte arg0); internal static global::MonoJavaBridge.MethodId _put14007; public abstract global::java.nio.ByteBuffer put(int arg0, byte arg1); internal static global::MonoJavaBridge.MethodId _put14008; public virtual global::java.nio.ByteBuffer put(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer._put14008, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._put14008, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _equals14009; public override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.ByteBuffer._equals14009, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._equals14009, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString14010; public override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer._toString14010)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._toString14010)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode14011; public override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.ByteBuffer._hashCode14011); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._hashCode14011); } internal static global::MonoJavaBridge.MethodId _compareTo14012; public virtual int compareTo(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.ByteBuffer._compareTo14012, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._compareTo14012, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _compareTo14013; public virtual int compareTo(java.nio.ByteBuffer arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.ByteBuffer._compareTo14013, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._compareTo14013, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getShort14014; public abstract short getShort(int arg0); internal static global::MonoJavaBridge.MethodId _getShort14015; public abstract short getShort(); internal static global::MonoJavaBridge.MethodId _putShort14016; public abstract global::java.nio.ByteBuffer putShort(int arg0, short arg1); internal static global::MonoJavaBridge.MethodId _putShort14017; public abstract global::java.nio.ByteBuffer putShort(short arg0); internal static global::MonoJavaBridge.MethodId _getChar14018; public abstract char getChar(); internal static global::MonoJavaBridge.MethodId _getChar14019; public abstract char getChar(int arg0); internal static global::MonoJavaBridge.MethodId _putChar14020; public abstract global::java.nio.ByteBuffer putChar(int arg0, char arg1); internal static global::MonoJavaBridge.MethodId _putChar14021; public abstract global::java.nio.ByteBuffer putChar(char arg0); internal static global::MonoJavaBridge.MethodId _getInt14022; public abstract int getInt(); internal static global::MonoJavaBridge.MethodId _getInt14023; public abstract int getInt(int arg0); internal static global::MonoJavaBridge.MethodId _putInt14024; public abstract global::java.nio.ByteBuffer putInt(int arg0, int arg1); internal static global::MonoJavaBridge.MethodId _putInt14025; public abstract global::java.nio.ByteBuffer putInt(int arg0); internal static global::MonoJavaBridge.MethodId _getLong14026; public abstract long getLong(int arg0); internal static global::MonoJavaBridge.MethodId _getLong14027; public abstract long getLong(); internal static global::MonoJavaBridge.MethodId _putLong14028; public abstract global::java.nio.ByteBuffer putLong(long arg0); internal static global::MonoJavaBridge.MethodId _putLong14029; public abstract global::java.nio.ByteBuffer putLong(int arg0, long arg1); internal static global::MonoJavaBridge.MethodId _getFloat14030; public abstract float getFloat(); internal static global::MonoJavaBridge.MethodId _getFloat14031; public abstract float getFloat(int arg0); internal static global::MonoJavaBridge.MethodId _putFloat14032; public abstract global::java.nio.ByteBuffer putFloat(float arg0); internal static global::MonoJavaBridge.MethodId _putFloat14033; public abstract global::java.nio.ByteBuffer putFloat(int arg0, float arg1); internal static global::MonoJavaBridge.MethodId _getDouble14034; public abstract double getDouble(); internal static global::MonoJavaBridge.MethodId _getDouble14035; public abstract double getDouble(int arg0); internal static global::MonoJavaBridge.MethodId _putDouble14036; public abstract global::java.nio.ByteBuffer putDouble(int arg0, double arg1); internal static global::MonoJavaBridge.MethodId _putDouble14037; public abstract global::java.nio.ByteBuffer putDouble(double arg0); internal static global::MonoJavaBridge.MethodId _isDirect14038; public abstract bool isDirect(); internal static global::MonoJavaBridge.MethodId _hasArray14039; public sealed override bool hasArray() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.ByteBuffer._hasArray14039); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._hasArray14039); } internal static global::MonoJavaBridge.MethodId _array14040; public override global::java.lang.Object array() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer._array14040)) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._array14040)) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _arrayOffset14041; public sealed override int arrayOffset() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.ByteBuffer._arrayOffset14041); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._arrayOffset14041); } internal static global::MonoJavaBridge.MethodId _wrap14042; public static global::java.nio.ByteBuffer wrap(byte[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._wrap14042, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _wrap14043; public static global::java.nio.ByteBuffer wrap(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._wrap14043, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _allocate14044; public static global::java.nio.ByteBuffer allocate(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._allocate14044, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _duplicate14045; public abstract global::java.nio.ByteBuffer duplicate(); internal static global::MonoJavaBridge.MethodId _allocateDirect14046; public static global::java.nio.ByteBuffer allocateDirect(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._allocateDirect14046, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _slice14047; public abstract global::java.nio.ByteBuffer slice(); internal static global::MonoJavaBridge.MethodId _asReadOnlyBuffer14048; public abstract global::java.nio.ByteBuffer asReadOnlyBuffer(); internal static global::MonoJavaBridge.MethodId _compact14049; public abstract global::java.nio.ByteBuffer compact(); internal static global::MonoJavaBridge.MethodId _order14050; public virtual global::java.nio.ByteBuffer order(java.nio.ByteOrder arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer._order14050, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._order14050, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _order14051; public virtual global::java.nio.ByteOrder order() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer._order14051)) as java.nio.ByteOrder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer.staticClass, global::java.nio.ByteBuffer._order14051)) as java.nio.ByteOrder; } internal static global::MonoJavaBridge.MethodId _asCharBuffer14052; public abstract global::java.nio.CharBuffer asCharBuffer(); internal static global::MonoJavaBridge.MethodId _asShortBuffer14053; public abstract global::java.nio.ShortBuffer asShortBuffer(); internal static global::MonoJavaBridge.MethodId _asIntBuffer14054; public abstract global::java.nio.IntBuffer asIntBuffer(); internal static global::MonoJavaBridge.MethodId _asLongBuffer14055; public abstract global::java.nio.LongBuffer asLongBuffer(); internal static global::MonoJavaBridge.MethodId _asFloatBuffer14056; public abstract global::java.nio.FloatBuffer asFloatBuffer(); internal static global::MonoJavaBridge.MethodId _asDoubleBuffer14057; public abstract global::java.nio.DoubleBuffer asDoubleBuffer(); private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.nio.ByteBuffer.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/ByteBuffer")); global::java.nio.ByteBuffer._get14000 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "get", "()B"); global::java.nio.ByteBuffer._get14001 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "get", "([B)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._get14002 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "get", "([BII)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._get14003 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "get", "(I)B"); global::java.nio.ByteBuffer._put14004 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "put", "(Ljava/nio/ByteBuffer;)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._put14005 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "put", "([B)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._put14006 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "put", "(B)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._put14007 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "put", "(IB)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._put14008 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "put", "([BII)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._equals14009 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::java.nio.ByteBuffer._toString14010 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "toString", "()Ljava/lang/String;"); global::java.nio.ByteBuffer._hashCode14011 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "hashCode", "()I"); global::java.nio.ByteBuffer._compareTo14012 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "compareTo", "(Ljava/lang/Object;)I"); global::java.nio.ByteBuffer._compareTo14013 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "compareTo", "(Ljava/nio/ByteBuffer;)I"); global::java.nio.ByteBuffer._getShort14014 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getShort", "(I)S"); global::java.nio.ByteBuffer._getShort14015 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getShort", "()S"); global::java.nio.ByteBuffer._putShort14016 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putShort", "(IS)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._putShort14017 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putShort", "(S)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._getChar14018 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getChar", "()C"); global::java.nio.ByteBuffer._getChar14019 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getChar", "(I)C"); global::java.nio.ByteBuffer._putChar14020 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putChar", "(IC)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._putChar14021 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putChar", "(C)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._getInt14022 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getInt", "()I"); global::java.nio.ByteBuffer._getInt14023 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getInt", "(I)I"); global::java.nio.ByteBuffer._putInt14024 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putInt", "(II)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._putInt14025 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putInt", "(I)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._getLong14026 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getLong", "(I)J"); global::java.nio.ByteBuffer._getLong14027 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getLong", "()J"); global::java.nio.ByteBuffer._putLong14028 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putLong", "(J)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._putLong14029 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putLong", "(IJ)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._getFloat14030 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getFloat", "()F"); global::java.nio.ByteBuffer._getFloat14031 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getFloat", "(I)F"); global::java.nio.ByteBuffer._putFloat14032 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putFloat", "(F)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._putFloat14033 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putFloat", "(IF)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._getDouble14034 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getDouble", "()D"); global::java.nio.ByteBuffer._getDouble14035 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "getDouble", "(I)D"); global::java.nio.ByteBuffer._putDouble14036 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putDouble", "(ID)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._putDouble14037 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "putDouble", "(D)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._isDirect14038 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "isDirect", "()Z"); global::java.nio.ByteBuffer._hasArray14039 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "hasArray", "()Z"); global::java.nio.ByteBuffer._array14040 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "array", "()Ljava/lang/Object;"); global::java.nio.ByteBuffer._arrayOffset14041 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "arrayOffset", "()I"); global::java.nio.ByteBuffer._wrap14042 = @__env.GetStaticMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "wrap", "([B)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._wrap14043 = @__env.GetStaticMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "wrap", "([BII)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._allocate14044 = @__env.GetStaticMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "allocate", "(I)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._duplicate14045 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "duplicate", "()Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._allocateDirect14046 = @__env.GetStaticMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "allocateDirect", "(I)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._slice14047 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "slice", "()Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._asReadOnlyBuffer14048 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "asReadOnlyBuffer", "()Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._compact14049 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "compact", "()Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._order14050 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "order", "(Ljava/nio/ByteOrder;)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer._order14051 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "order", "()Ljava/nio/ByteOrder;"); global::java.nio.ByteBuffer._asCharBuffer14052 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "asCharBuffer", "()Ljava/nio/CharBuffer;"); global::java.nio.ByteBuffer._asShortBuffer14053 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "asShortBuffer", "()Ljava/nio/ShortBuffer;"); global::java.nio.ByteBuffer._asIntBuffer14054 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "asIntBuffer", "()Ljava/nio/IntBuffer;"); global::java.nio.ByteBuffer._asLongBuffer14055 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "asLongBuffer", "()Ljava/nio/LongBuffer;"); global::java.nio.ByteBuffer._asFloatBuffer14056 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "asFloatBuffer", "()Ljava/nio/FloatBuffer;"); global::java.nio.ByteBuffer._asDoubleBuffer14057 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer.staticClass, "asDoubleBuffer", "()Ljava/nio/DoubleBuffer;"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.nio.ByteBuffer))] public sealed partial class ByteBuffer_ : java.nio.ByteBuffer { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ByteBuffer_() { InitJNI(); } internal ByteBuffer_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _get14058; public override byte get() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallByteMethod(this.JvmHandle, global::java.nio.ByteBuffer_._get14058); else return @__env.CallNonVirtualByteMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._get14058); } internal static global::MonoJavaBridge.MethodId _get14059; public override byte get(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallByteMethod(this.JvmHandle, global::java.nio.ByteBuffer_._get14059, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualByteMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._get14059, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _put14060; public override global::java.nio.ByteBuffer put(byte arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._put14060, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._put14060, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _put14061; public override global::java.nio.ByteBuffer put(int arg0, byte arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._put14061, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._put14061, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _getShort14062; public override short getShort(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallShortMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getShort14062, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getShort14062, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getShort14063; public override short getShort() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallShortMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getShort14063); else return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getShort14063); } internal static global::MonoJavaBridge.MethodId _putShort14064; public override global::java.nio.ByteBuffer putShort(int arg0, short arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putShort14064, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putShort14064, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _putShort14065; public override global::java.nio.ByteBuffer putShort(short arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putShort14065, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putShort14065, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _getChar14066; public override char getChar() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallCharMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getChar14066); else return @__env.CallNonVirtualCharMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getChar14066); } internal static global::MonoJavaBridge.MethodId _getChar14067; public override char getChar(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallCharMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getChar14067, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualCharMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getChar14067, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _putChar14068; public override global::java.nio.ByteBuffer putChar(int arg0, char arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putChar14068, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putChar14068, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _putChar14069; public override global::java.nio.ByteBuffer putChar(char arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putChar14069, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putChar14069, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _getInt14070; public override int getInt() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getInt14070); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getInt14070); } internal static global::MonoJavaBridge.MethodId _getInt14071; public override int getInt(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getInt14071, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getInt14071, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _putInt14072; public override global::java.nio.ByteBuffer putInt(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putInt14072, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putInt14072, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _putInt14073; public override global::java.nio.ByteBuffer putInt(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putInt14073, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putInt14073, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _getLong14074; public override long getLong(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getLong14074, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getLong14074, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getLong14075; public override long getLong() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getLong14075); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getLong14075); } internal static global::MonoJavaBridge.MethodId _putLong14076; public override global::java.nio.ByteBuffer putLong(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putLong14076, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putLong14076, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _putLong14077; public override global::java.nio.ByteBuffer putLong(int arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putLong14077, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putLong14077, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _getFloat14078; public override float getFloat() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getFloat14078); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getFloat14078); } internal static global::MonoJavaBridge.MethodId _getFloat14079; public override float getFloat(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getFloat14079, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getFloat14079, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _putFloat14080; public override global::java.nio.ByteBuffer putFloat(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putFloat14080, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putFloat14080, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _putFloat14081; public override global::java.nio.ByteBuffer putFloat(int arg0, float arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putFloat14081, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putFloat14081, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _getDouble14082; public override double getDouble() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallDoubleMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getDouble14082); else return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getDouble14082); } internal static global::MonoJavaBridge.MethodId _getDouble14083; public override double getDouble(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallDoubleMethod(this.JvmHandle, global::java.nio.ByteBuffer_._getDouble14083, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._getDouble14083, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _putDouble14084; public override global::java.nio.ByteBuffer putDouble(int arg0, double arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putDouble14084, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putDouble14084, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _putDouble14085; public override global::java.nio.ByteBuffer putDouble(double arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._putDouble14085, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._putDouble14085, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _isDirect14086; public override bool isDirect() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.ByteBuffer_._isDirect14086); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._isDirect14086); } internal static global::MonoJavaBridge.MethodId _duplicate14087; public override global::java.nio.ByteBuffer duplicate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._duplicate14087)) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._duplicate14087)) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _slice14088; public override global::java.nio.ByteBuffer slice() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._slice14088)) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._slice14088)) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _asReadOnlyBuffer14089; public override global::java.nio.ByteBuffer asReadOnlyBuffer() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._asReadOnlyBuffer14089)) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._asReadOnlyBuffer14089)) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _compact14090; public override global::java.nio.ByteBuffer compact() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._compact14090)) as java.nio.ByteBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._compact14090)) as java.nio.ByteBuffer; } internal static global::MonoJavaBridge.MethodId _asCharBuffer14091; public override global::java.nio.CharBuffer asCharBuffer() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._asCharBuffer14091)) as java.nio.CharBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._asCharBuffer14091)) as java.nio.CharBuffer; } internal static global::MonoJavaBridge.MethodId _asShortBuffer14092; public override global::java.nio.ShortBuffer asShortBuffer() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._asShortBuffer14092)) as java.nio.ShortBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._asShortBuffer14092)) as java.nio.ShortBuffer; } internal static global::MonoJavaBridge.MethodId _asIntBuffer14093; public override global::java.nio.IntBuffer asIntBuffer() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._asIntBuffer14093)) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._asIntBuffer14093)) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _asLongBuffer14094; public override global::java.nio.LongBuffer asLongBuffer() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._asLongBuffer14094)) as java.nio.LongBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._asLongBuffer14094)) as java.nio.LongBuffer; } internal static global::MonoJavaBridge.MethodId _asFloatBuffer14095; public override global::java.nio.FloatBuffer asFloatBuffer() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._asFloatBuffer14095)) as java.nio.FloatBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._asFloatBuffer14095)) as java.nio.FloatBuffer; } internal static global::MonoJavaBridge.MethodId _asDoubleBuffer14096; public override global::java.nio.DoubleBuffer asDoubleBuffer() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_._asDoubleBuffer14096)) as java.nio.DoubleBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._asDoubleBuffer14096)) as java.nio.DoubleBuffer; } internal static global::MonoJavaBridge.MethodId _isReadOnly14097; public override bool isReadOnly() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.ByteBuffer_._isReadOnly14097); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.ByteBuffer_.staticClass, global::java.nio.ByteBuffer_._isReadOnly14097); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.nio.ByteBuffer_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/ByteBuffer")); global::java.nio.ByteBuffer_._get14058 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "get", "()B"); global::java.nio.ByteBuffer_._get14059 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "get", "(I)B"); global::java.nio.ByteBuffer_._put14060 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "put", "(B)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._put14061 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "put", "(IB)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._getShort14062 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getShort", "(I)S"); global::java.nio.ByteBuffer_._getShort14063 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getShort", "()S"); global::java.nio.ByteBuffer_._putShort14064 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putShort", "(IS)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._putShort14065 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putShort", "(S)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._getChar14066 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getChar", "()C"); global::java.nio.ByteBuffer_._getChar14067 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getChar", "(I)C"); global::java.nio.ByteBuffer_._putChar14068 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putChar", "(IC)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._putChar14069 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putChar", "(C)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._getInt14070 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getInt", "()I"); global::java.nio.ByteBuffer_._getInt14071 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getInt", "(I)I"); global::java.nio.ByteBuffer_._putInt14072 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putInt", "(II)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._putInt14073 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putInt", "(I)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._getLong14074 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getLong", "(I)J"); global::java.nio.ByteBuffer_._getLong14075 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getLong", "()J"); global::java.nio.ByteBuffer_._putLong14076 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putLong", "(J)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._putLong14077 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putLong", "(IJ)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._getFloat14078 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getFloat", "()F"); global::java.nio.ByteBuffer_._getFloat14079 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getFloat", "(I)F"); global::java.nio.ByteBuffer_._putFloat14080 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putFloat", "(F)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._putFloat14081 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putFloat", "(IF)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._getDouble14082 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getDouble", "()D"); global::java.nio.ByteBuffer_._getDouble14083 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "getDouble", "(I)D"); global::java.nio.ByteBuffer_._putDouble14084 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putDouble", "(ID)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._putDouble14085 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "putDouble", "(D)Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._isDirect14086 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "isDirect", "()Z"); global::java.nio.ByteBuffer_._duplicate14087 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "duplicate", "()Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._slice14088 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "slice", "()Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._asReadOnlyBuffer14089 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "asReadOnlyBuffer", "()Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._compact14090 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "compact", "()Ljava/nio/ByteBuffer;"); global::java.nio.ByteBuffer_._asCharBuffer14091 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "asCharBuffer", "()Ljava/nio/CharBuffer;"); global::java.nio.ByteBuffer_._asShortBuffer14092 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "asShortBuffer", "()Ljava/nio/ShortBuffer;"); global::java.nio.ByteBuffer_._asIntBuffer14093 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "asIntBuffer", "()Ljava/nio/IntBuffer;"); global::java.nio.ByteBuffer_._asLongBuffer14094 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "asLongBuffer", "()Ljava/nio/LongBuffer;"); global::java.nio.ByteBuffer_._asFloatBuffer14095 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "asFloatBuffer", "()Ljava/nio/FloatBuffer;"); global::java.nio.ByteBuffer_._asDoubleBuffer14096 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "asDoubleBuffer", "()Ljava/nio/DoubleBuffer;"); global::java.nio.ByteBuffer_._isReadOnly14097 = @__env.GetMethodIDNoThrow(global::java.nio.ByteBuffer_.staticClass, "isReadOnly", "()Z"); } } }
using System; using System.ComponentModel.Design; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Input; using System.Windows.Threading; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using NuGet.VisualStudio; using NuGetConsole.Implementation.Console; using NuGetConsole.Implementation.PowerConsole; namespace NuGetConsole.Implementation { /// <summary> /// This class implements the tool window. /// </summary> [Guid("0AD07096-BBA9-4900-A651-0598D26F6D24")] public sealed class PowerConsoleToolWindow : ToolWindowPane, IOleCommandTarget, IPowerConsoleService { /// <summary> /// Get VS IComponentModel service. /// </summary> private IComponentModel ComponentModel { get { return this.GetService<IComponentModel>(typeof(SComponentModel)); } } private IProductUpdateService ProductUpdateService { get { return ComponentModel.GetService<IProductUpdateService>(); } } private IPackageRestoreManager PackageRestoreManager { get { return ComponentModel.GetService<IPackageRestoreManager>(); } } private PowerConsoleWindow PowerConsoleWindow { get { return ComponentModel.GetService<IPowerConsoleWindow>() as PowerConsoleWindow; } } private IVsUIShell VsUIShell { get { return this.GetService<IVsUIShell>(typeof(SVsUIShell)); } } private bool IsToolbarEnabled { get { return _wpfConsole != null && _wpfConsole.Dispatcher.IsStartCompleted && _wpfConsole.Host != null && _wpfConsole.Host.IsCommandEnabled; } } /// <summary> /// Standard constructor for the tool window. /// </summary> public PowerConsoleToolWindow() : base(null) { this.Caption = Resources.ToolWindowTitle; this.BitmapResourceID = 301; this.BitmapIndex = 0; this.ToolBar = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.idToolbar); } protected override void Initialize() { base.Initialize(); OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (mcs != null) { // Get list command for the Feed combo CommandID sourcesListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSourcesList); mcs.AddCommand(new OleMenuCommand(SourcesList_Exec, sourcesListCommandID)); // invoke command for the Feed combo CommandID sourcesCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidSources); mcs.AddCommand(new OleMenuCommand(Sources_Exec, sourcesCommandID)); // get default project command CommandID projectsListCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjectsList); mcs.AddCommand(new OleMenuCommand(ProjectsList_Exec, projectsListCommandID)); // invoke command for the Default project combo CommandID projectsCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidProjects); mcs.AddCommand(new OleMenuCommand(Projects_Exec, projectsCommandID)); // clear console command CommandID clearHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidClearHost); mcs.AddCommand(new OleMenuCommand(ClearHost_Exec, clearHostCommandID)); // terminate command execution command CommandID stopHostCommandID = new CommandID(GuidList.guidNuGetCmdSet, PkgCmdIDList.cmdidStopHost); mcs.AddCommand(new OleMenuCommand(StopHost_Exec, stopHostCommandID)); } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We really don't want exceptions from the console to bring down VS")] public override void OnToolWindowCreated() { // Register key bindings to use in the editor var windowFrame = (IVsWindowFrame)Frame; Guid cmdUi = VSConstants.GUID_TextEditorFactory; windowFrame.SetGuidProperty((int)__VSFPROPID.VSFPROPID_InheritKeyBindings, ref cmdUi); // pause for a tiny moment to let the tool window open before initializing the host var timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(0); timer.Tick += (o, e) => { timer.Stop(); // all exceptions from the timer thread should be caught to avoid crashing VS try { LoadConsoleEditor(); } catch (Exception x) { // hide the text "initialize host" when an error occurs. ConsoleParentPane.NotifyInitializationCompleted(); ExceptionHelper.WriteToActivityLog(x); } }; timer.Start(); base.OnToolWindowCreated(); } protected override void OnClose() { base.OnClose(); if (_wpfConsole != null) { _wpfConsole.Dispose(); } } /// <summary> /// This override allows us to forward these messages to the editor instance as well /// </summary> /// <param name="m"></param> /// <returns></returns> protected override bool PreProcessMessage(ref System.Windows.Forms.Message m) { IVsWindowPane vsWindowPane = this.VsTextView as IVsWindowPane; if (vsWindowPane != null) { MSG[] pMsg = new MSG[1]; pMsg[0].hwnd = m.HWnd; pMsg[0].message = (uint)m.Msg; pMsg[0].wParam = m.WParam; pMsg[0].lParam = m.LParam; return vsWindowPane.TranslateAccelerator(pMsg) == 0; } return base.PreProcessMessage(ref m); } /// <summary> /// Override to forward to editor or handle accordingly if supported by this tool window. /// </summary> int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { // examine buttons within our toolbar if (pguidCmdGroup == GuidList.guidNuGetCmdSet) { bool isEnabled = IsToolbarEnabled; if (isEnabled) { bool isStopButton = (prgCmds[0].cmdID == 0x0600); // 0x0600 is the Command ID of the Stop button, defined in .vsct // when command is executing: enable stop button and disable the rest // when command is not executing: disable the stop button and enable the rest isEnabled = !isStopButton ^ WpfConsole.Dispatcher.IsExecutingCommand; } if (isEnabled) { prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED); } else { prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED); } return VSConstants.S_OK; } int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED; if (this.VsTextView != null) { IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView; hr = cmdTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED || hr == OleCommandFilter.OLECMDERR_E_UNKNOWNGROUP) { IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget; if (target != null) { hr = target.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } } return hr; } /// <summary> /// Override to forward to editor or handle accordingly if supported by this tool window. /// </summary> int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { int hr = OleCommandFilter.OLECMDERR_E_NOTSUPPORTED; if (this.VsTextView != null) { IOleCommandTarget cmdTarget = (IOleCommandTarget)VsTextView; hr = cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } if (hr == OleCommandFilter.OLECMDERR_E_NOTSUPPORTED || hr == OleCommandFilter.OLECMDERR_E_UNKNOWNGROUP) { IOleCommandTarget target = this.GetService(typeof(IOleCommandTarget)) as IOleCommandTarget; if (target != null) { hr = target.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } } return hr; } private void SourcesList_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null || args.OutValue == IntPtr.Zero) { throw new ArgumentException("Invalid argument", "e"); } Marshal.GetNativeVariantForObject(PowerConsoleWindow.PackageSources, args.OutValue); } } /// <summary> /// Called to retrieve current combo item name or to select a new item. /// </summary> private void Sources_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null && args.InValue is int) // Selected a feed { int index = (int)args.InValue; if (index >= 0 && index < PowerConsoleWindow.PackageSources.Length) { PowerConsoleWindow.ActivePackageSource = PowerConsoleWindow.PackageSources[index]; } } else if (args.OutValue != IntPtr.Zero) // Query selected feed name { string displayName = PowerConsoleWindow.ActivePackageSource ?? string.Empty; Marshal.GetNativeVariantForObject(displayName, args.OutValue); } } } private void ProjectsList_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null || args.OutValue == IntPtr.Zero) { throw new ArgumentException("Invalid argument", "e"); } // get project list here Marshal.GetNativeVariantForObject(PowerConsoleWindow.AvailableProjects, args.OutValue); } } /// <summary> /// Called to retrieve current combo item name or to select a new item. /// </summary> private void Projects_Exec(object sender, EventArgs e) { OleMenuCmdEventArgs args = e as OleMenuCmdEventArgs; if (args != null) { if (args.InValue != null && args.InValue is int) { // Selected a default projects int index = (int)args.InValue; if (index >= 0 && index < PowerConsoleWindow.AvailableProjects.Length) { PowerConsoleWindow.SetDefaultProjectIndex(index); } } else if (args.OutValue != IntPtr.Zero) { string displayName = PowerConsoleWindow.DefaultProject ?? string.Empty; Marshal.GetNativeVariantForObject(displayName, args.OutValue); } } } /// <summary> /// ClearHost command handler. /// </summary> private void ClearHost_Exec(object sender, EventArgs e) { if (WpfConsole != null) { WpfConsole.Dispatcher.ClearConsole(); } } private void StopHost_Exec(object sender, EventArgs e) { if (WpfConsole != null) { WpfConsole.Host.Abort(); } } private HostInfo ActiveHostInfo { get { return PowerConsoleWindow.ActiveHostInfo; } } private void LoadConsoleEditor() { if (WpfConsole != null) { // allow the console to start writing output WpfConsole.StartWritingOutput(); FrameworkElement consolePane = WpfConsole.Content as FrameworkElement; ConsoleParentPane.AddConsoleEditor(consolePane); // WPF doesn't handle input focus automatically in this scenario. We // have to set the focus manually, otherwise the editor is displayed but // not focused and not receiving keyboard inputs until clicked. if (consolePane != null) { PendingMoveFocus(consolePane); } } } /// <summary> /// Set pending focus to a console pane. At the time of setting active host, /// the pane (UIElement) is usually not loaded yet and can't receive focus. /// In this case, we need to set focus in its Loaded event. /// </summary> /// <param name="consolePane"></param> private void PendingMoveFocus(FrameworkElement consolePane) { if (consolePane.IsLoaded && consolePane.IsConnectedToPresentationSource()) { PendingFocusPane = null; MoveFocus(consolePane); } else { PendingFocusPane = consolePane; } } private FrameworkElement _pendingFocusPane; private FrameworkElement PendingFocusPane { get { return _pendingFocusPane; } set { if (_pendingFocusPane != null) { _pendingFocusPane.Loaded -= PendingFocusPane_Loaded; } _pendingFocusPane = value; if (_pendingFocusPane != null) { _pendingFocusPane.Loaded += PendingFocusPane_Loaded; } } } private void PendingFocusPane_Loaded(object sender, RoutedEventArgs e) { MoveFocus(PendingFocusPane); PendingFocusPane = null; } private void MoveFocus(FrameworkElement consolePane) { // TAB focus into editor (consolePane.Focus() does not work due to editor layouts) consolePane.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); // Try start the console session now. This needs to be after the console // pane getting focus to avoid incorrect initial editor layout. StartConsoleSession(consolePane); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We really don't want exceptions from the console to bring down VS")] private void StartConsoleSession(FrameworkElement consolePane) { if (WpfConsole != null && WpfConsole.Content == consolePane && WpfConsole.Host != null) { try { if (WpfConsole.Dispatcher.IsStartCompleted) { OnDispatcherStartCompleted(); // if the dispatcher was started before we reach here, // it means the dispatcher has been in read-only mode (due to _startedWritingOutput = false). // enable key input now. WpfConsole.Dispatcher.AcceptKeyInput(); } else { WpfConsole.Dispatcher.StartCompleted += (sender, args) => OnDispatcherStartCompleted(); WpfConsole.Dispatcher.StartWaitingKey += OnDispatcherStartWaitingKey; WpfConsole.Dispatcher.Start(); } } catch (Exception x) { // hide the text "initialize host" when an error occurs. ConsoleParentPane.NotifyInitializationCompleted(); WpfConsole.WriteLine(x.GetBaseException().ToString()); ExceptionHelper.WriteToActivityLog(x); } } else { ConsoleParentPane.NotifyInitializationCompleted(); } } private void OnDispatcherStartWaitingKey(object sender, EventArgs args) { WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey; // we want to hide the text "initialize host..." when waiting for key input ConsoleParentPane.NotifyInitializationCompleted(); } private void OnDispatcherStartCompleted() { WpfConsole.Dispatcher.StartWaitingKey -= OnDispatcherStartWaitingKey; ConsoleParentPane.NotifyInitializationCompleted(); // force the UI to update the toolbar VsUIShell.UpdateCommandUI(0 /* false = update UI asynchronously */); NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageManagerConsoleLoaded); } private IWpfConsole _wpfConsole; /// <summary> /// Get the WpfConsole of the active host. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private IWpfConsole WpfConsole { get { if (_wpfConsole == null) { Debug.Assert(ActiveHostInfo != null); try { _wpfConsole = ActiveHostInfo.WpfConsole; } catch (Exception x) { _wpfConsole = ActiveHostInfo.WpfConsole; _wpfConsole.Write(x.ToString()); } } return _wpfConsole; } } private IVsTextView _vsTextView; /// <summary> /// Get the VsTextView of current WpfConsole if exists. /// </summary> private IVsTextView VsTextView { get { if (_vsTextView == null && _wpfConsole != null) { _vsTextView = (IVsTextView)(WpfConsole.VsTextView); } return _vsTextView; } } private ConsoleContainer _consoleParentPane; /// <summary> /// Get the parent pane of console panes. This serves as the Content of this tool window. /// </summary> private ConsoleContainer ConsoleParentPane { get { if (_consoleParentPane == null) { _consoleParentPane = new ConsoleContainer(ProductUpdateService, PackageRestoreManager); } return _consoleParentPane; } } public override object Content { get { return this.ConsoleParentPane; } set { base.Content = value; } } #region IPowerConsoleService Region public event EventHandler ExecuteEnd; private ITextSnapshot _snapshot; private int _previousPosition; public bool Execute(string command, object[] inputs) { if (ConsoleStatus.IsBusy) { VSOutputConsole.WriteLine(Resources.PackageManagerConsoleBusy); throw new NotSupportedException(Resources.PackageManagerConsoleBusy); } if (!String.IsNullOrEmpty(command)) { WpfConsole.SetExecutionMode(true); // Cast the ToolWindowPane to PowerConsoleToolWindow // Access the IHost from PowerConsoleToolWindow as follows PowerConsoleToolWindow.WpfConsole.Host // Cast IHost to IAsyncHost // Also, register for IAsyncHost.ExecutedEnd and return only when the command is completed IPrivateWpfConsole powerShellConsole = (IPrivateWpfConsole)WpfConsole; IHost host = powerShellConsole.Host; var asynchost = host as IAsyncHost; if (asynchost != null) { asynchost.ExecuteEnd += PowerConsoleCommand_ExecuteEnd; } // Here, we store the snapshot of the powershell Console output text buffer // Snapshot has reference to the buffer and the current length of the buffer // And, upon execution of the command, (check the commandexecuted handler) // the changes to the buffer is identified and copied over to the VS output window if (powerShellConsole.InputLineStart != null && powerShellConsole.InputLineStart.Value.Snapshot != null) { _snapshot = powerShellConsole.InputLineStart.Value.Snapshot; } // We should write the command to the console just to imitate typical user action before executing it // Asserts get fired otherwise. Also, the log is displayed in a disorderly fashion powerShellConsole.WriteLine(command); return host.Execute(powerShellConsole, command, null); } return false; } private void PowerConsoleCommand_ExecuteEnd(object sender, EventArgs e) { // Flush the change in console text buffer onto the output window for testability // If the VSOutputConsole could not be obtained, just ignore if (VSOutputConsole != null && _snapshot != null) { if (_previousPosition < _snapshot.Length) { VSOutputConsole.WriteLine(_snapshot.GetText(_previousPosition, (_snapshot.Length - _previousPosition))); } _previousPosition = _snapshot.Length; } (sender as IAsyncHost).ExecuteEnd -= PowerConsoleCommand_ExecuteEnd; WpfConsole.SetExecutionMode(false); // This does NOT imply that the command succeeded. It just indicates that the console is ready for input now VSOutputConsole.WriteLine(Resources.PackageManagerConsoleCommandExecuted); ExecuteEnd.Raise(this, EventArgs.Empty); } private IConsole _vsOutputConsole = null; private IConsole VSOutputConsole { get { if (_vsOutputConsole == null) { IOutputConsoleProvider outputConsoleProvider = ServiceLocator.GetInstance<IOutputConsoleProvider>(); if (null != outputConsoleProvider) { _vsOutputConsole = outputConsoleProvider.CreateOutputConsole(requirePowerShellHost: false); } } return _vsOutputConsole; } } private IConsoleStatus _consoleStatus; private IConsoleStatus ConsoleStatus { get { if (_consoleStatus == null) { _consoleStatus = ServiceLocator.GetInstance<IConsoleStatus>(); Debug.Assert(_consoleStatus != null); } return _consoleStatus; } } #endregion } }
using System; using System.IO; using System.Collections.Generic; using log4net; // We have to include the following lib even when using dynamic, since it contains // the definition of the enums using HSVCDATALOADLib; using Command; using HFMCmd; using Utilities; namespace HFM { public enum EDataLoadUpdateMode { Merge = HSV_DATALOAD_DUPLICATE_OPTIONS.HSV_DATALOAD_MERGE, Replace = HSV_DATALOAD_DUPLICATE_OPTIONS.HSV_DATALOAD_REPLACE, Accumulate = HSV_DATALOAD_DUPLICATE_OPTIONS.HSV_DATALOAD_ACCUMULATE, ReplaceWithSecurity = HSV_DATALOAD_DUPLICATE_OPTIONS.HSV_DATALOAD_REPLACEWITHSECURITY } public enum EDataLoadMode { Load = HSV_DATALOAD_MODES.HSV_DATALOAD_LOAD, ScanOnly = HSV_DATALOAD_MODES.HSV_DATALOAD_SCAN } public enum EDataView { Periodic = HSV_DATA_VIEW.HSV_DATA_VIEW_PERIODIC, YTD = HSV_DATA_VIEW.HSV_DATA_VIEW_YTD, ScenarioDefault = HSV_DATA_VIEW.HSV_DATA_VIEW_SCENARIO } public class DataLoad { /// <summary> /// Collection class holding options that can be specified when loading /// data. /// </summary> [Setting("AccumulateWithinFile", "If set, then multiple data values for the same cell " + "accumulate, rather than overwriting one another", InternalName = "Accumulate within file"), Setting("AppendToLog", "If true, any existing log file is appended to, instead of overwritten", InternalName = "Append to Log File"), Setting("ContainsShares", "Indicates whether the data file contains shares data, " + "such as Shares Outstanding, Voting Outstanding, or Owned", InternalName = "Does the file contain shares data"), Setting("ContainsSubmissionPhase", "Indicates whether the data file contains data for " + "phased submissions", InternalName = "Does the file contain submission phase data"), Setting("Delimiter", "Data file delimiter", ParameterType = typeof(string)), // TODO: Validation list Setting("DecimalChar", "The decimal character used within the data file", ParameterType = typeof(string)), Setting("ThousandsChar", "The thousands separator character used within the data file", ParameterType = typeof(string)), Setting("UpdateMode", "Specifies how data loads affect existing data values", InternalName = "Duplicates", ParameterType = typeof(EDataLoadUpdateMode), DefaultValue = EDataLoadUpdateMode.Merge), Setting("Mode", "Specifies how the data load should be processed. ScanOnly checks data files " + "for syntax errors, but does not load them.", ParameterType = typeof(EDataLoadMode), DefaultValue = EDataLoadMode.Load)] public class LoadOptions : LoadExtractOptions { [Factory] public LoadOptions(DataLoad dl) : base(typeof(IHsvLoadExtractOptions), typeof(IHsvLoadExtractOption), typeof(HSV_DATALOAD_OPTION), (IHsvLoadExtractOptions)dl.HsvcDataLoad.LoadOptions) { } } /// <summary> /// Collection class holding options that can be specified when extracting /// data. /// </summary> [Setting("AppendToLog", "If true, any existing log file is appended to, instead of overwritten", InternalName = "Append to Log File"), Setting("Delimiter", "File delimiter used in data extract file", ParameterType = typeof(string)), // TODO: Validation list Setting("IncludeCalculatedData", "If true, the data extract includes calculated data", InternalName = "Extract Calculated"), Setting("IncludePhasedGroups", "If true, includes phased groups in data extract", InternalName = "Extract Phased Groups"), Setting("View", "The view of data to extract", ParameterType = typeof(EDataView))] public class ExtractOptions : LoadExtractOptions { [Factory] public ExtractOptions(DataLoad dl) : base(typeof(IHsvLoadExtractOptions), typeof(IHsvLoadExtractOption), typeof(HSV_DATAEXTRACT_OPTION), (IHsvLoadExtractOptions)dl.HsvcDataLoad.ExtractOptions) { } } // Reference to class logger protected static readonly ILog _log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Reference to HFM HsvcDataLoad object #if LATE_BIND internal readonly dynamic HsvcDataLoad; #else internal readonly HsvcDataLoad HsvcDataLoad; #endif [Factory] public DataLoad(Session session) { _log.Trace("Constructing DataLoad object"); #if LATE_BIND HsvcDataLoad = HFM.CreateObject("Hyperion.HsvcDataLoad"); #else HsvcDataLoad = new HsvcDataLoad(); #endif HsvcDataLoad.SetSession(session.HsvSession); } [Command("Loads data to an HFM application from a text file")] public void LoadData( [Parameter("Path to the source data file(s). To load multiple files from the same " + "source directory, use wildcards in the file name", Alias = "DataFile")] string dataFiles, [Parameter("Path to the folder in which to create log files; if not specified, " + "defaults to same folder as the source data file. Log files have the " + "same file name (but with a .log extension) as the file from which " + "the data is loaded", DefaultValue = null)] string logDir, LoadOptions options, SystemInfo si, IOutput output) { object oErrors = null; bool didError = false; string logFile; var paths = FileUtilities.GetMatchingFiles(dataFiles); _log.InfoFormat("Found {0} data files to process", paths.Count); output.InitProgress("Data Load", paths.Count); foreach(var dataFile in paths) { if(logDir == null || logDir == "") { logFile = Path.ChangeExtension(dataFile, ".log"); } else { logFile = Path.Combine(logDir, Path.ChangeExtension( Path.GetFileName(dataFile), ".log")); } // Ensure data file exists and logFile is writeable FileUtilities.EnsureFileExists(dataFile); FileUtilities.EnsureFileWriteable(logFile); _log.InfoFormat("Loading data from {0}", dataFile); HFM.Try("Loading data", () => { si.MonitorBlockingTask(output); oErrors = HsvcDataLoad.Load2(dataFile, logFile); si.BlockingTaskComplete(); }); if((bool)oErrors) { _log.WarnFormat("Data load resulted in errors; check log file {0} for details", Path.GetFileName(logFile)); // TODO: Should we show the warnings here? didError = true; } else { _log.Info("Data load completed successfully"); } } output.EndProgress(); if(didError) { throw new HFMException("One or more errors occurred while loading data"); } } [Command("Extracts data from an HFM application to a text file")] public void ExtractData( [Parameter("Path to the generated data extract file")] string dataFile, [Parameter("Path to the extract log file; if not specified, defaults to same path " + "and name as extract file.", DefaultValue = null)] string logFile, [Parameter("The scenario to include in the extract")] string scenario, [Parameter("The year to include in the extract")] string year, [Parameter("The period(s) to include in the extract", Alias = "Period")] IEnumerable<string> periods, [Parameter("The entities to include in the extract", Alias = "Entity")] IEnumerable<string> entities, [Parameter("The accounts to include in the extract", Alias = "Account")] IEnumerable<string> accounts, ExtractOptions options, Metadata metadata) { options["Scenario"] = metadata["Scenario"].GetId(scenario); options["Year"] = metadata["Year"].GetId(year); var entityList = metadata["Entity"].GetMembers(entities); options["Entity Subset"] = entityList.MemberIds; options["Parent Subset"] = entityList.ParentIds; options["Period Subset"] = metadata["Period"].GetMembers(periods).MemberIds; options["Account Subset"] = metadata["Account"].GetMembers(accounts).MemberIds; if(logFile == null || logFile == "") { logFile = Path.ChangeExtension(dataFile, ".log"); } // Ensure dataFile and logFile are writeable locations FileUtilities.EnsureFileWriteable(dataFile); FileUtilities.EnsureFileWriteable(logFile); HFM.Try("Extracting data", () => HsvcDataLoad.Extract(dataFile, logFile)); } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// A VM crashdump /// First published in XenServer 4.0. /// </summary> public partial class Crashdump : XenObject<Crashdump> { #region Constructors public Crashdump() { } public Crashdump(string uuid, XenRef<VM> VM, XenRef<VDI> VDI, Dictionary<string, string> other_config) { this.uuid = uuid; this.VM = VM; this.VDI = VDI; this.other_config = other_config; } /// <summary> /// Creates a new Crashdump from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Crashdump(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Crashdump from a Proxy_Crashdump. /// </summary> /// <param name="proxy"></param> public Crashdump(Proxy_Crashdump proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Crashdump. /// </summary> public override void UpdateFrom(Crashdump record) { uuid = record.uuid; VM = record.VM; VDI = record.VDI; other_config = record.other_config; } internal void UpdateFrom(Proxy_Crashdump proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM); VDI = proxy.VDI == null ? null : XenRef<VDI>.Create(proxy.VDI); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Crashdump /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("VM")) VM = Marshalling.ParseRef<VM>(table, "VM"); if (table.ContainsKey("VDI")) VDI = Marshalling.ParseRef<VDI>(table, "VDI"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public Proxy_Crashdump ToProxy() { Proxy_Crashdump result_ = new Proxy_Crashdump(); result_.uuid = uuid ?? ""; result_.VM = VM ?? ""; result_.VDI = VDI ?? ""; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } public bool DeepEquals(Crashdump other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._VM, other._VM) && Helper.AreEqual2(this._VDI, other._VDI) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Crashdump server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { Crashdump.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given crashdump. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> [Deprecated("XenServer 7.3")] public static Crashdump get_record(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_record(session.opaque_ref, _crashdump); else return new Crashdump(session.XmlRpcProxy.crashdump_get_record(session.opaque_ref, _crashdump ?? "").parse()); } /// <summary> /// Get a reference to the crashdump instance with the specified UUID. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> [Deprecated("XenServer 7.3")] public static XenRef<Crashdump> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Crashdump>.Create(session.XmlRpcProxy.crashdump_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given crashdump. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static string get_uuid(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_uuid(session.opaque_ref, _crashdump); else return session.XmlRpcProxy.crashdump_get_uuid(session.opaque_ref, _crashdump ?? "").parse(); } /// <summary> /// Get the VM field of the given crashdump. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static XenRef<VM> get_VM(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_vm(session.opaque_ref, _crashdump); else return XenRef<VM>.Create(session.XmlRpcProxy.crashdump_get_vm(session.opaque_ref, _crashdump ?? "").parse()); } /// <summary> /// Get the VDI field of the given crashdump. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static XenRef<VDI> get_VDI(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_vdi(session.opaque_ref, _crashdump); else return XenRef<VDI>.Create(session.XmlRpcProxy.crashdump_get_vdi(session.opaque_ref, _crashdump ?? "").parse()); } /// <summary> /// Get the other_config field of the given crashdump. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static Dictionary<string, string> get_other_config(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_other_config(session.opaque_ref, _crashdump); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.crashdump_get_other_config(session.opaque_ref, _crashdump ?? "").parse()); } /// <summary> /// Set the other_config field of the given crashdump. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _crashdump, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.crashdump_set_other_config(session.opaque_ref, _crashdump, _other_config); else session.XmlRpcProxy.crashdump_set_other_config(session.opaque_ref, _crashdump ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given crashdump. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _crashdump, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.crashdump_add_to_other_config(session.opaque_ref, _crashdump, _key, _value); else session.XmlRpcProxy.crashdump_add_to_other_config(session.opaque_ref, _crashdump ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given crashdump. If the key is not in that Map, then do nothing. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _crashdump, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.crashdump_remove_from_other_config(session.opaque_ref, _crashdump, _key); else session.XmlRpcProxy.crashdump_remove_from_other_config(session.opaque_ref, _crashdump ?? "", _key ?? "").parse(); } /// <summary> /// Destroy the specified crashdump /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static void destroy(Session session, string _crashdump) { if (session.JsonRpcClient != null) session.JsonRpcClient.crashdump_destroy(session.opaque_ref, _crashdump); else session.XmlRpcProxy.crashdump_destroy(session.opaque_ref, _crashdump ?? "").parse(); } /// <summary> /// Destroy the specified crashdump /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_crashdump">The opaque_ref of the given crashdump</param> public static XenRef<Task> async_destroy(Session session, string _crashdump) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_crashdump_destroy(session.opaque_ref, _crashdump); else return XenRef<Task>.Create(session.XmlRpcProxy.async_crashdump_destroy(session.opaque_ref, _crashdump ?? "").parse()); } /// <summary> /// Return a list of all the crashdumps known to the system. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.3. /// </summary> /// <param name="session">The session</param> [Deprecated("XenServer 7.3")] public static List<XenRef<Crashdump>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_all(session.opaque_ref); else return XenRef<Crashdump>.Create(session.XmlRpcProxy.crashdump_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the crashdump Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Crashdump>, Crashdump> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.crashdump_get_all_records(session.opaque_ref); else return XenRef<Crashdump>.Create<Proxy_Crashdump>(session.XmlRpcProxy.crashdump_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// the virtual machine /// </summary> [JsonConverter(typeof(XenRefConverter<VM>))] public virtual XenRef<VM> VM { get { return _VM; } set { if (!Helper.AreEqual(value, _VM)) { _VM = value; NotifyPropertyChanged("VM"); } } } private XenRef<VM> _VM = new XenRef<VM>(Helper.NullOpaqueRef); /// <summary> /// the virtual disk /// </summary> [JsonConverter(typeof(XenRefConverter<VDI>))] public virtual XenRef<VDI> VDI { get { return _VDI; } set { if (!Helper.AreEqual(value, _VDI)) { _VDI = value; NotifyPropertyChanged("VDI"); } } } private XenRef<VDI> _VDI = new XenRef<VDI>(Helper.NullOpaqueRef); /// <summary> /// additional configuration /// First published in XenServer 4.1. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class FastList<T> { /// <summary> /// Comparison function should return -1 if left is less than right, 1 if left is greater than right, and 0 if they match. /// </summary> public delegate int CompareFunc(T left, T right); public T[] array = null; public int size = 0; public FastList () { } public FastList(int size) { if (size > 0) { this.size = 0; array = new T[size]; } else { this.size = 0; } } public int Count { get { return size;} set { } } public T this[int i] { get { return array[i];} set { array[i] = value;} } //Add item to end of list. public void Add(T item) { if (array == null || size == array.Length) { Allocate(); } array[size] = item; size++; } //Add item to end of list if it is unique. public void AddUnique( T item ) { if ( array == null || size == array.Length ) { Allocate(); } if ( !Contains( item ) ) { array[size] = item; size++; } } //Add items to the end of the list public void AddRange( IEnumerable<T> items ) { foreach ( T item in items ) { Add( item ); } } //Insert item at specified index public void Insert(int index, T item) { if (array == null || size == array.Length) { Allocate(); } if (index < size) { //move things back 1 for (int i = size; i > index; i--) { array[i] = array[i-1]; } array[index] = item; size++; } else Add(item); } //Removes specified item and keeps everything else in order public bool Remove(T item) { if (array != null) { for (int i = 0; i < size; i++) { if (item.Equals(array[i])) { //found it, push everything up size--; for (int j = i; j < size; j++) { array[j] = array[j+1]; } array[size] = default(T); return true; } } } return false; } //Removes item at specified index while keeping everything else in order //O(n) public void RemoveAt(int index) { if (array != null && size > 0 && index < size) { size--; for (int i = index; i < size; i++) { array[i] = array[i+1]; } array[size] = default(T); } } //Removes the specified item from the list and replaces with last item. Return true if removed, false if not found. public bool RemoveFast(T item) { if (array != null) { for (int i = 0; i < size; i++) { if ( item.Equals( array[i] )) { //found //Move last item here if (i < (size - 1)) { T lastItem = array[size-1]; array[size-1] = default(T); array[i] = lastItem; } else { array[i] = default(T); } size--; return true; } } } return false; } //Removes item at specified index and replace with last item. public void RemoveAtFast(int index) { if (array != null && index < size && index >= 0) { //last element if (index == size - 1) { array[index] = default(T); } else { T lastItem = array[size - 1]; array[index] = lastItem; array[size - 1] = default(T); } size--; } } //Return whether an item is contained within the list //O(n) public bool Contains(T item) { if (array == null || size <= 0 ) return false; for (int i = 0; i < size; i++) { if (array[i].Equals(item)) { return true;} } return false; } //Returns index of specified item, or -1 if not found. //O(n) public int IndexOf(T item) { if (size <= 0 || array == null) { return -1;} for (int i = 0; i < size; i++) { if (item.Equals(array[i])) { return i;} } return -1; } public T Pop() { if (array != null && size > 0) { T lastItem = array[size-1]; array[size-1] = default(T); size--; return lastItem; } return default(T); } public T[] ToArray() { Trim(); return array; } public void Sort (CompareFunc comparer) { int start = 0; int end = size - 1; bool changed = true; while (changed) { changed = false; for (int i = start; i < end; i++) { if (comparer(array[i], array[i + 1]) > 0) { T temp = array[i]; array[i] = array[i+1]; array[i+1] = temp; changed = true; } else if (!changed) { start = (i==0) ? 0 : i-1; } } } } public void InsertionSort(CompareFunc comparer) { for (int i = 1; i < size; i++) { T curr = array[i]; int j = i; while (j > 0 && comparer(array[j - 1], curr) > 0) { array[j] = array[j-1]; j--; } array[j] = curr; } } public IEnumerator<T> GetEnumerator() { if (array != null) { for (int i = 0; i < size; i++) { yield return array[i]; } } } public T Find(Predicate<T> match) { if (match != null) { if (array != null) { for (int i = 0; i < size; i++) { if (match(array[i])) { return array[i];} } } } return default(T); } //Allocate more space to internal array. void Allocate() { T[] newArray; if (array == null) { newArray = new T[32]; } else { newArray = new T[Mathf.Max(array.Length << 1, 32)]; } if (array != null && size > 0) { array.CopyTo(newArray, 0); } array = newArray; } void Trim() { if (size > 0) { T[] newArray = new T[size]; for (int i = 0; i < size; i++) { newArray[i] = array[i]; } array = newArray; } else { array = null; } } //Set size to 0, does not delete array from memory public void Clear() { size = 0; } //Delete array from memory public void Release() { Clear(); array = null; } }
//--------------------------------------------------------------------------- // // File: HtmlSchema.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Static information about HTML structure // //--------------------------------------------------------------------------- namespace ManagementGui.View.Control.XamlToHtmlParser { using System.Diagnostics; using System.Collections; /// <summary> /// HtmlSchema class /// maintains static information about HTML structure /// can be used by HtmlParser to check conditions under which an element starts or ends, etc. /// </summary> internal class HtmlSchema { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// static constructor, initializes the ArrayLists /// that hold the elements in various sub-components of the schema /// e.g _htmlEmptyElements, etc. /// </summary> static HtmlSchema() { // initializes the list of all html elements InitializeInlineElements(); InitializeBlockElements(); InitializeOtherOpenableElements(); // initialize empty elements list InitializeEmptyElements(); // initialize list of elements closing on the outer element end InitializeElementsClosingOnParentElementEnd(); // initalize list of elements that close when a new element starts InitializeElementsClosingOnNewElementStart(); // Initialize character entities InitializeHtmlCharacterEntities(); } #endregion Constructors; // --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// returns true when xmlElementName corresponds to empty element /// </summary> /// <param name="xmlElementName"> /// string representing name to test /// </param> internal static bool IsEmptyElement(string xmlElementName) { // convert to lowercase before we check // because element names are not case sensitive return _htmlEmptyElements.Contains(xmlElementName.ToLower()); } /// <summary> /// returns true if xmlElementName represents a block formattinng element. /// It used in an algorithm of transferring inline elements over block elements /// in HtmlParser /// </summary> /// <param name="xmlElementName"></param> /// <returns></returns> internal static bool IsBlockElement(string xmlElementName) { return _htmlBlockElements.Contains(xmlElementName); } /// <summary> /// returns true if the xmlElementName represents an inline formatting element /// </summary> /// <param name="xmlElementName"></param> /// <returns></returns> internal static bool IsInlineElement(string xmlElementName) { return _htmlInlineElements.Contains(xmlElementName); } /// <summary> /// It is a list of known html elements which we /// want to allow to produce bt HTML parser, /// but don'tt want to act as inline, block or no-scope. /// Presence in this list will allow to open /// elements during html parsing, and adding the /// to a tree produced by html parser. /// </summary> internal static bool IsKnownOpenableElement(string xmlElementName) { return _htmlOtherOpenableElements.Contains(xmlElementName); } /// <summary> /// returns true when xmlElementName closes when the outer element closes /// this is true of elements with optional start tags /// </summary> /// <param name="xmlElementName"> /// string representing name to test /// </param> internal static bool ClosesOnParentElementEnd(string xmlElementName) { // convert to lowercase when testing return _htmlElementsClosingOnParentElementEnd.Contains(xmlElementName.ToLower()); } /// <summary> /// returns true if the current element closes when the new element, whose name has just been read, starts /// </summary> /// <param name="currentElementName"> /// string representing current element name /// </param> /// <param name="elementName"></param> /// string representing name of the next element that will start internal static bool ClosesOnNextElementStart(string currentElementName, string nextElementName) { Debug.Assert(currentElementName == currentElementName.ToLower()); switch (currentElementName) { case "colgroup": return _htmlElementsClosingColgroup.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "dd": return _htmlElementsClosingDD.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "dt": return _htmlElementsClosingDT.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "li": return _htmlElementsClosingLI.Contains(nextElementName); case "p": return HtmlSchema.IsBlockElement(nextElementName); case "tbody": return _htmlElementsClosingTbody.Contains(nextElementName); case "tfoot": return _htmlElementsClosingTfoot.Contains(nextElementName); case "thead": return _htmlElementsClosingThead.Contains(nextElementName); case "tr": return _htmlElementsClosingTR.Contains(nextElementName); case "td": return _htmlElementsClosingTD.Contains(nextElementName); case "th": return _htmlElementsClosingTH.Contains(nextElementName); } return false; } /// <summary> /// returns true if the string passed as argument is an Html entity name /// </summary> /// <param name="entityName"> /// string to be tested for Html entity name /// </param> internal static bool IsEntity(string entityName) { // we do not convert entity strings to lowercase because these names are case-sensitive if (_htmlCharacterEntities.Contains(entityName)) { return true; } else { return false; } } /// <summary> /// returns the character represented by the entity name string which is passed as an argument, if the string is an entity name /// as specified in _htmlCharacterEntities, returns the character value of 0 otherwise /// </summary> /// <param name="entityName"> /// string representing entity name whose character value is desired /// </param> internal static char EntityCharacterValue(string entityName) { if (_htmlCharacterEntities.Contains(entityName)) { return (char) _htmlCharacterEntities[entityName]; } else { return (char)0; } } #endregion Internal Methods // --------------------------------------------------------------------- // // Internal Properties // // --------------------------------------------------------------------- #region Internal Properties #endregion Internal Indexers // --------------------------------------------------------------------- // // Private Methods // // --------------------------------------------------------------------- #region Private Methods private static void InitializeInlineElements() { _htmlInlineElements = new ArrayList(); _htmlInlineElements.Add("a"); _htmlInlineElements.Add("abbr"); _htmlInlineElements.Add("acronym"); _htmlInlineElements.Add("address"); _htmlInlineElements.Add("b"); _htmlInlineElements.Add("bdo"); // ??? _htmlInlineElements.Add("big"); _htmlInlineElements.Add("button"); _htmlInlineElements.Add("code"); _htmlInlineElements.Add("del"); // deleted text _htmlInlineElements.Add("dfn"); _htmlInlineElements.Add("em"); _htmlInlineElements.Add("font"); _htmlInlineElements.Add("i"); _htmlInlineElements.Add("ins"); // inserted text _htmlInlineElements.Add("kbd"); // text to entered by a User _htmlInlineElements.Add("label"); _htmlInlineElements.Add("legend"); // ??? _htmlInlineElements.Add("q"); // short inline quotation _htmlInlineElements.Add("s"); // strike-through text style _htmlInlineElements.Add("samp"); // Specifies a code sample _htmlInlineElements.Add("small"); _htmlInlineElements.Add("span"); _htmlInlineElements.Add("strike"); _htmlInlineElements.Add("strong"); _htmlInlineElements.Add("sub"); _htmlInlineElements.Add("sup"); _htmlInlineElements.Add("u"); _htmlInlineElements.Add("var"); // indicates an instance of a program variable } private static void InitializeBlockElements() { _htmlBlockElements = new ArrayList(); _htmlBlockElements.Add("blockquote"); _htmlBlockElements.Add("body"); _htmlBlockElements.Add("caption"); _htmlBlockElements.Add("center"); _htmlBlockElements.Add("cite"); _htmlBlockElements.Add("dd"); _htmlBlockElements.Add("dir"); // treat as UL element _htmlBlockElements.Add("div"); _htmlBlockElements.Add("dl"); _htmlBlockElements.Add("dt"); _htmlBlockElements.Add("form"); // Not a block according to XHTML spec _htmlBlockElements.Add("h1"); _htmlBlockElements.Add("h2"); _htmlBlockElements.Add("h3"); _htmlBlockElements.Add("h4"); _htmlBlockElements.Add("h5"); _htmlBlockElements.Add("h6"); _htmlBlockElements.Add("html"); _htmlBlockElements.Add("li"); _htmlBlockElements.Add("menu"); // treat as UL element _htmlBlockElements.Add("ol"); _htmlBlockElements.Add("p"); _htmlBlockElements.Add("pre"); // Renders text in a fixed-width font _htmlBlockElements.Add("table"); _htmlBlockElements.Add("tbody"); _htmlBlockElements.Add("td"); _htmlBlockElements.Add("textarea"); _htmlBlockElements.Add("tfoot"); _htmlBlockElements.Add("th"); _htmlBlockElements.Add("thead"); _htmlBlockElements.Add("tr"); _htmlBlockElements.Add("tt"); _htmlBlockElements.Add("ul"); } /// <summary> /// initializes _htmlEmptyElements with empty elements in HTML 4 spec at /// http://www.w3.org/TR/REC-html40/index/elements.html /// </summary> private static void InitializeEmptyElements() { // Build a list of empty (no-scope) elements // (element not requiring closing tags, and not accepting any content) _htmlEmptyElements = new ArrayList(); _htmlEmptyElements.Add("area"); _htmlEmptyElements.Add("base"); _htmlEmptyElements.Add("basefont"); _htmlEmptyElements.Add("br"); _htmlEmptyElements.Add("col"); _htmlEmptyElements.Add("frame"); _htmlEmptyElements.Add("hr"); _htmlEmptyElements.Add("img"); _htmlEmptyElements.Add("input"); _htmlEmptyElements.Add("isindex"); _htmlEmptyElements.Add("link"); _htmlEmptyElements.Add("meta"); _htmlEmptyElements.Add("param"); } private static void InitializeOtherOpenableElements() { // It is a list of known html elements which we // want to allow to produce bt HTML parser, // but don'tt want to act as inline, block or no-scope. // Presence in this list will allow to open // elements during html parsing, and adding the // to a tree produced by html parser. _htmlOtherOpenableElements = new ArrayList(); _htmlOtherOpenableElements.Add("applet"); _htmlOtherOpenableElements.Add("base"); _htmlOtherOpenableElements.Add("basefont"); _htmlOtherOpenableElements.Add("colgroup"); _htmlOtherOpenableElements.Add("fieldset"); //_htmlOtherOpenableElements.Add("form"); --> treated as block _htmlOtherOpenableElements.Add("frameset"); _htmlOtherOpenableElements.Add("head"); _htmlOtherOpenableElements.Add("iframe"); _htmlOtherOpenableElements.Add("map"); _htmlOtherOpenableElements.Add("noframes"); _htmlOtherOpenableElements.Add("noscript"); _htmlOtherOpenableElements.Add("object"); _htmlOtherOpenableElements.Add("optgroup"); _htmlOtherOpenableElements.Add("option"); _htmlOtherOpenableElements.Add("script"); _htmlOtherOpenableElements.Add("select"); _htmlOtherOpenableElements.Add("style"); _htmlOtherOpenableElements.Add("title"); } /// <summary> /// initializes _htmlElementsClosingOnParentElementEnd with the list of HTML 4 elements for which closing tags are optional /// we assume that for any element for which closing tags are optional, the element closes when it's outer element /// (in which it is nested) does /// </summary> private static void InitializeElementsClosingOnParentElementEnd() { _htmlElementsClosingOnParentElementEnd = new ArrayList(); _htmlElementsClosingOnParentElementEnd.Add("body"); _htmlElementsClosingOnParentElementEnd.Add("colgroup"); _htmlElementsClosingOnParentElementEnd.Add("dd"); _htmlElementsClosingOnParentElementEnd.Add("dt"); _htmlElementsClosingOnParentElementEnd.Add("head"); _htmlElementsClosingOnParentElementEnd.Add("html"); _htmlElementsClosingOnParentElementEnd.Add("li"); _htmlElementsClosingOnParentElementEnd.Add("p"); _htmlElementsClosingOnParentElementEnd.Add("tbody"); _htmlElementsClosingOnParentElementEnd.Add("td"); _htmlElementsClosingOnParentElementEnd.Add("tfoot"); _htmlElementsClosingOnParentElementEnd.Add("thead"); _htmlElementsClosingOnParentElementEnd.Add("th"); _htmlElementsClosingOnParentElementEnd.Add("tr"); } private static void InitializeElementsClosingOnNewElementStart() { _htmlElementsClosingColgroup = new ArrayList(); _htmlElementsClosingColgroup.Add("colgroup"); _htmlElementsClosingColgroup.Add("tr"); _htmlElementsClosingColgroup.Add("thead"); _htmlElementsClosingColgroup.Add("tfoot"); _htmlElementsClosingColgroup.Add("tbody"); _htmlElementsClosingDD = new ArrayList(); _htmlElementsClosingDD.Add("dd"); _htmlElementsClosingDD.Add("dt"); // TODO: dd may end in other cases as well - if a new "p" starts, etc. // TODO: these are the basic "legal" cases but there may be more recovery _htmlElementsClosingDT = new ArrayList(); _htmlElementsClosingDD.Add("dd"); _htmlElementsClosingDD.Add("dt"); // TODO: dd may end in other cases as well - if a new "p" starts, etc. // TODO: these are the basic "legal" cases but there may be more recovery _htmlElementsClosingLI = new ArrayList(); _htmlElementsClosingLI.Add("li"); // TODO: more complex recovery _htmlElementsClosingTbody = new ArrayList(); _htmlElementsClosingTbody.Add("tbody"); _htmlElementsClosingTbody.Add("thead"); _htmlElementsClosingTbody.Add("tfoot"); // TODO: more complex recovery _htmlElementsClosingTR = new ArrayList(); // NOTE: tr should not really close on a new thead // because if there are rows before a thead, it is assumed to be in tbody, whose start tag is optional // and thead can't come after tbody // however, if we do encounter this, it's probably best to end the row and ignore the thead or treat // it as part of the table _htmlElementsClosingTR.Add("thead"); _htmlElementsClosingTR.Add("tfoot"); _htmlElementsClosingTR.Add("tbody"); _htmlElementsClosingTR.Add("tr"); // TODO: more complex recovery _htmlElementsClosingTD = new ArrayList(); _htmlElementsClosingTD.Add("td"); _htmlElementsClosingTD.Add("th"); _htmlElementsClosingTD.Add("tr"); _htmlElementsClosingTD.Add("tbody"); _htmlElementsClosingTD.Add("tfoot"); _htmlElementsClosingTD.Add("thead"); // TODO: more complex recovery _htmlElementsClosingTH = new ArrayList(); _htmlElementsClosingTH.Add("td"); _htmlElementsClosingTH.Add("th"); _htmlElementsClosingTH.Add("tr"); _htmlElementsClosingTH.Add("tbody"); _htmlElementsClosingTH.Add("tfoot"); _htmlElementsClosingTH.Add("thead"); // TODO: more complex recovery _htmlElementsClosingThead = new ArrayList(); _htmlElementsClosingThead.Add("tbody"); _htmlElementsClosingThead.Add("tfoot"); // TODO: more complex recovery _htmlElementsClosingTfoot = new ArrayList(); _htmlElementsClosingTfoot.Add("tbody"); // although thead comes before tfoot, we add it because if it is found the tfoot should close // and some recovery processing be done on the thead _htmlElementsClosingTfoot.Add("thead"); // TODO: more complex recovery } /// <summary> /// initializes _htmlCharacterEntities hashtable with the character corresponding to entity names /// </summary> private static void InitializeHtmlCharacterEntities() { _htmlCharacterEntities = new Hashtable(); _htmlCharacterEntities["Aacute"] = (char)193; _htmlCharacterEntities["aacute"] = (char)225; _htmlCharacterEntities["Acirc"] = (char)194; _htmlCharacterEntities["acirc"] = (char)226; _htmlCharacterEntities["acute"] = (char)180; _htmlCharacterEntities["AElig"] = (char)198; _htmlCharacterEntities["aelig"] = (char)230; _htmlCharacterEntities["Agrave"] = (char)192; _htmlCharacterEntities["agrave"] = (char)224; _htmlCharacterEntities["alefsym"] = (char)8501; _htmlCharacterEntities["Alpha"] = (char)913; _htmlCharacterEntities["alpha"] = (char)945; _htmlCharacterEntities["amp"] = (char)38; _htmlCharacterEntities["and"] = (char)8743; _htmlCharacterEntities["ang"] = (char)8736; _htmlCharacterEntities["Aring"] = (char)197; _htmlCharacterEntities["aring"] = (char)229; _htmlCharacterEntities["asymp"] = (char)8776; _htmlCharacterEntities["Atilde"] = (char)195; _htmlCharacterEntities["atilde"] = (char)227; _htmlCharacterEntities["Auml"] = (char)196; _htmlCharacterEntities["auml"] = (char)228; _htmlCharacterEntities["bdquo"] = (char)8222; _htmlCharacterEntities["Beta"] = (char)914; _htmlCharacterEntities["beta"] = (char)946; _htmlCharacterEntities["brvbar"] = (char)166; _htmlCharacterEntities["bull"] = (char)8226; _htmlCharacterEntities["cap"] = (char)8745; _htmlCharacterEntities["Ccedil"] = (char)199; _htmlCharacterEntities["ccedil"] = (char)231; _htmlCharacterEntities["cent"] = (char)162; _htmlCharacterEntities["Chi"] = (char)935; _htmlCharacterEntities["chi"] = (char)967; _htmlCharacterEntities["circ"] = (char)710; _htmlCharacterEntities["clubs"] = (char)9827; _htmlCharacterEntities["cong"] = (char)8773; _htmlCharacterEntities["copy"] = (char)169; _htmlCharacterEntities["crarr"] = (char)8629; _htmlCharacterEntities["cup"] = (char)8746; _htmlCharacterEntities["curren"] = (char)164; _htmlCharacterEntities["dagger"] = (char)8224; _htmlCharacterEntities["Dagger"] = (char)8225; _htmlCharacterEntities["darr"] = (char)8595; _htmlCharacterEntities["dArr"] = (char)8659; _htmlCharacterEntities["deg"] = (char)176; _htmlCharacterEntities["Delta"] = (char)916; _htmlCharacterEntities["delta"] = (char)948; _htmlCharacterEntities["diams"] = (char)9830; _htmlCharacterEntities["divide"] = (char)247; _htmlCharacterEntities["Eacute"] = (char)201; _htmlCharacterEntities["eacute"] = (char)233; _htmlCharacterEntities["Ecirc"] = (char)202; _htmlCharacterEntities["ecirc"] = (char)234; _htmlCharacterEntities["Egrave"] = (char)200; _htmlCharacterEntities["egrave"] = (char)232; _htmlCharacterEntities["empty"] = (char)8709; _htmlCharacterEntities["emsp"] = (char)8195; _htmlCharacterEntities["ensp"] = (char)8194; _htmlCharacterEntities["Epsilon"] = (char)917; _htmlCharacterEntities["epsilon"] = (char)949; _htmlCharacterEntities["equiv"] = (char)8801; _htmlCharacterEntities["Eta"] = (char)919; _htmlCharacterEntities["eta"] = (char)951; _htmlCharacterEntities["ETH"] = (char)208; _htmlCharacterEntities["eth"] = (char)240; _htmlCharacterEntities["Euml"] = (char)203; _htmlCharacterEntities["euml"] = (char)235; _htmlCharacterEntities["euro"] = (char)8364; _htmlCharacterEntities["exist"] = (char)8707; _htmlCharacterEntities["fnof"] = (char)402; _htmlCharacterEntities["forall"] = (char)8704; _htmlCharacterEntities["frac12"] = (char)189; _htmlCharacterEntities["frac14"] = (char)188; _htmlCharacterEntities["frac34"] = (char)190; _htmlCharacterEntities["frasl"] = (char)8260; _htmlCharacterEntities["Gamma"] = (char)915; _htmlCharacterEntities["gamma"] = (char)947; _htmlCharacterEntities["ge"] = (char)8805; _htmlCharacterEntities["gt"] = (char)62; _htmlCharacterEntities["harr"] = (char)8596; _htmlCharacterEntities["hArr"] = (char)8660; _htmlCharacterEntities["hearts"] = (char)9829; _htmlCharacterEntities["hellip"] = (char)8230; _htmlCharacterEntities["Iacute"] = (char)205; _htmlCharacterEntities["iacute"] = (char)237; _htmlCharacterEntities["Icirc"] = (char)206; _htmlCharacterEntities["icirc"] = (char)238; _htmlCharacterEntities["iexcl"] = (char)161; _htmlCharacterEntities["Igrave"] = (char)204; _htmlCharacterEntities["igrave"] = (char)236; _htmlCharacterEntities["image"] = (char)8465; _htmlCharacterEntities["infin"] = (char)8734; _htmlCharacterEntities["int"] = (char)8747; _htmlCharacterEntities["Iota"] = (char)921; _htmlCharacterEntities["iota"] = (char)953; _htmlCharacterEntities["iquest"] = (char)191; _htmlCharacterEntities["isin"] = (char)8712; _htmlCharacterEntities["Iuml"] = (char)207; _htmlCharacterEntities["iuml"] = (char)239; _htmlCharacterEntities["Kappa"] = (char)922; _htmlCharacterEntities["kappa"] = (char)954; _htmlCharacterEntities["Lambda"] = (char)923; _htmlCharacterEntities["lambda"] = (char)955; _htmlCharacterEntities["lang"] = (char)9001; _htmlCharacterEntities["laquo"] = (char)171; _htmlCharacterEntities["larr"] = (char)8592; _htmlCharacterEntities["lArr"] = (char)8656; _htmlCharacterEntities["lceil"] = (char)8968; _htmlCharacterEntities["ldquo"] = (char)8220; _htmlCharacterEntities["le"] = (char)8804; _htmlCharacterEntities["lfloor"] = (char)8970; _htmlCharacterEntities["lowast"] = (char)8727; _htmlCharacterEntities["loz"] = (char)9674; _htmlCharacterEntities["lrm"] = (char)8206; _htmlCharacterEntities["lsaquo"] = (char)8249; _htmlCharacterEntities["lsquo"] = (char)8216; _htmlCharacterEntities["lt"] = (char)60; _htmlCharacterEntities["macr"] = (char)175; _htmlCharacterEntities["mdash"] = (char)8212; _htmlCharacterEntities["micro"] = (char)181; _htmlCharacterEntities["middot"] = (char)183; _htmlCharacterEntities["minus"] = (char)8722; _htmlCharacterEntities["Mu"] = (char)924; _htmlCharacterEntities["mu"] = (char)956; _htmlCharacterEntities["nabla"] = (char)8711; _htmlCharacterEntities["nbsp"] = (char)160; _htmlCharacterEntities["ndash"] = (char)8211; _htmlCharacterEntities["ne"] = (char)8800; _htmlCharacterEntities["ni"] = (char)8715; _htmlCharacterEntities["not"] = (char)172; _htmlCharacterEntities["notin"] = (char)8713; _htmlCharacterEntities["nsub"] = (char)8836; _htmlCharacterEntities["Ntilde"] = (char)209; _htmlCharacterEntities["ntilde"] = (char)241; _htmlCharacterEntities["Nu"] = (char)925; _htmlCharacterEntities["nu"] = (char)957; _htmlCharacterEntities["Oacute"] = (char)211; _htmlCharacterEntities["ocirc"] = (char)244; _htmlCharacterEntities["OElig"] = (char)338; _htmlCharacterEntities["oelig"] = (char)339; _htmlCharacterEntities["Ograve"] = (char)210; _htmlCharacterEntities["ograve"] = (char)242; _htmlCharacterEntities["oline"] = (char)8254; _htmlCharacterEntities["Omega"] = (char)937; _htmlCharacterEntities["omega"] = (char)969; _htmlCharacterEntities["Omicron"] = (char)927; _htmlCharacterEntities["omicron"] = (char)959; _htmlCharacterEntities["oplus"] = (char)8853; _htmlCharacterEntities["or"] = (char)8744; _htmlCharacterEntities["ordf"] = (char)170; _htmlCharacterEntities["ordm"] = (char)186; _htmlCharacterEntities["Oslash"] = (char)216; _htmlCharacterEntities["oslash"] = (char)248; _htmlCharacterEntities["Otilde"] = (char)213; _htmlCharacterEntities["otilde"] = (char)245; _htmlCharacterEntities["otimes"] = (char)8855; _htmlCharacterEntities["Ouml"] = (char)214; _htmlCharacterEntities["ouml"] = (char)246; _htmlCharacterEntities["para"] = (char)182; _htmlCharacterEntities["part"] = (char)8706; _htmlCharacterEntities["permil"] = (char)8240; _htmlCharacterEntities["perp"] = (char)8869; _htmlCharacterEntities["Phi"] = (char)934; _htmlCharacterEntities["phi"] = (char)966; _htmlCharacterEntities["pi"] = (char)960; _htmlCharacterEntities["piv"] = (char)982; _htmlCharacterEntities["plusmn"] = (char)177; _htmlCharacterEntities["pound"] = (char)163; _htmlCharacterEntities["prime"] = (char)8242; _htmlCharacterEntities["Prime"] = (char)8243; _htmlCharacterEntities["prod"] = (char)8719; _htmlCharacterEntities["prop"] = (char)8733; _htmlCharacterEntities["Psi"] = (char)936; _htmlCharacterEntities["psi"] = (char)968; _htmlCharacterEntities["quot"] = (char)34; _htmlCharacterEntities["radic"] = (char)8730; _htmlCharacterEntities["rang"] = (char)9002; _htmlCharacterEntities["raquo"] = (char)187; _htmlCharacterEntities["rarr"] = (char)8594; _htmlCharacterEntities["rArr"] = (char)8658; _htmlCharacterEntities["rceil"] = (char)8969; _htmlCharacterEntities["rdquo"] = (char)8221; _htmlCharacterEntities["real"] = (char)8476; _htmlCharacterEntities["reg"] = (char)174; _htmlCharacterEntities["rfloor"] = (char)8971; _htmlCharacterEntities["Rho"] = (char)929; _htmlCharacterEntities["rho"] = (char)961; _htmlCharacterEntities["rlm"] = (char)8207; _htmlCharacterEntities["rsaquo"] = (char)8250; _htmlCharacterEntities["rsquo"] = (char)8217; _htmlCharacterEntities["sbquo"] = (char)8218; _htmlCharacterEntities["Scaron"] = (char)352; _htmlCharacterEntities["scaron"] = (char)353; _htmlCharacterEntities["sdot"] = (char)8901; _htmlCharacterEntities["sect"] = (char)167; _htmlCharacterEntities["shy"] = (char)173; _htmlCharacterEntities["Sigma"] = (char)931; _htmlCharacterEntities["sigma"] = (char)963; _htmlCharacterEntities["sigmaf"] = (char)962; _htmlCharacterEntities["sim"] = (char)8764; _htmlCharacterEntities["spades"] = (char)9824; _htmlCharacterEntities["sub"] = (char)8834; _htmlCharacterEntities["sube"] = (char)8838; _htmlCharacterEntities["sum"] = (char)8721; _htmlCharacterEntities["sup"] = (char)8835; _htmlCharacterEntities["sup1"] = (char)185; _htmlCharacterEntities["sup2"] = (char)178; _htmlCharacterEntities["sup3"] = (char)179; _htmlCharacterEntities["supe"] = (char)8839; _htmlCharacterEntities["szlig"] = (char)223; _htmlCharacterEntities["Tau"] = (char)932; _htmlCharacterEntities["tau"] = (char)964; _htmlCharacterEntities["there4"] = (char)8756; _htmlCharacterEntities["Theta"] = (char)920; _htmlCharacterEntities["theta"] = (char)952; _htmlCharacterEntities["thetasym"] = (char)977; _htmlCharacterEntities["thinsp"] = (char)8201; _htmlCharacterEntities["THORN"] = (char)222; _htmlCharacterEntities["thorn"] = (char)254; _htmlCharacterEntities["tilde"] = (char)732; _htmlCharacterEntities["times"] = (char)215; _htmlCharacterEntities["trade"] = (char)8482; _htmlCharacterEntities["Uacute"] = (char)218; _htmlCharacterEntities["uacute"] = (char)250; _htmlCharacterEntities["uarr"] = (char)8593; _htmlCharacterEntities["uArr"] = (char)8657; _htmlCharacterEntities["Ucirc"] = (char)219; _htmlCharacterEntities["ucirc"] = (char)251; _htmlCharacterEntities["Ugrave"] = (char)217; _htmlCharacterEntities["ugrave"] = (char)249; _htmlCharacterEntities["uml"] = (char)168; _htmlCharacterEntities["upsih"] = (char)978; _htmlCharacterEntities["Upsilon"] = (char)933; _htmlCharacterEntities["upsilon"] = (char)965; _htmlCharacterEntities["Uuml"] = (char)220; _htmlCharacterEntities["uuml"] = (char)252; _htmlCharacterEntities["weierp"] = (char)8472; _htmlCharacterEntities["Xi"] = (char)926; _htmlCharacterEntities["xi"] = (char)958; _htmlCharacterEntities["Yacute"] = (char)221; _htmlCharacterEntities["yacute"] = (char)253; _htmlCharacterEntities["yen"] = (char)165; _htmlCharacterEntities["Yuml"] = (char)376; _htmlCharacterEntities["yuml"] = (char)255; _htmlCharacterEntities["Zeta"] = (char)918; _htmlCharacterEntities["zeta"] = (char)950; _htmlCharacterEntities["zwj"] = (char)8205; _htmlCharacterEntities["zwnj"] = (char)8204; } #endregion Private Methods // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields // html element names // this is an array list now, but we may want to make it a hashtable later for better performance private static ArrayList _htmlInlineElements; private static ArrayList _htmlBlockElements; private static ArrayList _htmlOtherOpenableElements; // list of html empty element names private static ArrayList _htmlEmptyElements; // names of html elements for which closing tags are optional, and close when the outer nested element closes private static ArrayList _htmlElementsClosingOnParentElementEnd; // names of elements that close certain optional closing tag elements when they start // names of elements closing the colgroup element private static ArrayList _htmlElementsClosingColgroup; // names of elements closing the dd element private static ArrayList _htmlElementsClosingDD; // names of elements closing the dt element private static ArrayList _htmlElementsClosingDT; // names of elements closing the li element private static ArrayList _htmlElementsClosingLI; // names of elements closing the tbody element private static ArrayList _htmlElementsClosingTbody; // names of elements closing the td element private static ArrayList _htmlElementsClosingTD; // names of elements closing the tfoot element private static ArrayList _htmlElementsClosingTfoot; // names of elements closing the thead element private static ArrayList _htmlElementsClosingThead; // names of elements closing the th element private static ArrayList _htmlElementsClosingTH; // names of elements closing the tr element private static ArrayList _htmlElementsClosingTR; // html character entities hashtable private static Hashtable _htmlCharacterEntities; #endregion Private Fields } }
/*************************************************************************** * LinkLabel.cs * * Copyright (C) 2006 Novell, Inc. * Written by Aaron Bockover <aaron@abock.org> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using Gtk; using Hyena.Gui; namespace Banshee.Widgets { public class LinkLabel : EventBox { public delegate bool UriOpenHandler(string uri); private static UriOpenHandler default_open_handler; private static Gdk.Cursor hand_cursor = new Gdk.Cursor(Gdk.CursorType.Hand1); private Label label; private Uri uri; private bool act_as_link; private bool is_pressed; private bool is_hovering; private bool selectable; private UriOpenHandler open_handler; private Gdk.Color link_color; private bool interior_focus; private int focus_width; private int focus_padding; private int padding; public event EventHandler Clicked; public LinkLabel() : this(null, null) { Open = DefaultOpen; } public LinkLabel(string text, Uri uri) { CanFocus = true; AppPaintable = true; this.uri = uri; label = new Label(text); label.Show(); link_color = label.Style.Background(StateType.Selected); ActAsLink = true; Add(label); } protected override void OnStyleSet (Style previous_style) { base.OnStyleSet (previous_style); CheckButton check = new CheckButton (); check.EnsureStyle (); interior_focus = GtkUtilities.StyleGetProperty<bool> (check, "interior-focus", false); focus_width = GtkUtilities.StyleGetProperty<int> (check, "focus-line-width", -1); focus_padding = GtkUtilities.StyleGetProperty<int> (check, "focus-padding", -1); padding = interior_focus ? focus_width + focus_padding : 0; } protected virtual void OnClicked() { if(uri != null && Open != null) { Open(uri.AbsoluteUri); } EventHandler handler = Clicked; if(handler != null) { handler(this, new EventArgs()); } } protected override bool OnExposeEvent(Gdk.EventExpose evnt) { if(!IsDrawable) { return false; } if(evnt.Window == GdkWindow && HasFocus) { int layout_width = 0, layout_height = 0; label.Layout.GetPixelSize(out layout_width, out layout_height); Style.PaintFocus (Style, GdkWindow, State, evnt.Area, this, "checkbutton", 0, 0, layout_width + 2 * padding, layout_height + 2 * padding); } if(Child != null) { PropagateExpose(Child, evnt); } return false; } protected override void OnSizeRequested (ref Requisition requisition) { if (label == null) { base.OnSizeRequested (ref requisition); return; } requisition.Width = 0; requisition.Height = 0; Requisition child_requisition = label.SizeRequest (); requisition.Width = Math.Max (requisition.Width, child_requisition.Width); requisition.Height += child_requisition.Height; requisition.Width += ((int)BorderWidth + padding) * 2; requisition.Height += ((int)BorderWidth + padding) * 2; base.OnSizeRequested (ref requisition); } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { base.OnSizeAllocated (allocation); Gdk.Rectangle child_allocation = new Gdk.Rectangle (); if (label == null || !label.Visible) { return; } int total_padding = (int)BorderWidth + padding; child_allocation.X = total_padding; child_allocation.Y = total_padding; child_allocation.Width = (int)Math.Max (1, Allocation.Width - 2 * total_padding); child_allocation.Height = (int)Math.Max (1, Allocation.Height - 2 * total_padding); label.SizeAllocate (child_allocation); } protected override bool OnButtonPressEvent(Gdk.EventButton evnt) { if(evnt.Button == 1) { HasFocus = true; is_pressed = true; } return false; } protected override bool OnButtonReleaseEvent(Gdk.EventButton evnt) { if(evnt.Button == 1 && is_pressed && is_hovering) { OnClicked(); is_pressed = false; } return false; } protected override bool OnKeyReleaseEvent(Gdk.EventKey evnt) { if(evnt.Key != Gdk.Key.KP_Enter && evnt.Key != Gdk.Key.Return && evnt.Key != Gdk.Key.space) { return false; } OnClicked(); return false; } protected override bool OnEnterNotifyEvent(Gdk.EventCrossing evnt) { is_hovering = true; GdkWindow.Cursor = hand_cursor; return false; } protected override bool OnLeaveNotifyEvent(Gdk.EventCrossing evnt) { is_hovering = false; GdkWindow.Cursor = null; return false; } public Pango.EllipsizeMode Ellipsize { get { return label.Ellipsize; } set { label.Ellipsize = value; } } public string Text { get { return label.Text; } set { label.Text = value; } } public string Markup { set { label.Markup = value; } } public Label Label { get { return label; } } public float Xalign { get { return label.Xalign; } set { label.Xalign = value; } } public float Yalign { get { return label.Yalign; } set { label.Yalign = value; } } public bool Selectable { get { return selectable; } set { if((value && !ActAsLink) || !value) { label.Selectable = value; } selectable = value; } } public Uri Uri { get { return uri; } set { uri = value; } } public string UriString { get { return uri == null ? null : uri.AbsoluteUri; } set { uri = value == null ? null : new Uri(value); } } public UriOpenHandler Open { get { return open_handler; } set { open_handler = value; } } public bool ActAsLink { get { return act_as_link; } set { if(act_as_link == value) { return; } act_as_link = value; if(act_as_link) { label.Selectable = false; label.ModifyFg(Gtk.StateType.Normal, link_color); } else { label.Selectable = selectable; label.ModifyFg(Gtk.StateType.Normal, label.Style.Foreground(Gtk.StateType.Normal)); } label.QueueDraw(); } } public static UriOpenHandler DefaultOpen { get { return default_open_handler; } set { default_open_handler = value; } } } }
// 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 Microsoft.Win32.SafeHandles; using System; using System.IO.Pipes; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.ComponentModel; using System.Security.AccessControl; using System.Security.Principal; namespace Thrift.Transport.Server { // ReSharper disable once InconsistentNaming public class TNamedPipeServerTransport : TServerTransport { /// <summary> /// This is the address of the Pipe on the localhost. /// </summary> private readonly string _pipeAddress; private bool _asyncMode = true; private volatile bool _isPending = true; private NamedPipeServerStream _stream = null; public TNamedPipeServerTransport(string pipeAddress) { _pipeAddress = pipeAddress; } public override void Listen() { // nothing to do here } public override void Close() { if (_stream != null) { try { if (_stream.IsConnected) _stream.Disconnect(); _stream.Dispose(); } finally { _stream = null; _isPending = false; } } } public override bool IsClientPending() { return _isPending; } private void EnsurePipeInstance() { if (_stream == null) { const PipeDirection direction = PipeDirection.InOut; const int maxconn = NamedPipeServerStream.MaxAllowedServerInstances; const PipeTransmissionMode mode = PipeTransmissionMode.Byte; const int inbuf = 4096; const int outbuf = 4096; var options = _asyncMode ? PipeOptions.Asynchronous : PipeOptions.None; // TODO: "CreatePipeNative" ist only a workaround, and there are have basically two possible outcomes: // - once NamedPipeServerStream() gets a CTOR that supports pipesec, remove CreatePipeNative() // - if 31190 gets resolved before, use _stream.SetAccessControl(pipesec) instead of CreatePipeNative() // EITHER WAY, // - if CreatePipeNative() finally gets removed, also remove "allow unsafe code" from the project settings try { var handle = CreatePipeNative(_pipeAddress, inbuf, outbuf); if( (handle != null) && (!handle.IsInvalid)) _stream = new NamedPipeServerStream(PipeDirection.InOut, _asyncMode, false, handle); else _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf/*, pipesec*/); } catch (NotImplementedException) // Mono still does not support async, fallback to sync { if (_asyncMode) { options &= (~PipeOptions.Asynchronous); _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf); _asyncMode = false; } else { throw; } } } } #region CreatePipeNative workaround [StructLayout(LayoutKind.Sequential)] internal class SECURITY_ATTRIBUTES { internal int nLength = 0; internal IntPtr lpSecurityDescriptor = IntPtr.Zero; internal int bInheritHandle = 0; } private const string Kernel32 = "kernel32.dll"; [DllImport(Kernel32, SetLastError = true)] internal static extern IntPtr CreateNamedPipe( string lpName, uint dwOpenMode, uint dwPipeMode, uint nMaxInstances, uint nOutBufferSize, uint nInBufferSize, uint nDefaultTimeOut, SECURITY_ATTRIBUTES pipeSecurityDescriptor ); // Workaround: create the pipe via API call // we have to do it this way, since NamedPipeServerStream() for netstd still lacks a few CTORs // and _stream.SetAccessControl(pipesec); only keeps throwing ACCESS_DENIED errors at us // References: // - https://github.com/dotnet/corefx/issues/30170 (closed, continued in 31190) // - https://github.com/dotnet/corefx/issues/31190 System.IO.Pipes.AccessControl package does not work // - https://github.com/dotnet/corefx/issues/24040 NamedPipeServerStream: Provide support for WRITE_DAC // - https://github.com/dotnet/corefx/issues/34400 Have a mechanism for lower privileged user to connect to a privileged user's pipe private SafePipeHandle CreatePipeNative(string name, int inbuf, int outbuf) { if (Environment.OSVersion.Platform != PlatformID.Win32NT) return null; // Windows only var pinningHandle = new GCHandle(); try { // owner gets full access, everyone else read/write var pipesec = new PipeSecurity(); using (var currentIdentity = WindowsIdentity.GetCurrent()) { var sidOwner = currentIdentity.Owner; var sidWorld = new SecurityIdentifier(WellKnownSidType.WorldSid, null); pipesec.SetOwner(sidOwner); pipesec.AddAccessRule(new PipeAccessRule(sidOwner, PipeAccessRights.FullControl, AccessControlType.Allow)); pipesec.AddAccessRule(new PipeAccessRule(sidWorld, PipeAccessRights.ReadWrite, AccessControlType.Allow)); } // create a security descriptor and assign it to the security attribs var secAttrs = new SECURITY_ATTRIBUTES(); byte[] sdBytes = pipesec.GetSecurityDescriptorBinaryForm(); pinningHandle = GCHandle.Alloc(sdBytes, GCHandleType.Pinned); unsafe { fixed (byte* pSD = sdBytes) { secAttrs.lpSecurityDescriptor = (IntPtr)pSD; } } // a bunch of constants we will need shortly const int PIPE_ACCESS_DUPLEX = 0x00000003; const int FILE_FLAG_OVERLAPPED = 0x40000000; const int WRITE_DAC = 0x00040000; const int PIPE_TYPE_BYTE = 0x00000000; const int PIPE_READMODE_BYTE = 0x00000000; const int PIPE_UNLIMITED_INSTANCES = 255; // create the pipe via API call var rawHandle = CreateNamedPipe( @"\\.\pipe\" + name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | WRITE_DAC, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, PIPE_UNLIMITED_INSTANCES, (uint)inbuf, (uint)outbuf, 5 * 1000, secAttrs ); // make a SafePipeHandle() from it var handle = new SafePipeHandle(rawHandle, true); if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error()); // return it (to be packaged) return handle; } finally { if (pinningHandle.IsAllocated) pinningHandle.Free(); } } #endregion protected override async ValueTask<TTransport> AcceptImplementationAsync(CancellationToken cancellationToken) { try { EnsurePipeInstance(); await _stream.WaitForConnectionAsync(cancellationToken); var trans = new ServerTransport(_stream); _stream = null; // pass ownership to ServerTransport //_isPending = false; return trans; } catch (TTransportException) { Close(); throw; } catch (Exception e) { Close(); throw new TTransportException(TTransportException.ExceptionType.NotOpen, e.Message); } } private class ServerTransport : TTransport { private readonly NamedPipeServerStream PipeStream; public ServerTransport(NamedPipeServerStream stream) { PipeStream = stream; } public override bool IsOpen => PipeStream != null && PipeStream.IsConnected; public override async Task OpenAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override void Close() { PipeStream?.Dispose(); } public override async ValueTask<int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { if (PipeStream == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen); } return await PipeStream.ReadAsync(buffer, offset, length, cancellationToken); } public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { if (PipeStream == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen); } // if necessary, send the data in chunks // there's a system limit around 0x10000 bytes that we hit otherwise // MSDN: "Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section." var nBytes = Math.Min(15 * 4096, length); // 16 would exceed the limit while (nBytes > 0) { await PipeStream.WriteAsync(buffer, offset, nBytes, cancellationToken); offset += nBytes; length -= nBytes; nBytes = Math.Min(nBytes, length); } } public override async Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } protected override void Dispose(bool disposing) { PipeStream?.Dispose(); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR.Infrastructure; namespace Microsoft.AspNetCore.SignalR.Messaging { public abstract class Subscription : ISubscription, IDisposable { private readonly Func<MessageResult, object, Task<bool>> _callback; private readonly object _callbackState; private readonly IPerformanceCounterManager _counters; private int _state; private int _subscriptionState; private bool Alive { get { return _subscriptionState != SubscriptionState.Disposed; } } public string Identity { get; private set; } public IList<string> EventKeys { get; private set; } public int MaxMessages { get; private set; } public IDisposable Disposable { get; set; } protected Subscription(string identity, IList<string> eventKeys, Func<MessageResult, object, Task<bool>> callback, int maxMessages, IPerformanceCounterManager counters, object state) { if (String.IsNullOrEmpty(identity)) { throw new ArgumentNullException("identity"); } if (eventKeys == null) { throw new ArgumentNullException("eventKeys"); } if (callback == null) { throw new ArgumentNullException("callback"); } if (maxMessages < 0) { throw new ArgumentOutOfRangeException("maxMessages"); } if (counters == null) { throw new ArgumentNullException("counters"); } Identity = identity; _callback = callback; EventKeys = eventKeys; MaxMessages = maxMessages; _counters = counters; _callbackState = state; _counters.MessageBusSubscribersTotal.Increment(); _counters.MessageBusSubscribersCurrent.Increment(); _counters.MessageBusSubscribersPerSec.Increment(); } public virtual Task<bool> Invoke(MessageResult result) { return Invoke(result, (s, o) => { }, state: null); } private async Task<bool> Invoke(MessageResult result, Action<Subscription, object> beforeInvoke, object state) { // Change the state from idle to invoking callback var prevState = Interlocked.CompareExchange(ref _subscriptionState, SubscriptionState.InvokingCallback, SubscriptionState.Idle); if (prevState == SubscriptionState.Disposed) { // Only allow terminal messages after dispose if (!result.Terminal) { return false; } } beforeInvoke(this, state); _counters.MessageBusMessagesReceivedTotal.IncrementBy(result.TotalCount); _counters.MessageBusMessagesReceivedPerSec.IncrementBy(result.TotalCount); try { return await _callback(result, _callbackState); } finally { // Go from invoking callback to idle Interlocked.CompareExchange(ref _subscriptionState, SubscriptionState.Idle, SubscriptionState.InvokingCallback); } } [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "We have a sync and async code path.")] public async Task Work() { // Set the state to working Interlocked.Exchange(ref _state, State.Working); var items = new List<ArraySegment<Message>>(); while (Alive) { int totalCount; object state; items.Clear(); PerformWork(items, out totalCount, out state); if (items.Count > 0) { var messageResult = new MessageResult(items, totalCount); bool result = await Invoke(messageResult, (s, o) => s.BeforeInvoke(o), state); if (!result) { Dispose(); // If the callback said it's done then stop break; } } else { break; } } } public bool SetQueued() { return Interlocked.Increment(ref _state) == State.Working; } public bool UnsetQueued() { // If we try to set the state to idle and we were not already in the working state then keep going return Interlocked.CompareExchange(ref _state, State.Idle, State.Working) != State.Working; } protected virtual void BeforeInvoke(object state) { } [SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "The list needs to be populated")] [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "The caller wouldn't be able to specify what the generic type argument is")] [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "The count needs to be returned")] [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "The state needs to be set by the callee")] protected abstract void PerformWork(IList<ArraySegment<Message>> items, out int totalCount, out object state); public virtual bool AddEvent(string key, Topic topic) { return AddEventCore(key); } public virtual void RemoveEvent(string key) { lock (EventKeys) { EventKeys.Remove(key); } } public virtual void SetEventTopic(string key, Topic topic) { // Don't call AddEvent since that's virtual AddEventCore(key); } protected virtual void Dispose(bool disposing) { if (disposing) { // REIVIEW: Consider sleeping instead of using a tight loop, or maybe timing out after some interval // if the client is very slow then this invoke call might not end quickly and this will make the CPU // hot waiting for the task to return. var spinWait = new SpinWait(); while (true) { // Wait until the subscription isn't working anymore var state = Interlocked.CompareExchange(ref _subscriptionState, SubscriptionState.Disposed, SubscriptionState.Idle); // If we're not working then stop if (state != SubscriptionState.InvokingCallback) { if (state != SubscriptionState.Disposed) { // Only decrement if we're not disposed already _counters.MessageBusSubscribersCurrent.Decrement(); _counters.MessageBusSubscribersPerSec.Decrement(); } // Raise the disposed callback if (Disposable != null) { Disposable.Dispose(); } break; } spinWait.SpinOnce(); } } } public void Dispose() { Dispose(true); } public abstract void WriteCursor(TextWriter textWriter); private bool AddEventCore(string key) { lock (EventKeys) { if (EventKeys.Contains(key)) { return false; } EventKeys.Add(key); return true; } } private static class State { public const int Idle = 0; public const int Working = 1; } private static class SubscriptionState { public const int Idle = 0; public const int InvokingCallback = 1; public const int Disposed = 2; } } }
// 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; using System.Threading; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else using System.Threading.Tasks; namespace System.Diagnostics.Tracing #endif { /// <summary> /// Tracks activities. This is meant to be a singleton (accessed by the ActivityTracer.Instance static property) /// /// Logically this is simply holds the m_current variable that holds the async local that holds the current ActivityInfo /// An ActivityInfo is represents a activity (which knows its creator and thus knows its path). /// /// Most of the magic is in the async local (it gets copied to new tasks) /// /// On every start event call OnStart /// /// Guid activityID; /// Guid relatedActivityID; /// if (OnStart(activityName, out activityID, out relatedActivityID, ForceStop, options)) /// // Log Start event with activityID and relatedActivityID /// /// On every stop event call OnStop /// /// Guid activityID; /// if (OnStop(activityName, ref activityID ForceStop)) /// // Stop event with activityID /// /// On any normal event log the event with activityTracker.CurrentActivityId /// </summary> internal class ActivityTracker { /// <summary> /// Called on work item begins. The activity name = providerName + activityName without 'Start' suffix. /// It updates CurrentActivityId to track. /// /// It returns true if the Start should be logged, otherwise (if it is illegal recursion) it return false. /// /// The start event should use as its activity ID the CurrentActivityId AFTER calling this routine and its /// RelatedActivityID the CurrentActivityId BEFORE calling this routine (the creator). /// /// If activity tracing is not on, then activityId and relatedActivityId are not set /// </summary> public void OnStart(string providerName, string activityName, int task, ref Guid activityId, ref Guid relatedActivityId, EventActivityOptions options) { if (m_current == null) // We are not enabled { // We used to rely on the TPL provider turning us on, but that has the disadvantage that you don't get Start-Stop tracking // until you use Tasks for the first time (which you may never do). Thus we change it to pull rather tan push for whether // we are enabled. if (m_checkedForEnable) return; m_checkedForEnable = true; if (TplEtwProvider.Log.IsEnabled(EventLevel.Informational, TplEtwProvider.Keywords.TasksFlowActivityIds)) Enable(); if (m_current == null) return; } Contract.Assert((options & EventActivityOptions.Disable) == 0); var currentActivity = m_current.Value; var fullActivityName = NormalizeActivityName(providerName, activityName, task); var etwLog = TplEtwProvider.Log; if (etwLog.Debug) { etwLog.DebugFacilityMessage("OnStartEnter", fullActivityName); etwLog.DebugFacilityMessage("OnStartEnterActivityState", ActivityInfo.LiveActivities(currentActivity)); } if (currentActivity != null) { // Stop activity tracking if we reached the maximum allowed depth if (currentActivity.m_level >= MAX_ACTIVITY_DEPTH) { activityId = Guid.Empty; relatedActivityId = Guid.Empty; if (etwLog.Debug) etwLog.DebugFacilityMessage("OnStartRET", "Fail"); return; } // Check for recursion, and force-stop any activities if the activity already started. if ((options & EventActivityOptions.Recursive) == 0) { ActivityInfo existingActivity = FindActiveActivity(fullActivityName, currentActivity); if (existingActivity != null) { OnStop(providerName, activityName, task, ref activityId); currentActivity = m_current.Value; } } } // Get a unique ID for this activity. long id; if (currentActivity == null) id = Interlocked.Increment(ref m_nextId); else id = Interlocked.Increment(ref currentActivity.m_lastChildID); // The previous ID is my 'causer' and becomes my related activity ID relatedActivityId = EventSource.CurrentThreadActivityId; // Add to the list of started but not stopped activities. ActivityInfo newActivity = new ActivityInfo(fullActivityName, id, currentActivity, relatedActivityId, options); m_current.Value = newActivity; // Remember the current ID so we can log it activityId = newActivity.ActivityId; if (etwLog.Debug) { etwLog.DebugFacilityMessage("OnStartRetActivityState", ActivityInfo.LiveActivities(newActivity)); etwLog.DebugFacilityMessage1("OnStartRet", activityId.ToString(), relatedActivityId.ToString()); } } /// <summary> /// Called when a work item stops. The activity name = providerName + activityName without 'Stop' suffix. /// It updates m_current variable to track this fact. The Stop event associated with stop should log the ActivityID associated with the event. /// /// If activity tracing is not on, then activityId and relatedActivityId are not set /// </summary> public void OnStop(string providerName, string activityName, int task, ref Guid activityId) { if (m_current == null) // We are not enabled return; var fullActivityName = NormalizeActivityName(providerName, activityName, task); var etwLog = TplEtwProvider.Log; if (etwLog.Debug) { etwLog.DebugFacilityMessage("OnStopEnter", fullActivityName); etwLog.DebugFacilityMessage("OnStopEnterActivityState", ActivityInfo.LiveActivities(m_current.Value)); } for (; ; ) // This is a retry loop. { ActivityInfo currentActivity = m_current.Value; ActivityInfo newCurrentActivity = null; // if we have seen any live activities (orphans), at he first one we have seen. // Search to find the activity to stop in one pass. This insures that we don't let one mistake // (stopping something that was not started) cause all active starts to be stopped // By first finding the target start to stop we are more robust. ActivityInfo activityToStop = FindActiveActivity(fullActivityName, currentActivity); // ignore stops where we can't find a start because we may have popped them previously. if (activityToStop == null) { activityId = Guid.Empty; // TODO add some logging about this. Basically could not find matching start. if (etwLog.Debug) etwLog.DebugFacilityMessage("OnStopRET", "Fail"); return; } activityId = activityToStop.ActivityId; // See if there are any orphans that need to be stopped. ActivityInfo orphan = currentActivity; while (orphan != activityToStop && orphan != null) { if (orphan.m_stopped != 0) // Skip dead activities. { orphan = orphan.m_creator; continue; } if (orphan.CanBeOrphan()) { // We can't pop anything after we see a valid orphan, remember this for later when we update m_current. if (newCurrentActivity == null) newCurrentActivity = orphan; } else { orphan.m_stopped = 1; Contract.Assert(orphan.m_stopped != 0); } orphan = orphan.m_creator; } // try to Stop the activity atomically. Other threads may be trying to do this as well. if (Interlocked.CompareExchange(ref activityToStop.m_stopped, 1, 0) == 0) { // I succeeded stopping this activity. Now we update our m_current pointer // If I haven't yet determined the new current activity, it is my creator. if (newCurrentActivity == null) newCurrentActivity = activityToStop.m_creator; m_current.Value = newCurrentActivity; if (etwLog.Debug) { etwLog.DebugFacilityMessage("OnStopRetActivityState", ActivityInfo.LiveActivities(newCurrentActivity)); etwLog.DebugFacilityMessage("OnStopRet", activityId.ToString()); } return; } // We failed to stop it. We must have hit a race to stop it. Just start over and try again. } } /// <summary> /// Turns on activity tracking. It is sticky, once on it stays on (race issues otherwise) /// </summary> [System.Security.SecuritySafeCritical] public void Enable() { if (m_current == null) { // Catch the not Implemented try { m_current = new AsyncLocal<ActivityInfo>(ActivityChanging); } catch (NotImplementedException) { #if (!ES_BUILD_PCL && ! PROJECTN) // send message to debugger without delay System.Diagnostics.Debugger.Log(0, null, "Activity Enabled() called but AsyncLocals Not Supported (pre V4.6). Ignoring Enable"); #endif } } } /// <summary> /// An activity tracker is a singleton, this is how you get the one and only instance. /// </summary> public static ActivityTracker Instance { get { return s_activityTrackerInstance; } } #region private /// <summary> /// The current activity ID. Use this to log normal events. /// </summary> private Guid CurrentActivityId { get { return m_current.Value.ActivityId; } } /// <summary> /// Searched for a active (nonstopped) activity with the given name. Returns null if not found. /// </summary> private ActivityInfo FindActiveActivity(string name, ActivityInfo startLocation) { var activity = startLocation; while (activity != null) { if (name == activity.m_name && activity.m_stopped == 0) return activity; activity = activity.m_creator; } return null; } /// <summary> /// Strip out "Start" or "End" suffix from activity name and add providerName prefix. /// If 'task' it does not end in Start or Stop and Task is non-zero use that as the name of the activity /// </summary> private string NormalizeActivityName(string providerName, string activityName, int task) { if (activityName.EndsWith(EventSource.s_ActivityStartSuffix, StringComparison.Ordinal)) activityName = activityName.Substring(0, activityName.Length - EventSource.s_ActivityStartSuffix.Length); else if (activityName.EndsWith(EventSource.s_ActivityStopSuffix, StringComparison.Ordinal)) activityName = activityName.Substring(0, activityName.Length - EventSource.s_ActivityStopSuffix.Length); else if (task != 0) activityName = "task" + task.ToString(); // We use provider name to distinguish between activities from different providers. return providerName + activityName; } // ******************************************************************************* /// <summary> /// An ActivityInfo represents a particular activity. It is almost read-only. The only /// fields that change after creation are /// m_lastChildID - used to generate unique IDs for the children activities and for the most part can be ignored. /// m_stopped - indicates that this activity is dead /// This read-only-ness is important because an activity's m_creator chain forms the /// 'Path of creation' for the activity (which is also its unique ID) but is also used as /// the 'list of live parents' which indicate of those ancestors, which are alive (if they /// are not marked dead they are alive). /// </summary> private class ActivityInfo { public ActivityInfo(string name, long uniqueId, ActivityInfo creator, Guid activityIDToRestore, EventActivityOptions options) { m_name = name; m_eventOptions = options; m_creator = creator; m_uniqueId = uniqueId; m_level = creator != null ? creator.m_level + 1 : 0; m_activityIdToRestore = activityIDToRestore; // Create a nice GUID that encodes the chain of activities that started this one. CreateActivityPathGuid(out m_guid, out m_activityPathGuidOffset); } public Guid ActivityId { get { return m_guid; } } public static string Path(ActivityInfo activityInfo) { if (activityInfo == null) return (""); return Path(activityInfo.m_creator) + "/" + activityInfo.m_uniqueId.ToString(); } public override string ToString() { return m_name + "(" + Path(this) + (m_stopped != 0 ? ",DEAD)" : ")"); } public static string LiveActivities(ActivityInfo list) { if (list == null) return ""; return list.ToString() + ";" + LiveActivities(list.m_creator); } public bool CanBeOrphan() { if ((m_eventOptions & EventActivityOptions.Detachable) != 0) return true; return false; } #region private #region CreateActivityPathGuid /// <summary> /// Logically every activity Path (see Path()) that describes the activities that caused this /// (rooted in an activity that predates activity tracking. /// /// We wish to encode this path in the Guid to the extent that we can. Many of the paths have /// many small numbers in them and we take advantage of this in the encoding to output as long /// a path in the GUID as possible. /// /// Because of the possibility of GUID collision, we only use 96 of the 128 bits of the GUID /// for encoding the path. The last 32 bits are a simple checksum (and random number) that /// identifies this as using the convention defined here. /// /// It returns both the GUID which has the path as well as the offset that points just beyond /// the end of the activity (so it can be appended to). Note that if the end is in a nibble /// (it uses nibbles instead of bytes as the unit of encoding, then it will point at the unfinished /// byte (since the top nibble can't be zero you can determine if this is true by seeing if /// this byte is nonZero. This offset is needed to efficiently create the ID for child activities. /// </summary> [System.Security.SecuritySafeCritical] private unsafe void CreateActivityPathGuid(out Guid idRet, out int activityPathGuidOffset) { fixed (Guid* outPtr = &idRet) { int activityPathGuidOffsetStart = 0; if (m_creator != null) { activityPathGuidOffsetStart = m_creator.m_activityPathGuidOffset; idRet = m_creator.m_guid; } else { // TODO FIXME - differentiate between AD inside PCL int appDomainID = 0; #if (!ES_BUILD_STANDALONE && !PROJECTN) appDomainID = System.Threading.Thread.GetDomainID(); #endif // We start with the appdomain number to make this unique among appdomains. activityPathGuidOffsetStart = AddIdToGuid(outPtr, activityPathGuidOffsetStart, (uint)appDomainID); } activityPathGuidOffset = AddIdToGuid(outPtr, activityPathGuidOffsetStart, (uint)m_uniqueId); // If the path does not fit, Make a GUID by incrementing rather than as a path, keeping as much of the path as possible if (12 < activityPathGuidOffset) CreateOverflowGuid(outPtr); } } /// <summary> /// If we can't fit the activity Path into the GUID we come here. What we do is simply /// generate a 4 byte number (s_nextOverflowId). Then look for an ancestor that has /// sufficient space for this ID. By doing this, we preserve the fact that this activity /// is a child (of unknown depth) from that ancestor. /// </summary> [System.Security.SecurityCritical] private unsafe void CreateOverflowGuid(Guid* outPtr) { // Search backwards for an ancestor that has sufficient space to put the ID. for (ActivityInfo ancestor = m_creator; ancestor != null; ancestor = ancestor.m_creator) { if (ancestor.m_activityPathGuidOffset <= 10) // we need at least 2 bytes. { uint id = unchecked((uint)Interlocked.Increment(ref ancestor.m_lastChildID)); // Get a unique ID // Try to put the ID into the GUID *outPtr = ancestor.m_guid; int endId = AddIdToGuid(outPtr, ancestor.m_activityPathGuidOffset, id, true); // Does it fit? if (endId <= 12) break; } } } /// <summary> /// The encoding for a list of numbers used to make Activity GUIDs. Basically /// we operate on nibbles (which are nice because they show up as hex digits). The /// list is ended with a end nibble (0) and depending on the nibble value (Below) /// the value is either encoded into nibble itself or it can spill over into the /// bytes that follow. /// </summary> enum NumberListCodes : byte { End = 0x0, // ends the list. No valid value has this prefix. LastImmediateValue = 0xA, PrefixCode = 0xB, // all the 'long' encodings go here. If the next nibble is MultiByte1-4 // than this is a 'overflow' id. Unlike the hierarchical IDs these are // allocated densely but don't tell you anything about nesting. we use // these when we run out of space in the GUID to store the path. MultiByte1 = 0xC, // 1 byte follows. If this Nibble is in the high bits, it the high bits of the number are stored in the low nibble. // commented out because the code does not explicitly reference the names (but they are logically defined). // MultiByte2 = 0xD, // 2 bytes follow (we don't bother with the nibble optimization) // MultiByte3 = 0xE, // 3 bytes follow (we don't bother with the nibble optimization) // MultiByte4 = 0xF, // 4 bytes follow (we don't bother with the nibble optimization) } /// Add the activity id 'id' to the output Guid 'outPtr' starting at the offset 'whereToAddId' /// Thus if this number is 6 that is where 'id' will be added. This will return 13 (12 /// is the maximum number of bytes that fit in a GUID) if the path did not fit. /// If 'overflow' is true, then the number is encoded as an 'overflow number (which has a /// special (longer prefix) that indicates that this ID is allocated differently [System.Security.SecurityCritical] private static unsafe int AddIdToGuid(Guid* outPtr, int whereToAddId, uint id, bool overflow = false) { byte* ptr = (byte*)outPtr; byte* endPtr = ptr + 12; ptr += whereToAddId; if (endPtr <= ptr) return 13; // 12 means we might exactly fit, 13 means we definately did not fit if (0 < id && id <= (uint)NumberListCodes.LastImmediateValue && !overflow) WriteNibble(ref ptr, endPtr, id); else { uint len = 4; if (id <= 0xFF) len = 1; else if (id <= 0xFFFF) len = 2; else if (id <= 0xFFFFFF) len = 3; if (overflow) { if (endPtr <= ptr + 2) // I need at least 2 bytes return 13; // Write out the prefix code nibble and the length nibble WriteNibble(ref ptr, endPtr, (uint)NumberListCodes.PrefixCode); } // The rest is the same for overflow and non-overflow case WriteNibble(ref ptr, endPtr, (uint)NumberListCodes.MultiByte1 + (len - 1)); // Do we have an odd nibble? If so flush it or use it for the 12 byte case. if (ptr < endPtr && *ptr != 0) { // If the value < 4096 we can use the nibble we are otherwise just outputting as padding. if (id < 4096) { // Indicate this is a 1 byte multicode with 4 high order bits in the lower nibble. *ptr = (byte)(((uint)NumberListCodes.MultiByte1 << 4) + (id >> 8)); id &= 0xFF; // Now we only want the low order bits. } ptr++; } // Write out the bytes. while (0 < len) { if (endPtr <= ptr) { ptr++; // Indicate that we have overflowed break; } *ptr++ = (byte)id; id = (id >> 8); --len; } } // Compute the checksum uint* sumPtr = (uint*)outPtr; // We set the last DWORD the sum of the first 3 DWORDS in the GUID. This sumPtr[3] = sumPtr[0] + sumPtr[1] + sumPtr[2] + 0x599D99AD; // This last number is a random number (it identifies us as us) return (int)(ptr - ((byte*)outPtr)); } /// <summary> /// Write a single Nible 'value' (must be 0-15) to the byte buffer represented by *ptr. /// Will not go past 'endPtr'. Also it assumes that we never write 0 so we can detect /// whether a nibble has already been written to ptr because it will be nonzero. /// Thus if it is non-zero it adds to the current byte, otherwise it advances and writes /// the new byte (in the high bits) of the next byte. /// </summary> [System.Security.SecurityCritical] private static unsafe void WriteNibble(ref byte* ptr, byte* endPtr, uint value) { Contract.Assert(0 <= value && value < 16); Contract.Assert(ptr < endPtr); if (*ptr != 0) *ptr++ |= (byte)value; else *ptr = (byte)(value << 4); } #endregion // CreateGuidForActivityPath readonly internal string m_name; // The name used in the 'start' and 'stop' APIs to help match up readonly long m_uniqueId; // a small number that makes this activity unique among its siblings internal readonly Guid m_guid; // Activity Guid, it is basically an encoding of the Path() (see CreateActivityPathGuid) internal readonly int m_activityPathGuidOffset; // Keeps track of where in m_guid the causality path stops (used to generated child GUIDs) internal readonly int m_level; // current depth of the Path() of the activity (used to keep recursion under control) readonly internal EventActivityOptions m_eventOptions; // Options passed to start. internal long m_lastChildID; // used to create a unique ID for my children activities internal int m_stopped; // This work item has stopped readonly internal ActivityInfo m_creator; // My parent (creator). Forms the Path() for the activity. readonly internal Guid m_activityIdToRestore; // The Guid to restore after a stop. #endregion } // This callback is used to initialize the m_current AsyncLocal Variable. // Its job is to keep the ETW Activity ID (part of thread local storage) in sync // with m_current.ActivityID void ActivityChanging(AsyncLocalValueChangedArgs<ActivityInfo> args) { ActivityInfo cur = args.CurrentValue; ActivityInfo prev = args.PreviousValue; // Are we popping off a value? (we have a prev, and it creator is cur) // Then check if we should use the GUID at the time of the start event if (prev != null && prev.m_creator == cur) { // If the saved activity ID is not the same as the creator activity // that takes precedence (it means someone explicitly did a SetActivityID) // Set it to that and get out if (cur == null || prev.m_activityIdToRestore != cur.ActivityId) { EventSource.SetCurrentThreadActivityId(prev.m_activityIdToRestore); return; } } // OK we did not have an explicit SetActivityID set. Then we should be // setting the activity to current ActivityInfo. However that activity // might be dead, in which case we should skip it, so we never set // the ID to dead things. while (cur != null) { // We found a live activity (typically the first time), set it to that. if (cur.m_stopped == 0) { EventSource.SetCurrentThreadActivityId(cur.ActivityId); return; } cur = cur.m_creator; } // we can get here if there is no information on our activity stack (everything is dead) // currently we do nothing, as that seems better than setting to Guid.Emtpy. } /// <summary> /// Async local variables have the property that the are automatically copied whenever a task is created and used /// while that task is running. Thus m_current 'flows' to any task that is caused by the current thread that /// last set it. /// /// This variable points a a linked list that represents all Activities that have started but have not stopped. /// </summary> AsyncLocal<ActivityInfo> m_current; bool m_checkedForEnable; // Singleton private static ActivityTracker s_activityTrackerInstance = new ActivityTracker(); // Used to create unique IDs at the top level. Not used for nested Ids (each activity has its own id generator) static long m_nextId = 0; private const ushort MAX_ACTIVITY_DEPTH = 100; // Limit maximum depth of activities to be tracked at 100. // This will avoid leaking memory in case of activities that are never stopped. #endregion } #if ES_BUILD_STANDALONE || PROJECTN /******************************** SUPPORT *****************************/ /// <summary> /// This is supplied by the framework. It is has the semantics that the value is copied to any new Tasks that is created /// by the current task. Thus all causally related code gets this value. Note that reads and writes to this VARIABLE /// (not what it points it) to this does not need to be protected by locks because it is inherently thread local (you always /// only get your thread local copy which means that you never have races. /// </summary> /// #if ES_BUILD_STANDALONE [EventSource(Name = "Microsoft.Tasks.Nuget")] #else [EventSource(Name = "System.Diagnostics.Tracing.TplEtwProvider")] #endif internal class TplEtwProvider : EventSource { public class Keywords { public const EventKeywords TasksFlowActivityIds = (EventKeywords)0x80; public const EventKeywords Debug = (EventKeywords)0x20000; } public static TplEtwProvider Log = new TplEtwProvider(); public bool Debug { get { return IsEnabled(EventLevel.Verbose, Keywords.Debug); } } public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(1, Facility, Message); } public void DebugFacilityMessage1(string Facility, string Message, string Arg) { WriteEvent(2, Facility, Message, Arg); } public void SetActivityId(Guid Id) { WriteEvent(3, Id); } } #endif #if ES_BUILD_AGAINST_DOTNET_V35 || ES_BUILD_PCL || NO_ASYNC_LOCAL // In these cases we don't have any Async local support. Do nothing. internal sealed class AsyncLocalValueChangedArgs<T> { public T PreviousValue { get { return default(T); } } public T CurrentValue { get { return default(T); } } } internal sealed class AsyncLocal<T> { public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>> valueChangedHandler) { throw new NotImplementedException("AsyncLocal only available on V4.6 and above"); } public T Value { get { return default(T); } set { } } } #endif }
using System; using System.Collections.Generic; using Sce.Pss.Core; using Sce.Pss.Core.Environment; using Sce.Pss.Core.Graphics; using Sce.Pss.Core.Input; using Sce.Pss.Core.Audio; using Sce.Pss.HighLevel.GameEngine2D; using Sce.Pss.HighLevel.GameEngine2D.Base; using Sce.Pss.HighLevel.UI; using MagnateUI; namespace Magnate { public class Game { public static Game Instance; Game game = Game.Instance; public int battlePhase = 1; public bool startscreenmusic = true; static GraphicsContext graphics; public bool Running = true; //GameEngine2D public WorldMap World {get;set;} public StartScreen Start {get;set;} //UI scenes public MainGUI GUI {get; set;} public BattleUI Battle {get; set;} public ScreenVignette screen {get; set;} public ChatDialogueUI chat {get; set;} public StartScreenUI startui {get; set;} public Mine Mine {get;set;} public GoodTown GoodTown {get;set;} public Hilltop Hilltop {get;set;} public DestroyedTown DestroyedTown {get;set;} public FinalBattle FinalBattle {get;set;} public FirstScene FirstScene {get;set;} public Dungeon Dungeon {get;set;} public Fortress Fortress {get;set;} public BlackSmith BlackSmith {get;set;} //Like its the 90s yo! public BgmPlayer BOOMBOX {get; set;} public Bgm Music{get;set;} public bool StartScreenFinished {get;set;} public bool BattleFinished {get;set;} public bool ChatFinished {get;set;} public bool ScreenFinished {get;set;} public bool guiFinished {get;set;} public bool resetCount {get;set;} public bool StartBattle {get; set;} public bool ResumeChat {get; set;} public bool StartScreenCleanup {get; set;} public bool ChatSceneCleanup {get; set;} public bool VignetteCleanup {get; set;} public bool WorldMapCleanUp {get; set;} public bool BattleCleanUp {get; set;} public bool MusicCleanUp {get; set;} public bool GUICleanup {get; set;} public bool startmusic {get; set;} public bool quitmusic {get;set;} public bool CleanUI {get; set;} private static List<TouchData> touch_data; public void Initialize () { uint spriteCapacity = 500; uint drawHelpersCapacity = 400; graphics = new GraphicsContext (); StartUpMethods.SetUpDirector (spriteCapacity, drawHelpersCapacity, graphics); var uitransition = new CrossFadeTransition(); Start = new StartScreen(); startui = new StartScreenUI(); startui.Transition = uitransition; Director.Instance.RunWithScene (Start, true); StartUpMethods.SetUpUI(graphics, startui); } public void Update () { touch_data = Touch.GetData(0); // Not strictly neccessary Input2.Touch.SetData(0, touch_data); Director.Instance.Update (); UISystem.Update (touch_data); if(StartBattle) { SceneManager.PushUIScene((int)UI.BATTLE,battlePhase); StartBattle = false; } if(ResumeChat) { } } public void Render () { graphics.SetClearColor (Colors.Black); Director.Instance.Render (); UISystem.Render (); Director.Instance.GL.Context.SwapBuffers (); Director.Instance.PostSwap (); } public void Cleanup () { Director.Terminate (); UISystem.Terminate (); } public void Quit() { Running = false; } public void CleanAllUI() { StartScreenCleanup = true; VignetteCleanup = true; GUICleanup = true; BattleCleanUp = true; game.CleanUI = true; } } /******************************************************************************************************************************/ public static class StartUpMethods { public static void SetUpDirector (uint spriteCapacity, uint drawHelperCapacity, Sce.Pss.Core.Graphics.GraphicsContext context) { Director.Initialize (spriteCapacity, drawHelperCapacity, context); Director.Instance.GL.Context.SetClearColor (Colors.White); Director.Instance.DebugFlags |= DebugFlags.Navigate; } public static void SetUpUI (GraphicsContext graphics, Sce.Pss.HighLevel.UI.Scene scene) { UISystem.Initialize (graphics); UISystem.SetScene (scene); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities; using Microsoft.AspNetCore.Server.IntegrationTesting; using Microsoft.AspNetCore.Server.IntegrationTesting.IIS; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Xunit; #if !IIS_FUNCTIONALS using Microsoft.AspNetCore.Server.IIS.FunctionalTests; #if IISEXPRESS_FUNCTIONALS namespace Microsoft.AspNetCore.Server.IIS.IISExpress.FunctionalTests #elif NEWHANDLER_FUNCTIONALS namespace Microsoft.AspNetCore.Server.IIS.NewHandler.FunctionalTests #elif NEWSHIM_FUNCTIONALS namespace Microsoft.AspNetCore.Server.IIS.NewShim.FunctionalTests #endif #else namespace Microsoft.AspNetCore.Server.IIS.FunctionalTests #endif { [Collection(PublishedSitesCollection.Name)] [SkipNonHelix("https://github.com/dotnet/aspnetcore/issues/25107")] public class FrebTests : IISFunctionalTestBase { public FrebTests(PublishedSitesFixture fixture) : base(fixture) { } public static IList<FrebLogItem> FrebChecks() { var list = new List<FrebLogItem>(); list.Add(new FrebLogItem("ANCM_INPROC_EXECUTE_REQUEST_START")); list.Add(new FrebLogItem("ANCM_INPROC_EXECUTE_REQUEST_COMPLETION", "1")); list.Add(new FrebLogItem("ANCM_INPROC_ASYNC_COMPLETION_START")); list.Add(new FrebLogItem("ANCM_INPROC_ASYNC_COMPLETION_COMPLETION", "0")); list.Add(new FrebLogItem("ANCM_INPROC_MANAGED_REQUEST_COMPLETION")); return list; } [ConditionalFact] [RequiresIIS(IISCapability.FailedRequestTracingModule)] public async Task CheckCommonFrebEvents() { var result = await SetupFrebApp(); await result.HttpClient.GetAsync("HelloWorld"); StopServer(); AssertFrebLogs(result, FrebChecks()); } [ConditionalFact] [RequiresNewShim] [RequiresIIS(IISCapability.FailedRequestTracingModule)] public async Task FrebIncludesHResultFailures() { var parameters = Fixture.GetBaseDeploymentParameters(); parameters.TransformArguments((args, _) => string.Empty); var result = await SetupFrebApp(parameters); await result.HttpClient.GetAsync("HelloWorld"); StopServer(); AssertFrebLogs(result, new FrebLogItem("ANCM_HRESULT_FAILED"), new FrebLogItem("ANCM_EXCEPTION_CAUGHT")); } [ConditionalFact] [RequiresIIS(IISCapability.FailedRequestTracingModule)] public async Task CheckFailedRequestEvents() { var result = await SetupFrebApp(); await result.HttpClient.GetAsync("Throw"); StopServer(); AssertFrebLogs(result, new FrebLogItem("ANCM_INPROC_ASYNC_COMPLETION_COMPLETION", "2")); } // I think this test is flaky due to freb file not being created quickly enough. // Adding extra logging, marking as flaky, and repeating should help [ConditionalFact] [Repeat(10)] [RequiresIIS(IISCapability.FailedRequestTracingModule)] public async Task CheckFrebDisconnect() { var result = await SetupFrebApp(); using (var connection = new TestConnection(result.HttpClient.BaseAddress.Port)) { await connection.Send( "GET /WaitForAbort HTTP/1.1", "Host: localhost", "Connection: close", "", ""); await result.HttpClient.RetryRequestAsync("/WaitingRequestCount", async message => await message.Content.ReadAsStringAsync() == "1"); } StopServer(); // The order of freb logs is based on when the requests are complete. // This is non-deterministic here, so we need to check both freb files for a request that was disconnected. AssertFrebLogs(result, new FrebLogItem("ANCM_INPROC_REQUEST_DISCONNECT"), new FrebLogItem("ANCM_INPROC_MANAGED_REQUEST_COMPLETION")); } private async Task<IISDeploymentResult> SetupFrebApp(IISDeploymentParameters parameters = null) { parameters = parameters ?? Fixture.GetBaseDeploymentParameters(); parameters.EnableFreb("Verbose", LogFolderPath); Directory.CreateDirectory(LogFolderPath); var result = await DeployAsync(parameters); return result; } private void AssertFrebLogs(IISDeploymentResult result, params FrebLogItem[] expectedFrebEvents) { AssertFrebLogs(result, (IEnumerable<FrebLogItem>)expectedFrebEvents); } private void AssertFrebLogs(IISDeploymentResult result, IEnumerable<FrebLogItem> expectedFrebEvents) { var frebEvent = GetFrebLogItems(result); foreach (var expectedEvent in expectedFrebEvents) { result.Logger.LogInformation($"Checking if {expectedEvent.ToString()} exists."); Assert.Contains(expectedEvent, frebEvent); } } private IEnumerable<FrebLogItem> GetFrebLogItems(IISDeploymentResult result) { var folderPath = Helpers.GetFrebFolder(LogFolderPath, result); var xmlFiles = Directory.GetFiles(folderPath).Where(f => f.EndsWith("xml", StringComparison.Ordinal)).ToList(); var frebEvents = new List<FrebLogItem>(); result.Logger.LogInformation($"Number of freb files available {xmlFiles.Count}."); foreach (var xmlFile in xmlFiles) { var xDocument = XDocument.Load(xmlFile).Root; var nameSpace = (XNamespace)"http://schemas.microsoft.com/win/2004/08/events/event"; var eventElements = xDocument.Descendants(nameSpace + "Event"); foreach (var eventElement in eventElements) { var eventElementWithOpCode = eventElement.Descendants(nameSpace + "RenderingInfo").Single().Descendants(nameSpace + "Opcode").Single(); var requestStatus = eventElement.Element(nameSpace + "EventData").Descendants().Where(el => el.Attribute("Name").Value == "requestStatus").SingleOrDefault(); frebEvents.Add(new FrebLogItem(eventElementWithOpCode.Value, requestStatus?.Value)); } } return frebEvents; } public class FrebLogItem { private string _opCode; private string _requestStatus; public FrebLogItem(string opCode) { _opCode = opCode; } public FrebLogItem(string opCode, string requestStatus) { _opCode = opCode; _requestStatus = requestStatus; } public override bool Equals(object obj) { var item = obj as FrebLogItem; return item != null && _opCode == item._opCode && _requestStatus == item._requestStatus; } public override int GetHashCode() { return HashCode.Combine(_opCode, _requestStatus); } public override string ToString() { return $"FrebLogItem: opCode: {_opCode}, requestStatus: {_requestStatus}"; } } } }
//----------------------------------------------------------------------- // <copyright file="Tcp.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Immutable; using System.Net; using System.Threading.Tasks; using Akka.Actor; using Akka.IO; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Implementation.IO; namespace Akka.Streams.Dsl { /// <summary> /// TBD /// </summary> public class Tcp : ExtensionIdProvider<TcpExt> { /// <summary> /// TBD /// </summary> /// <param name="system">TBD</param> /// <returns>TBD</returns> public override TcpExt CreateExtension(ExtendedActorSystem system) => new TcpExt(system); /// <summary> /// Represents a successful TCP server binding. /// </summary> public struct ServerBinding { private readonly Func<Task> _unbindAction; /// <summary> /// TBD /// </summary> /// <param name="localAddress">TBD</param> /// <param name="unbindAction">TBD</param> public ServerBinding(EndPoint localAddress, Func<Task> unbindAction) { _unbindAction = unbindAction; LocalAddress = localAddress; } /// <summary> /// TBD /// </summary> public readonly EndPoint LocalAddress; /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public Task Unbind() => _unbindAction(); } /// <summary> /// Represents an accepted incoming TCP connection. /// </summary> public struct IncomingConnection { /// <summary> /// TBD /// </summary> /// <param name="localAddress">TBD</param> /// <param name="remoteAddress">TBD</param> /// <param name="flow">TBD</param> public IncomingConnection(EndPoint localAddress, EndPoint remoteAddress, Flow<ByteString, ByteString, NotUsed> flow) { LocalAddress = localAddress; RemoteAddress = remoteAddress; Flow = flow; } /// <summary> /// TBD /// </summary> public readonly EndPoint LocalAddress; /// <summary> /// TBD /// </summary> public readonly EndPoint RemoteAddress; /// <summary> /// TBD /// </summary> public readonly Flow<ByteString, ByteString, NotUsed> Flow; /// <summary> /// Handles the connection using the given flow, which is materialized exactly once and the respective /// materialized instance is returned. /// <para/> /// Convenience shortcut for: flow.join(handler).run(). /// </summary> /// <typeparam name="TMat">TBD</typeparam> /// <param name="handler">TBD</param> /// <param name="materializer">TBD</param> /// <returns>TBD</returns> public TMat HandleWith<TMat>(Flow<ByteString, ByteString, TMat> handler, IMaterializer materializer) => Flow.JoinMaterialized(handler, Keep.Right).Run(materializer); } /// <summary> /// Represents a prospective outgoing TCP connection. /// </summary> public struct OutgoingConnection { /// <summary> /// TBD /// </summary> /// <param name="remoteAddress">TBD</param> /// <param name="localAddress">TBD</param> public OutgoingConnection(EndPoint remoteAddress, EndPoint localAddress) { LocalAddress = localAddress; RemoteAddress = remoteAddress; } /// <summary> /// TBD /// </summary> public readonly EndPoint LocalAddress; /// <summary> /// TBD /// </summary> public readonly EndPoint RemoteAddress; } } /// <summary> /// TBD /// </summary> public class TcpExt : IExtension { private readonly ExtendedActorSystem _system; /// <summary> /// TBD /// </summary> /// <param name="system">TBD</param> public TcpExt(ExtendedActorSystem system) { _system = system; BindShutdownTimeout = ActorMaterializer.Create(system).Settings.SubscriptionTimeoutSettings.Timeout; } /// <summary> /// TBD /// </summary> protected readonly TimeSpan BindShutdownTimeout; /// <summary> /// Creates a <see cref="Tcp.ServerBinding"/> instance which represents a prospective TCP server binding on the given <paramref name="host"/> and <paramref name="port"/>/>. /// <para/> /// Please note that the startup of the server is asynchronous, i.e. after materializing the enclosing /// <see cref="RunnableGraph{TMat}"/> the server is not immediately available. Only after the materialized future /// completes is the server ready to accept client connections. /// </summary> /// <param name="host">The host to listen on</param> /// <param name="port">The port to listen on</param> /// <param name="backlog">Controls the size of the connection backlog</param> /// <param name="options">TCP options for the connections, see <see cref="Akka.IO.Tcp"/> for details</param> /// <param name="halfClose">Controls whether the connection is kept open even after writing has been completed to the accepted TCP connections. /// If set to true, the connection will implement the TCP half-close mechanism, allowing the client to /// write to the connection even after the server has finished writing. The TCP socket is only closed /// after both the client and server finished writing. /// If set to false, the connection will immediately closed once the server closes its write side, /// independently whether the client is still attempting to write. This setting is recommended /// for servers, and therefore it is the default setting. /// </param> /// <param name="idleTimeout">TBD</param> /// <exception cref="ArgumentException">TBD</exception> /// <returns>TBD</returns> public Source<Tcp.IncomingConnection, Task<Tcp.ServerBinding>> Bind(string host, int port, int backlog = 100, IImmutableList<Inet.SocketOption> options = null, bool halfClose = false, TimeSpan? idleTimeout = null) { // DnsEndpoint isn't allowed var ipAddresses = System.Net.Dns.GetHostAddressesAsync(host).Result; if (ipAddresses.Length == 0) throw new ArgumentException($"Couldn't resolve IpAdress for host {host}", nameof(host)); return Source.FromGraph(new ConnectionSourceStage(_system.Tcp(), new IPEndPoint(ipAddresses[0], port), backlog, options, halfClose, idleTimeout, BindShutdownTimeout)); } /// <summary> /// Creates a <see cref="Tcp.ServerBinding"/> instance which represents a prospective TCP server binding on the given <paramref name="host"/> and <paramref name="port"/>/> /// handling the incoming connections using the provided Flow. /// <para/> /// Please note that the startup of the server is asynchronous, i.e. after materializing the enclosing /// <see cref="RunnableGraph{TMat}"/> the server is not immediately available. Only after the materialized future /// completes is the server ready to accept client connections. /// </summary> /// <param name="handler">A Flow that represents the server logic</param> /// <param name="materializer">TBD</param> /// <param name="host">The host to listen on</param> /// <param name="port">The port to listen on</param> /// <param name="backlog">Controls the size of the connection backlog</param> /// <param name="options">TCP options for the connections, see <see cref="Akka.IO.Tcp"/> for details</param> /// <param name="halfClose">Controls whether the connection is kept open even after writing has been completed to the accepted TCP connections. /// If set to true, the connection will implement the TCP half-close mechanism, allowing the client to /// write to the connection even after the server has finished writing. The TCP socket is only closed /// after both the client and server finished writing. /// If set to false, the connection will immediately closed once the server closes its write side, /// independently whether the client is still attempting to write. This setting is recommended /// for servers, and therefore it is the default setting. /// </param> /// <param name="idleTimeout">TBD</param> /// <returns>TBD</returns> public Task<Tcp.ServerBinding> BindAndHandle(Flow<ByteString, ByteString, NotUsed> handler, IMaterializer materializer, string host, int port, int backlog = 100, IImmutableList<Inet.SocketOption> options = null, bool halfClose = false, TimeSpan? idleTimeout = null) { return Bind(host, port, backlog, options, halfClose, idleTimeout) .To(Sink.ForEach<Tcp.IncomingConnection>(connection => connection.Flow.Join(handler).Run(materializer))) .Run(materializer); } /// <summary> /// Creates a <see cref="Tcp.OutgoingConnection"/> instance representing a prospective TCP client connection to the given endpoint. /// </summary> /// <param name="remoteAddress"> The remote address to connect to</param> /// <param name="localAddress">Optional local address for the connection</param> /// <param name="options">TCP options for the connections, see <see cref="Akka.IO.Tcp"/> for details</param> /// <param name="halfClose"> Controls whether the connection is kept open even after writing has been completed to the accepted TCP connections. /// If set to true, the connection will implement the TCP half-close mechanism, allowing the server to /// write to the connection even after the client has finished writing.The TCP socket is only closed /// after both the client and server finished writing. This setting is recommended for clients and therefore it is the default setting. /// If set to false, the connection will immediately closed once the client closes its write side, /// independently whether the server is still attempting to write. /// </param> /// <param name="connectionTimeout">TBD</param> /// <param name="idleTimeout">TBD</param> /// <returns>TBD</returns> public Flow<ByteString, ByteString, Task<Tcp.OutgoingConnection>> OutgoingConnection(EndPoint remoteAddress, EndPoint localAddress = null, IImmutableList<Inet.SocketOption> options = null, bool halfClose = true, TimeSpan? connectionTimeout = null, TimeSpan? idleTimeout = null) { //connectionTimeout = connectionTimeout ?? TimeSpan.FromMinutes(60); var tcpFlow = Flow.FromGraph(new OutgoingConnectionStage(_system.Tcp(), remoteAddress, localAddress, options, halfClose, connectionTimeout)).Via(new Detacher<ByteString>()); if (idleTimeout.HasValue) return tcpFlow.Join(BidiFlow.BidirectionalIdleTimeout<ByteString, ByteString>(idleTimeout.Value)); return tcpFlow; } /// <summary> /// Creates an <see cref="Tcp.OutgoingConnection"/> without specifying options. /// It represents a prospective TCP client connection to the given endpoint. /// </summary> /// <param name="host">TBD</param> /// <param name="port">TBD</param> /// <returns>TBD</returns> public Flow<ByteString, ByteString, Task<Tcp.OutgoingConnection>> OutgoingConnection(string host, int port) => OutgoingConnection(CreateEndpoint(host, port)); internal static EndPoint CreateEndpoint(string host, int port) { IPAddress address; return IPAddress.TryParse(host, out address) ? (EndPoint) new IPEndPoint(address, port) : new DnsEndPoint(host, port); } } /// <summary> /// TBD /// </summary> public static class TcpStreamExtensions { /// <summary> /// TBD /// </summary> /// <param name="system">TBD</param> /// <returns>TBD</returns> public static TcpExt TcpStream(this ActorSystem system) => system.WithExtension<TcpExt, Tcp>(); } public sealed class TcpIdleTimeoutException : TimeoutException { public TcpIdleTimeoutException(string message, TimeSpan duration) : base(message) { Duration = duration; } public TimeSpan Duration { get; } } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.List.IndexOf(T item) /// </summary> public class ListIndexOf1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int"); try { int[] iArray = new int[1000]; for (int i = 0; i < 1000; i++) { iArray[i] = i; } List<int> listObject = new List<int>(iArray); int ob = this.GetInt32(0, 1000); int result = listObject.IndexOf(ob); if (result != ob) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string"); try { string[] strArray = { "apple", "banana", "chocolate", "dog", "food" }; List<string> listObject = new List<string>(strArray); int result = listObject.IndexOf("dog"); if (result != 3) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is a custom type"); try { MyClass myclass1 = new MyClass(); MyClass myclass2 = new MyClass(); MyClass myclass3 = new MyClass(); MyClass[] mc = new MyClass[3] { myclass1, myclass2, myclass3 }; List<MyClass> listObject = new List<MyClass>(mc); int result = listObject.IndexOf(myclass3); if (result != 2) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: There are many element in the list with the same value"); try { string[] strArray = { "apple", "banana", "chocolate", "banana", "banana", "dog", "banana", "food" }; List<string> listObject = new List<string>(strArray); int result = listObject.IndexOf("banana"); if (result != 1) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Do not find the element "); try { int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); int result = listObject.IndexOf(-10000); if (result != -1) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases #endregion #endregion public static int Main() { ListIndexOf1 test = new ListIndexOf1(); TestLibrary.TestFramework.BeginTestCase("ListIndexOf1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } } public class MyClass { }
using System; using Avalonia.Media; using Avalonia.Platform; using SkiaSharp; namespace Avalonia.Skia { /// <summary> /// A Skia implementation of <see cref="IGeometryImpl"/>. /// </summary> internal abstract class GeometryImpl : IGeometryImpl { private PathCache _pathCache; private SKPathMeasure _pathMeasureCache; private SKPathMeasure CachedPathMeasure { get { if (_pathMeasureCache is null) { _pathMeasureCache = new SKPathMeasure(EffectivePath); } return _pathMeasureCache; } } /// <inheritdoc /> public abstract Rect Bounds { get; } /// <inheritdoc /> public double ContourLength { get { if (EffectivePath is null) return 0; return (double)CachedPathMeasure?.Length; } } public abstract SKPath EffectivePath { get; } /// <inheritdoc /> public bool FillContains(Point point) { return PathContainsCore(EffectivePath, point); } /// <inheritdoc /> public bool StrokeContains(IPen pen, Point point) { // Skia requires to compute stroke path to check for point containment. // Due to that we are caching using stroke width. // Usually this function is being called with same stroke width per path, so this saves a lot of Skia traffic. var strokeWidth = (float)(pen?.Thickness ?? 0); if (!_pathCache.HasCacheFor(strokeWidth)) { UpdatePathCache(strokeWidth); } return PathContainsCore(_pathCache.CachedStrokePath, point); } /// <summary> /// Update path cache for given stroke width. /// </summary> /// <param name="strokeWidth">Stroke width.</param> private void UpdatePathCache(float strokeWidth) { var strokePath = new SKPath(); // For stroke widths close to 0 simply use empty path. Render bounds are cached from fill path. if (Math.Abs(strokeWidth) < float.Epsilon) { _pathCache.Cache(strokePath, strokeWidth, Bounds); } else { using (var paint = new SKPaint()) { paint.IsStroke = true; paint.StrokeWidth = strokeWidth; paint.GetFillPath(EffectivePath, strokePath); _pathCache.Cache(strokePath, strokeWidth, strokePath.TightBounds.ToAvaloniaRect()); } } } /// <summary> /// Check Skia path if it contains a point. /// </summary> /// <param name="path">Path to check.</param> /// <param name="point">Point.</param> /// <returns>True, if point is contained in a path.</returns> private static bool PathContainsCore(SKPath path, Point point) { return path.Contains((float)point.X, (float)point.Y); } /// <inheritdoc /> public IGeometryImpl Intersect(IGeometryImpl geometry) { var result = EffectivePath.Op(((GeometryImpl)geometry).EffectivePath, SKPathOp.Intersect); return result == null ? null : new StreamGeometryImpl(result); } /// <inheritdoc /> public Rect GetRenderBounds(IPen pen) { var strokeWidth = (float)(pen?.Thickness ?? 0); if (!_pathCache.HasCacheFor(strokeWidth)) { UpdatePathCache(strokeWidth); } return _pathCache.CachedGeometryRenderBounds; } /// <inheritdoc /> public ITransformedGeometryImpl WithTransform(Matrix transform) { return new TransformedGeometryImpl(this, transform); } /// <inheritdoc /> public bool TryGetPointAtDistance(double distance, out Point point) { if (EffectivePath is null) { point = new Point(); return false; } var res = CachedPathMeasure.GetPosition((float)distance, out var skPoint); point = new Point(skPoint.X, skPoint.Y); return res; } /// <inheritdoc /> public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { if (EffectivePath is null) { point = new Point(); tangent = new Point(); return false; } var res = CachedPathMeasure.GetPositionAndTangent((float)distance, out var skPoint, out var skTangent); point = new Point(skPoint.X, skPoint.Y); tangent = new Point(skTangent.X, skTangent.Y); return res; } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { if (EffectivePath is null) { segmentGeometry = null; return false; } segmentGeometry = null; var _skPathSegment = new SKPath(); var res = CachedPathMeasure.GetSegment((float)startDistance, (float)stopDistance, _skPathSegment, startOnBeginFigure); if (res) { segmentGeometry = new StreamGeometryImpl(_skPathSegment); } return res; } /// <summary> /// Invalidate all caches. Call after chaining path contents. /// </summary> protected void InvalidateCaches() { _pathCache.Invalidate(); } private struct PathCache { private float _cachedStrokeWidth; /// <summary> /// Tolerance for two stroke widths to be deemed equal /// </summary> public const float Tolerance = float.Epsilon; /// <summary> /// Cached contour path. /// </summary> public SKPath CachedStrokePath { get; private set; } /// <summary> /// Cached geometry render bounds. /// </summary> public Rect CachedGeometryRenderBounds { get; private set; } /// <summary> /// Is cached valid for given stroke width. /// </summary> /// <param name="strokeWidth">Stroke width to check.</param> /// <returns>True, if CachedStrokePath can be used for given stroke width.</returns> public bool HasCacheFor(float strokeWidth) { return CachedStrokePath != null && Math.Abs(_cachedStrokeWidth - strokeWidth) < Tolerance; } /// <summary> /// Cache path for given stroke width. Takes ownership of a passed path. /// </summary> /// <param name="path">Path to cache.</param> /// <param name="strokeWidth">Stroke width to cache.</param> /// <param name="geometryRenderBounds">Render bounds to use.</param> public void Cache(SKPath path, float strokeWidth, Rect geometryRenderBounds) { if (CachedStrokePath != path) { CachedStrokePath?.Dispose(); } CachedStrokePath = path; CachedGeometryRenderBounds = geometryRenderBounds; _cachedStrokeWidth = strokeWidth; } /// <summary> /// Invalidate cache state. /// </summary> public void Invalidate() { CachedStrokePath?.Dispose(); CachedGeometryRenderBounds = Rect.Empty; _cachedStrokeWidth = default(float); } } } }
// 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; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Roslyn.Utilities; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.CodeAnalysis.CommandLine; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// This class defines all of the common stuff that is shared between the Vbc and Csc tasks. /// This class is not instantiatable as a Task just by itself. /// </summary> public abstract class ManagedCompiler : ToolTask { private CancellationTokenSource _sharedCompileCts; internal readonly PropertyDictionary _store = new PropertyDictionary(); public ManagedCompiler() { TaskResources = ErrorString.ResourceManager; } #region Properties // Please keep these alphabetized. public string[] AdditionalLibPaths { set { _store[nameof(AdditionalLibPaths)] = value; } get { return (string[])_store[nameof(AdditionalLibPaths)]; } } public string[] AddModules { set { _store[nameof(AddModules)] = value; } get { return (string[])_store[nameof(AddModules)]; } } public ITaskItem[] AdditionalFiles { set { _store[nameof(AdditionalFiles)] = value; } get { return (ITaskItem[])_store[nameof(AdditionalFiles)]; } } public ITaskItem[] Analyzers { set { _store[nameof(Analyzers)] = value; } get { return (ITaskItem[])_store[nameof(Analyzers)]; } } // We do not support BugReport because it always requires user interaction, // which will cause a hang. public string ChecksumAlgorithm { set { _store[nameof(ChecksumAlgorithm)] = value; } get { return (string)_store[nameof(ChecksumAlgorithm)]; } } /// <summary> /// An instrument flag that specifies instrumentation settings. /// </summary> public string Instrument { set { _store[nameof(Instrument)] = value; } get { return (string)_store[nameof(Instrument)]; } } public string CodeAnalysisRuleSet { set { _store[nameof(CodeAnalysisRuleSet)] = value; } get { return (string)_store[nameof(CodeAnalysisRuleSet)]; } } public int CodePage { set { _store[nameof(CodePage)] = value; } get { return _store.GetOrDefault(nameof(CodePage), 0); } } [Output] public ITaskItem[] CommandLineArgs { set { _store[nameof(CommandLineArgs)] = value; } get { return (ITaskItem[])_store[nameof(CommandLineArgs)]; } } public string DebugType { set { _store[nameof(DebugType)] = value; } get { return (string)_store[nameof(DebugType)]; } } public string SourceLink { set { _store[nameof(SourceLink)] = value; } get { return (string)_store[nameof(SourceLink)]; } } public string DefineConstants { set { _store[nameof(DefineConstants)] = value; } get { return (string)_store[nameof(DefineConstants)]; } } public bool DelaySign { set { _store[nameof(DelaySign)] = value; } get { return _store.GetOrDefault(nameof(DelaySign), false); } } public bool Deterministic { set { _store[nameof(Deterministic)] = value; } get { return _store.GetOrDefault(nameof(Deterministic), false); } } public bool PublicSign { set { _store[nameof(PublicSign)] = value; } get { return _store.GetOrDefault(nameof(PublicSign), false); } } public bool EmitDebugInformation { set { _store[nameof(EmitDebugInformation)] = value; } get { return _store.GetOrDefault(nameof(EmitDebugInformation), false); } } public string ErrorLog { set { _store[nameof(ErrorLog)] = value; } get { return (string)_store[nameof(ErrorLog)]; } } public string Features { set { _store[nameof(Features)] = value; } get { return (string)_store[nameof(Features)]; } } public int FileAlignment { set { _store[nameof(FileAlignment)] = value; } get { return _store.GetOrDefault(nameof(FileAlignment), 0); } } public bool HighEntropyVA { set { _store[nameof(HighEntropyVA)] = value; } get { return _store.GetOrDefault(nameof(HighEntropyVA), false); } } public string KeyContainer { set { _store[nameof(KeyContainer)] = value; } get { return (string)_store[nameof(KeyContainer)]; } } public string KeyFile { set { _store[nameof(KeyFile)] = value; } get { return (string)_store[nameof(KeyFile)]; } } public ITaskItem[] LinkResources { set { _store[nameof(LinkResources)] = value; } get { return (ITaskItem[])_store[nameof(LinkResources)]; } } public string MainEntryPoint { set { _store[nameof(MainEntryPoint)] = value; } get { return (string)_store[nameof(MainEntryPoint)]; } } public bool NoConfig { set { _store[nameof(NoConfig)] = value; } get { return _store.GetOrDefault(nameof(NoConfig), false); } } public bool NoLogo { set { _store[nameof(NoLogo)] = value; } get { return _store.GetOrDefault(nameof(NoLogo), false); } } public bool NoWin32Manifest { set { _store[nameof(NoWin32Manifest)] = value; } get { return _store.GetOrDefault(nameof(NoWin32Manifest), false); } } public bool Optimize { set { _store[nameof(Optimize)] = value; } get { return _store.GetOrDefault(nameof(Optimize), false); } } [Output] public ITaskItem OutputAssembly { set { _store[nameof(OutputAssembly)] = value; } get { return (ITaskItem)_store[nameof(OutputAssembly)]; } } public string Platform { set { _store[nameof(Platform)] = value; } get { return (string)_store[nameof(Platform)]; } } public bool Prefer32Bit { set { _store[nameof(Prefer32Bit)] = value; } get { return _store.GetOrDefault(nameof(Prefer32Bit), false); } } public bool ProvideCommandLineArgs { set { _store[nameof(ProvideCommandLineArgs)] = value; } get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); } } public ITaskItem[] References { set { _store[nameof(References)] = value; } get { return (ITaskItem[])_store[nameof(References)]; } } public bool ReportAnalyzer { set { _store[nameof(ReportAnalyzer)] = value; } get { return _store.GetOrDefault(nameof(ReportAnalyzer), false); } } public ITaskItem[] Resources { set { _store[nameof(Resources)] = value; } get { return (ITaskItem[])_store[nameof(Resources)]; } } public string RuntimeMetadataVersion { set { _store[nameof(RuntimeMetadataVersion)] = value; } get { return (string)_store[nameof(RuntimeMetadataVersion)]; } } public ITaskItem[] ResponseFiles { set { _store[nameof(ResponseFiles)] = value; } get { return (ITaskItem[])_store[nameof(ResponseFiles)]; } } public bool SkipCompilerExecution { set { _store[nameof(SkipCompilerExecution)] = value; } get { return _store.GetOrDefault(nameof(SkipCompilerExecution), false); } } public ITaskItem[] Sources { set { if (UsedCommandLineTool) { NormalizePaths(value); } _store[nameof(Sources)] = value; } get { return (ITaskItem[])_store[nameof(Sources)]; } } public string SubsystemVersion { set { _store[nameof(SubsystemVersion)] = value; } get { return (string)_store[nameof(SubsystemVersion)]; } } public string TargetType { set { _store[nameof(TargetType)] = CultureInfo.InvariantCulture.TextInfo.ToLower(value); } get { return (string)_store[nameof(TargetType)]; } } public bool TreatWarningsAsErrors { set { _store[nameof(TreatWarningsAsErrors)] = value; } get { return _store.GetOrDefault(nameof(TreatWarningsAsErrors), false); } } public bool Utf8Output { set { _store[nameof(Utf8Output)] = value; } get { return _store.GetOrDefault(nameof(Utf8Output), false); } } public string Win32Icon { set { _store[nameof(Win32Icon)] = value; } get { return (string)_store[nameof(Win32Icon)]; } } public string Win32Manifest { set { _store[nameof(Win32Manifest)] = value; } get { return (string)_store[nameof(Win32Manifest)]; } } public string Win32Resource { set { _store[nameof(Win32Resource)] = value; } get { return (string)_store[nameof(Win32Resource)]; } } public string PathMap { set { _store[nameof(PathMap)] = value; } get { return (string)_store[nameof(PathMap)]; } } /// <summary> /// If this property is true then the task will take every C# or VB /// compilation which is queued by MSBuild and send it to the /// VBCSCompiler server instance, starting a new instance if necessary. /// If false, we will use the values from ToolPath/Exe. /// </summary> public bool UseSharedCompilation { set { _store[nameof(UseSharedCompilation)] = value; } get { return _store.GetOrDefault(nameof(UseSharedCompilation), false); } } // Map explicit platform of "AnyCPU" or the default platform (null or ""), since it is commonly understood in the // managed build process to be equivalent to "AnyCPU", to platform "AnyCPU32BitPreferred" if the Prefer32Bit // property is set. internal string PlatformWith32BitPreference { get { string platform = Platform; if ((string.IsNullOrEmpty(platform) || platform.Equals("anycpu", StringComparison.OrdinalIgnoreCase)) && Prefer32Bit) { platform = "anycpu32bitpreferred"; } return platform; } } /// <summary> /// Overridable property specifying the encoding of the captured task standard output stream /// </summary> protected override Encoding StandardOutputEncoding { get { return (Utf8Output) ? Encoding.UTF8 : base.StandardOutputEncoding; } } #endregion internal abstract RequestLanguage Language { get; } protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { if (ProvideCommandLineArgs) { CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands) .Select(arg => new TaskItem(arg)).ToArray(); } if (SkipCompilerExecution) { return 0; } if (!UseSharedCompilation || !string.IsNullOrEmpty(ToolPath)) { return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } using (_sharedCompileCts = new CancellationTokenSource()) { try { CompilerServerLogger.Log($"CommandLine = '{commandLineCommands}'"); CompilerServerLogger.Log($"BuildResponseFile = '{responseFileCommands}'"); // Try to get the location of the user-provided build client and server, // which should be located next to the build task. If not, fall back to // "pathToTool", which is the compiler in the MSBuild default bin directory. var clientDir = TryGetClientDir() ?? Path.GetDirectoryName(pathToTool); pathToTool = Path.Combine(clientDir, ToolExe); // Note: we can't change the "tool path" printed to the console when we run // the Csc/Vbc task since MSBuild logs it for us before we get here. Instead, // we'll just print our own message that contains the real client location Log.LogMessage(ErrorString.UsingSharedCompilation, clientDir); var buildPaths = new BuildPaths( clientDir: clientDir, // MSBuild doesn't need the .NET SDK directory sdkDir: null, workingDir: CurrentDirectoryToUse()); var responseTask = BuildClientShim.RunServerCompilation( Language, GetArguments(commandLineCommands, responseFileCommands).ToList(), buildPaths, keepAlive: null, libEnvVariable: LibDirectoryToUse(), cancellationToken: _sharedCompileCts.Token); responseTask.Wait(_sharedCompileCts.Token); var response = responseTask.Result; if (response != null) { ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands); } else { Log.LogMessage(ErrorString.SharedCompilationFallback, pathToTool); ExitCode = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } } catch (OperationCanceledException) { ExitCode = 0; } catch (Exception e) { Log.LogErrorWithCodeFromResources("Compiler_UnexpectedException"); LogErrorOutput(e.ToString()); ExitCode = -1; } } return ExitCode; } /// <summary> /// Try to get the directory this assembly is in. Returns null if assembly /// was in the GAC or DLL location can not be retrieved. /// </summary> private static string TryGetClientDir() { #if PORTABLE50 return null; #else var buildTask = typeof(ManagedCompiler).GetTypeInfo().Assembly; if (buildTask.GlobalAssemblyCache) return null; var uri = new Uri(buildTask.CodeBase); string assemblyPath = uri.IsFile ? uri.LocalPath : Assembly.GetCallingAssembly().Location; return Path.GetDirectoryName(assemblyPath); #endif } /// <summary> /// Cancel the in-process build task. /// </summary> public override void Cancel() { base.Cancel(); _sharedCompileCts?.Cancel(); } /// <summary> /// Get the current directory that the compiler should run in. /// </summary> private string CurrentDirectoryToUse() { // ToolTask has a method for this. But it may return null. Use the process directory // if ToolTask didn't override. MSBuild uses the process directory. string workingDirectory = GetWorkingDirectory(); if (string.IsNullOrEmpty(workingDirectory)) workingDirectory = Directory.GetCurrentDirectory(); return workingDirectory; } /// <summary> /// Get the "LIB" environment variable, or NULL if none. /// </summary> private string LibDirectoryToUse() { // First check the real environment. string libDirectory = Environment.GetEnvironmentVariable("LIB"); // Now go through additional environment variables. string[] additionalVariables = EnvironmentVariables; if (additionalVariables != null) { foreach (string var in EnvironmentVariables) { if (var.StartsWith("LIB=", StringComparison.OrdinalIgnoreCase)) { libDirectory = var.Substring(4); } } } return libDirectory; } /// <summary> /// The return code of the compilation. Strangely, this isn't overridable from ToolTask, so we need /// to create our own. /// </summary> [Output] public new int ExitCode { get; private set; } /// <summary> /// Handle a response from the server, reporting messages and returning /// the appropriate exit code. /// </summary> private int HandleResponse(BuildResponse response, string pathToTool, string responseFileCommands, string commandLineCommands) { switch (response.Type) { case BuildResponse.ResponseType.MismatchedVersion: LogErrorOutput(CommandLineParser.MismatchedVersionErrorText); return -1; case BuildResponse.ResponseType.Completed: var completedResponse = (CompletedBuildResponse)response; LogMessages(completedResponse.Output, StandardOutputImportanceToUse); if (LogStandardErrorAsError) { LogErrorOutput(completedResponse.ErrorOutput); } else { LogMessages(completedResponse.ErrorOutput, StandardErrorImportanceToUse); } return completedResponse.ReturnCode; case BuildResponse.ResponseType.Rejected: case BuildResponse.ResponseType.AnalyzerInconsistency: return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); default: throw new InvalidOperationException("Encountered unknown response type"); } } private void LogErrorOutput(string output) { string[] lines = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { string trimmedMessage = line.Trim(); if (trimmedMessage != "") { Log.LogError(trimmedMessage); } } } /// <summary> /// Log each of the messages in the given output with the given importance. /// We assume each line is a message to log. /// </summary> /// <remarks> /// Should be "private protected" visibility once it is introduced into C#. /// </remarks> internal abstract void LogMessages(string output, MessageImportance messageImportance); public string GenerateResponseFileContents() { return GenerateResponseFileCommands(); } /// <summary> /// Get the command line arguments to pass to the compiler. /// </summary> private string[] GetArguments(string commandLineCommands, string responseFileCommands) { var commandLineArguments = CommandLineParser.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true); var responseFileArguments = CommandLineParser.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true); return commandLineArguments.Concat(responseFileArguments).ToArray(); } /// <summary> /// Returns the command line switch used by the tool executable to specify the response file /// Will only be called if the task returned a non empty string from GetResponseFileCommands /// Called after ValidateParameters, SkipTaskExecution and GetResponseFileCommands /// </summary> protected override string GenerateResponseFileCommands() { CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension(); AddResponseFileCommands(commandLineBuilder); return commandLineBuilder.ToString(); } protected override string GenerateCommandLineCommands() { CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension(); AddCommandLineCommands(commandLineBuilder); return commandLineBuilder.ToString(); } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and /// must go directly onto the command line. /// </summary> protected internal virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendWhenTrue("/noconfig", _store, nameof(NoConfig)); } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> protected internal virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { // If outputAssembly is not specified, then an "/out: <name>" option won't be added to // overwrite the one resulting from the OutputAssembly member of the CompilerParameters class. // In that case, we should set the outputAssembly member based on the first source file. if ( (OutputAssembly == null) && (Sources != null) && (Sources.Length > 0) && (ResponseFiles == null) // The response file may already have a /out: switch in it, so don't try to be smart here. ) { try { OutputAssembly = new TaskItem(Path.GetFileNameWithoutExtension(Sources[0].ItemSpec)); } catch (ArgumentException e) { throw new ArgumentException(e.Message, "Sources"); } if (string.Compare(TargetType, "library", StringComparison.OrdinalIgnoreCase) == 0) { OutputAssembly.ItemSpec += ".dll"; } else if (string.Compare(TargetType, "module", StringComparison.OrdinalIgnoreCase) == 0) { OutputAssembly.ItemSpec += ".netmodule"; } else { OutputAssembly.ItemSpec += ".exe"; } } commandLine.AppendSwitchIfNotNull("/addmodule:", AddModules, ","); commandLine.AppendSwitchWithInteger("/codepage:", _store, nameof(CodePage)); ConfigureDebugProperties(); // The "DebugType" parameter should be processed after the "EmitDebugInformation" parameter // because it's more specific. Order matters on the command-line, and the last one wins. // /debug+ is just a shorthand for /debug:full. And /debug- is just a shorthand for /debug:none. commandLine.AppendPlusOrMinusSwitch("/debug", _store, nameof(EmitDebugInformation)); commandLine.AppendSwitchIfNotNull("/debug:", DebugType); commandLine.AppendPlusOrMinusSwitch("/delaysign", _store, nameof(DelaySign)); commandLine.AppendSwitchWithInteger("/filealign:", _store, nameof(FileAlignment)); commandLine.AppendSwitchIfNotNull("/keycontainer:", KeyContainer); commandLine.AppendSwitchIfNotNull("/keyfile:", KeyFile); // If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject. commandLine.AppendSwitchIfNotNull("/linkresource:", LinkResources, new string[] { "LogicalName", "Access" }); commandLine.AppendWhenTrue("/nologo", _store, nameof(NoLogo)); commandLine.AppendWhenTrue("/nowin32manifest", _store, nameof(NoWin32Manifest)); commandLine.AppendPlusOrMinusSwitch("/optimize", _store, nameof(Optimize)); commandLine.AppendSwitchIfNotNull("/pathmap:", PathMap); commandLine.AppendSwitchIfNotNull("/out:", OutputAssembly); commandLine.AppendSwitchIfNotNull("/ruleset:", CodeAnalysisRuleSet); commandLine.AppendSwitchIfNotNull("/errorlog:", ErrorLog); commandLine.AppendSwitchIfNotNull("/subsystemversion:", SubsystemVersion); commandLine.AppendWhenTrue("/reportanalyzer", _store, nameof(ReportAnalyzer)); // If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject. commandLine.AppendSwitchIfNotNull("/resource:", Resources, new string[] { "LogicalName", "Access" }); commandLine.AppendSwitchIfNotNull("/target:", TargetType); commandLine.AppendPlusOrMinusSwitch("/warnaserror", _store, nameof(TreatWarningsAsErrors)); commandLine.AppendWhenTrue("/utf8output", _store, nameof(Utf8Output)); commandLine.AppendSwitchIfNotNull("/win32icon:", Win32Icon); commandLine.AppendSwitchIfNotNull("/win32manifest:", Win32Manifest); AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(commandLine); AddAnalyzersToCommandLine(commandLine, Analyzers); AddAdditionalFilesToCommandLine(commandLine); // Append the sources. commandLine.AppendFileNamesIfNotNull(Sources, " "); } internal void AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(CommandLineBuilderExtension commandLine) { commandLine.AppendPlusOrMinusSwitch("/deterministic", _store, nameof(Deterministic)); commandLine.AppendPlusOrMinusSwitch("/publicsign", _store, nameof(PublicSign)); commandLine.AppendSwitchIfNotNull("/runtimemetadataversion:", RuntimeMetadataVersion); commandLine.AppendSwitchIfNotNull("/checksumalgorithm:", ChecksumAlgorithm); commandLine.AppendSwitchIfNotNull("/instrument:", Instrument); commandLine.AppendSwitchIfNotNull("/sourcelink:", SourceLink); AddFeatures(commandLine, Features); } /// <summary> /// Adds a "/features:" switch to the command line for each provided feature. /// </summary> internal static void AddFeatures(CommandLineBuilderExtension commandLine, string features) { if (string.IsNullOrEmpty(features)) { return; } foreach (var feature in CompilerOptionParseUtilities.ParseFeatureFromMSBuild(features)) { commandLine.AppendSwitchIfNotNull("/features:", feature.Trim()); } } /// <summary> /// Adds a "/analyzer:" switch to the command line for each provided analyzer. /// </summary> internal static void AddAnalyzersToCommandLine(CommandLineBuilderExtension commandLine, ITaskItem[] analyzers) { // If there were no analyzers passed in, don't add any /analyzer: switches // on the command-line. if (analyzers == null) { return; } foreach (ITaskItem analyzer in analyzers) { commandLine.AppendSwitchIfNotNull("/analyzer:", analyzer.ItemSpec); } } /// <summary> /// Adds a "/additionalfile:" switch to the command line for each additional file. /// </summary> private void AddAdditionalFilesToCommandLine(CommandLineBuilderExtension commandLine) { // If there were no additional files passed in, don't add any /additionalfile: switches // on the command-line. if (AdditionalFiles == null) { return; } foreach (ITaskItem additionalFile in AdditionalFiles) { commandLine.AppendSwitchIfNotNull("/additionalfile:", additionalFile.ItemSpec); } } /// <summary> /// Configure the debug switches which will be placed on the compiler command-line. /// The matrix of debug type and symbol inputs and the desired results is as follows: /// /// Debug Symbols DebugType Desired Results /// True Full /debug+ /debug:full /// True PdbOnly /debug+ /debug:PdbOnly /// True None /debug- /// True Blank /debug+ /// False Full /debug- /debug:full /// False PdbOnly /debug- /debug:PdbOnly /// False None /debug- /// False Blank /debug- /// Blank Full /debug:full /// Blank PdbOnly /debug:PdbOnly /// Blank None /debug- /// Debug: Blank Blank /debug+ //Microsoft.common.targets will set this /// Release: Blank Blank "Nothing for either switch" /// /// The logic is as follows: /// If debugtype is none set debugtype to empty and debugSymbols to false /// If debugType is blank use the debugsymbols "as is" /// If debug type is set, use its value and the debugsymbols value "as is" /// </summary> private void ConfigureDebugProperties() { // If debug type is set we need to take some action depending on the value. If debugtype is not set // We don't need to modify the EmitDebugInformation switch as its value will be used as is. if (_store[nameof(DebugType)] != null) { // If debugtype is none then only show debug- else use the debug type and the debugsymbols as is. if (string.Compare((string)_store[nameof(DebugType)], "none", StringComparison.OrdinalIgnoreCase) == 0) { _store[nameof(DebugType)] = null; _store[nameof(EmitDebugInformation)] = false; } } } /// <summary> /// Validate parameters, log errors and warnings and return true if /// Execute should proceed. /// </summary> protected override bool ValidateParameters() { return ListHasNoDuplicateItems(Resources, nameof(Resources), "LogicalName", Log) && ListHasNoDuplicateItems(Sources, nameof(Sources), Log); } /// <summary> /// Returns true if the provided item list contains duplicate items, false otherwise. /// </summary> internal static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, TaskLoggingHelper log) { return ListHasNoDuplicateItems(itemList, parameterName, null, log); } /// <summary> /// Returns true if the provided item list contains duplicate items, false otherwise. /// </summary> /// <param name="itemList"></param> /// <param name="disambiguatingMetadataName">Optional name of metadata that may legitimately disambiguate items. May be null.</param> /// <param name="parameterName"></param> /// <param name="log"></param> private static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, string disambiguatingMetadataName, TaskLoggingHelper log) { if (itemList == null || itemList.Length == 0) { return true; } Hashtable alreadySeen = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (ITaskItem item in itemList) { string key; string disambiguatingMetadataValue = null; if (disambiguatingMetadataName != null) { disambiguatingMetadataValue = item.GetMetadata(disambiguatingMetadataName); } if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue)) { key = item.ItemSpec; } else { key = item.ItemSpec + ":" + disambiguatingMetadataValue; } if (alreadySeen.ContainsKey(key)) { if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue)) { log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupported", item.ItemSpec, parameterName); } else { log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupportedWithMetadata", item.ItemSpec, parameterName, disambiguatingMetadataValue, disambiguatingMetadataName); } return false; } else { alreadySeen[key] = string.Empty; } } return true; } /// <summary> /// Allows tool to handle the return code. /// This method will only be called with non-zero exitCode. /// </summary> protected override bool HandleTaskExecutionErrors() { // For managed compilers, the compiler should emit the appropriate // error messages before returning a non-zero exit code, so we don't // normally need to emit any additional messages now. // // If somehow the compiler DID return a non-zero exit code and didn't log an error, we'd like to log that exit code. // We can only do this for the command line compiler: if the inproc compiler was used, // we can't tell what if anything it logged as it logs directly to Visual Studio's output window. // if (!Log.HasLoggedErrors && UsedCommandLineTool) { // This will log a message "MSB3093: The command exited with code {0}." base.HandleTaskExecutionErrors(); } return false; } /// <summary> /// Takes a list of files and returns the normalized locations of these files /// </summary> private void NormalizePaths(ITaskItem[] taskItems) { foreach (var item in taskItems) { item.ItemSpec = Utilities.GetFullPathNoThrow(item.ItemSpec); } } /// <summary> /// Whether the command line compiler was invoked, instead /// of the host object compiler. /// </summary> protected bool UsedCommandLineTool { get; set; } private bool _hostCompilerSupportsAllParameters; protected bool HostCompilerSupportsAllParameters { get { return _hostCompilerSupportsAllParameters; } set { _hostCompilerSupportsAllParameters = value; } } /// <summary> /// Checks the bool result from calling one of the methods on the host compiler object to /// set one of the parameters. If it returned false, that means the host object doesn't /// support a particular parameter or variation on a parameter. So we log a comment, /// and set our state so we know not to call the host object to do the actual compilation. /// </summary> /// <owner>RGoel</owner> protected void CheckHostObjectSupport ( string parameterName, bool resultFromHostObjectSetOperation ) { if (!resultFromHostObjectSetOperation) { Log.LogMessageFromResources(MessageImportance.Normal, "General_ParameterUnsupportedOnHostCompiler", parameterName); _hostCompilerSupportsAllParameters = false; } } internal void InitializeHostObjectSupportForNewSwitches(ITaskHost hostObject, ref string param) { var compilerOptionsHostObject = hostObject as ICompilerOptionsHostObject; if (compilerOptionsHostObject != null) { var commandLineBuilder = new CommandLineBuilderExtension(); AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(commandLineBuilder); param = "CompilerOptions"; CheckHostObjectSupport(param, compilerOptionsHostObject.SetCompilerOptions(commandLineBuilder.ToString())); } } /// <summary> /// Checks to see whether all of the passed-in references exist on disk before we launch the compiler. /// </summary> /// <owner>RGoel</owner> protected bool CheckAllReferencesExistOnDisk() { if (null == References) { // No references return true; } bool success = true; foreach (ITaskItem reference in References) { if (!File.Exists(reference.ItemSpec)) { success = false; Log.LogErrorWithCodeFromResources("General_ReferenceDoesNotExist", reference.ItemSpec); } } return success; } /// <summary> /// The IDE and command line compilers unfortunately differ in how win32 /// manifests are specified. In particular, the command line compiler offers a /// "/nowin32manifest" switch, while the IDE compiler does not offer analogous /// functionality. If this switch is omitted from the command line and no win32 /// manifest is specified, the compiler will include a default win32 manifest /// named "default.win32manifest" found in the same directory as the compiler /// executable. Again, the IDE compiler does not offer analogous support. /// /// We'd like to imitate the command line compiler's behavior in the IDE, but /// it isn't aware of the default file, so we must compute the path to it if /// noDefaultWin32Manifest is false and no win32Manifest was provided by the /// project. /// /// This method will only be called during the initialization of the host object, /// which is only used during IDE builds. /// </summary> /// <returns>the path to the win32 manifest to provide to the host object</returns> internal string GetWin32ManifestSwitch ( bool noDefaultWin32Manifest, string win32Manifest ) { if (!noDefaultWin32Manifest) { if (string.IsNullOrEmpty(win32Manifest) && string.IsNullOrEmpty(Win32Resource)) { // We only want to consider the default.win32manifest if this is an executable if (!string.Equals(TargetType, "library", StringComparison.OrdinalIgnoreCase) && !string.Equals(TargetType, "module", StringComparison.OrdinalIgnoreCase)) { // We need to compute the path to the default win32 manifest string pathToDefaultManifest = ToolLocationHelper.GetPathToDotNetFrameworkFile ( "default.win32manifest", // We are choosing to pass Version46 instead of VersionLatest. TargetDotNetFrameworkVersion // is an enum, and VersionLatest is not some sentinel value but rather a constant that is // equal to the highest version defined in the enum. Enum values, being constants, are baked // into consuming assembly, so specifying VersionLatest means not the latest version wherever // this code is running, but rather the latest version of the framework according to the // reference assembly with which this assembly was built. As of this writing, we are building // our bits on machines with Visual Studio 2015 that know about 4.6.1, so specifying // VersionLatest would bake in the enum value for 4.6.1. But we need to run on machines with // MSBuild that only know about Version46 (and no higher), so VersionLatest will fail there. // Explicitly passing Version46 prevents this problem. TargetDotNetFrameworkVersion.Version46 ); if (null == pathToDefaultManifest) { // This is rather unlikely, and the inproc compiler seems to log an error anyway. // So just a message is fine. Log.LogMessageFromResources ( "General_ExpectedFileMissing", "default.win32manifest" ); } return pathToDefaultManifest; } } } return win32Manifest; } } }
// 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.Linq; using Xunit.Abstractions; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Text.RegularExpressions; namespace System.Xml.Tests { public class LineInfo { public int LineNumber { get; private set; } public int LinePosition { get; private set; } public string FilePath { get; private set; } public LineInfo(int lineNum, int linePos) { LineNumber = lineNum; LinePosition = linePos; FilePath = string.Empty; } public LineInfo(int lineNum, int linePos, string filePath) { LineNumber = lineNum; LinePosition = linePos; FilePath = filePath; } } [Flags] public enum ExceptionVerificationFlags { None = 0, IgnoreMultipleDots = 1, IgnoreLineInfo = 2, } public class ExceptionVerifier { private readonly Assembly _asm; private Assembly _locAsm; private readonly Hashtable _resources; private string _actualMessage; private string _expectedMessage; private Exception _ex; private ExceptionVerificationFlags _verificationFlags = ExceptionVerificationFlags.None; private ITestOutputHelper _output; public bool IgnoreMultipleDots { get { return (_verificationFlags & ExceptionVerificationFlags.IgnoreMultipleDots) != 0; } set { if (value) _verificationFlags = _verificationFlags | ExceptionVerificationFlags.IgnoreMultipleDots; else _verificationFlags = _verificationFlags & (~ExceptionVerificationFlags.IgnoreMultipleDots); } } public bool IgnoreLineInfo { get { return (_verificationFlags & ExceptionVerificationFlags.IgnoreLineInfo) != 0; } set { if (value) _verificationFlags = _verificationFlags | ExceptionVerificationFlags.IgnoreLineInfo; else _verificationFlags = _verificationFlags & (~ExceptionVerificationFlags.IgnoreLineInfo); } } private const string ESCAPE_ANY = "~%anything%~"; private const string ESCAPE_NUMBER = "~%number%~"; public ExceptionVerifier(string assemblyName, ExceptionVerificationFlags flags, ITestOutputHelper output) { _output = output; if (assemblyName == null) throw new VerifyException("Assembly name cannot be null"); _verificationFlags = flags; try { switch (assemblyName.ToUpper()) { case "SYSTEM.XML": { var dom = new XmlDocument(); _asm = dom.GetType().Assembly; } break; default: _asm = Assembly.LoadFrom(GetRuntimeInstallDir() + assemblyName + ".dll"); break; } if (_asm == null) throw new VerifyException("Can not load assembly " + assemblyName); // let's determine if this is a loc run, if it is then we need to load satellite assembly _locAsm = null; if (!CultureInfo.CurrentCulture.Equals(new CultureInfo("en-US")) && !CultureInfo.CurrentCulture.Equals(new CultureInfo("en"))) { try { // load satellite assembly _locAsm = _asm.GetSatelliteAssembly(new CultureInfo(CultureInfo.CurrentCulture.Parent.IetfLanguageTag)); } catch (FileNotFoundException e1) { _output.WriteLine(e1.ToString()); } catch (FileLoadException e2) { _output.WriteLine(e2.ToString()); } } } catch (Exception e) { _output.WriteLine("Exception: " + e.Message); _output.WriteLine("Stack: " + e.StackTrace); throw new VerifyException("Error while loading assembly"); } string[] resArray; Stream resStream = null; var bFound = false; // Check that assembly manifest has resources if (null != _locAsm) resArray = _locAsm.GetManifestResourceNames(); else resArray = _asm.GetManifestResourceNames(); foreach (var s in resArray) { if (s.EndsWith(".resources")) { resStream = null != _locAsm ? _locAsm.GetManifestResourceStream(s) : _asm.GetManifestResourceStream(s); bFound = true; if (bFound && resStream != null) { // Populate hashtable from resources var resReader = new ResourceReader(resStream); if (_resources == null) { _resources = new Hashtable(); } var ide = resReader.GetEnumerator(); while (ide.MoveNext()) { if (!_resources.ContainsKey(ide.Key.ToString())) _resources.Add(ide.Key.ToString(), ide.Value.ToString()); } resReader.Dispose(); } } } if (!bFound || resStream == null) throw new VerifyException("GetManifestResourceStream() failed"); } private static string GetRuntimeInstallDir() { // Get mscorlib path var s = typeof(object).Module.FullyQualifiedName; // Remove mscorlib.dll from the path return Directory.GetParent(s).ToString() + "\\"; } public ExceptionVerifier(string assemblyName, ITestOutputHelper output) : this(assemblyName, ExceptionVerificationFlags.None, output) { } private void ExceptionInfoOutput() { // Use reflection to obtain "res" property value var exceptionType = _ex.GetType(); var fInfo = exceptionType.GetField("res", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase) ?? exceptionType.BaseType.GetField("res", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase); if (fInfo == null) throw new VerifyException("Cannot obtain Resource ID from Exception."); _output.WriteLine( "\n===== Original Exception Message =====\n" + _ex.Message + "\n===== Resource Id =====\n" + fInfo.GetValue(_ex) + "\n===== HelpLink =====\n" + _ex.HelpLink + "\n===== Source =====\n" + _ex.Source); _output.WriteLine( "\n===== InnerException =====\n" + _ex.InnerException + "\n===== StackTrace =====\n" + _ex.StackTrace); } public string[] ReturnAllMatchingResIds(string message) { var ide = _resources.GetEnumerator(); var list = new ArrayList(); _output.WriteLine("===== All mached ResIDs ====="); while (ide.MoveNext()) { var resMessage = ide.Value.ToString(); resMessage = ESCAPE_ANY + Regex.Replace(resMessage, @"\{\d*\}", ESCAPE_ANY) + ESCAPE_ANY; resMessage = MakeEscapes(resMessage).Replace(ESCAPE_ANY, ".*"); if (Regex.Match(message, resMessage, RegexOptions.Singleline).ToString() == message) { list.Add(ide.Key); _output.WriteLine(" [" + ide.Key.ToString() + "] = \"" + ide.Value.ToString() + "\""); } } return (string[])list.ToArray(typeof(string[])); } // Common helper methods used by different overloads of IsExceptionOk() private static void CheckNull(Exception e) { if (e == null) { throw new VerifyException("NULL exception passed to IsExceptionOk()"); } } private void CompareMessages() { if (IgnoreMultipleDots && _expectedMessage.EndsWith(".")) _expectedMessage = _expectedMessage.TrimEnd(new char[] { '.' }) + "."; _expectedMessage = Regex.Escape(_expectedMessage); _expectedMessage = _expectedMessage.Replace(ESCAPE_ANY, ".*"); _expectedMessage = _expectedMessage.Replace(ESCAPE_NUMBER, @"\d*"); // ignore case _expectedMessage = _expectedMessage.ToLowerInvariant(); _actualMessage = _actualMessage.ToLowerInvariant(); if (!PlatformDetection.IsNetNative) // .NET Native toolchain optimizes away exception messages. { if (Regex.Match(_actualMessage, _expectedMessage, RegexOptions.Singleline).ToString() != _actualMessage) { // Unescape before printing the expected message string _expectedMessage = Regex.Unescape(_expectedMessage); _output.WriteLine("Mismatch in error message"); _output.WriteLine("===== Expected Message =====\n" + _expectedMessage); _output.WriteLine("===== Expected Message Length =====\n" + _expectedMessage.Length); _output.WriteLine("===== Actual Message =====\n" + _actualMessage); _output.WriteLine("===== Actual Message Length =====\n" + _actualMessage.Length); throw new VerifyException("Mismatch in error message"); } } } public void IsExceptionOk(Exception e, string expectedResId) { CheckNull(e); _ex = e; if (expectedResId == null) { // Pint actual exception info and quit // This can be used to dump exception properties, verify them and then plug them into our expected results ExceptionInfoOutput(); throw new VerifyException("Did not pass resource ID to verify"); } IsExceptionOk(e, new object[] { expectedResId }); } public void IsExceptionOk(Exception e, string expectedResId, string[] paramValues) { var list = new ArrayList { expectedResId }; foreach (var param in paramValues) list.Add(param); IsExceptionOk(e, list.ToArray()); } public void IsExceptionOk(Exception e, string expectedResId, string[] paramValues, LineInfo lineInfo) { var list = new ArrayList { expectedResId, lineInfo }; foreach (var param in paramValues) list.Add(param); IsExceptionOk(e, list.ToArray()); } public void IsExceptionOk(Exception e, object[] IdsAndParams) { CheckNull(e); _ex = e; _actualMessage = e.Message; _expectedMessage = ConstructExpectedMessage(IdsAndParams); CompareMessages(); } private static string MakeEscapes(string str) { return new[] { "\\", "$", "{", "[", "(", "|", ")", "*", "+", "?" }.Aggregate(str, (current, esc) => current.Replace(esc, "\\" + esc)); } public string ConstructExpectedMessage(object[] IdsAndParams) { var lineInfoMessage = ""; var paramList = new ArrayList(); var paramsStartPosition = 1; // Verify that input list contains at least one element - ResId if (IdsAndParams.Length == 0 || !(IdsAndParams[0] is string)) throw new VerifyException("ResID at IDsAndParams[0] missing!"); string expectedResId = (IdsAndParams[0] as string); // Verify that resource id exists in resources if (!_resources.ContainsKey(expectedResId)) { ExceptionInfoOutput(); throw new VerifyException("Resources in [" + _asm.GetName().Name + "] does not contain string resource: " + expectedResId); } // If LineInfo exist, construct LineInfo message if (IdsAndParams.Length > 1 && (IdsAndParams[1] is LineInfo)) { if (!IgnoreLineInfo) { var lineInfo = (IdsAndParams[1] as LineInfo); // Xml_ErrorPosition = "Line {0}, position {1}." lineInfoMessage = string.IsNullOrEmpty(lineInfo.FilePath) ? _resources["Xml_ErrorPosition"].ToString() : _resources["Xml_ErrorFilePosition"].ToString(); var lineNumber = lineInfo.LineNumber.ToString(); var linePosition = lineInfo.LinePosition.ToString(); lineInfoMessage = string.IsNullOrEmpty(lineInfo.FilePath) ? string.Format(lineInfoMessage, lineNumber, linePosition) : string.Format(lineInfoMessage, lineInfo.FilePath, lineNumber, linePosition); } else lineInfoMessage = ESCAPE_ANY; lineInfoMessage = " " + lineInfoMessage; paramsStartPosition = 2; } string message = _resources[expectedResId].ToString(); for (var i = paramsStartPosition; i < IdsAndParams.Length; i++) { if (IdsAndParams[i] is object[]) paramList.Add(ConstructExpectedMessage(IdsAndParams[i] as object[])); else { if (IdsAndParams[i] == null) paramList.Add(ESCAPE_ANY); else paramList.Add(IdsAndParams[i] as string); } } try { message = string.Format(message, paramList.ToArray()); } catch (FormatException) { throw new VerifyException("Mismatch in number of parameters!"); } return message + lineInfoMessage; } } public class VerifyException : Exception { public VerifyException(string msg) : base(msg) { } } }
// 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.GraphModel.Schemas; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Progression; using Microsoft.VisualStudio.Shell; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal class AbstractGraphProvider : IGraphProvider { private readonly IGlyphService _glyphService; private readonly IServiceProvider _serviceProvider; private readonly GraphQueryManager _graphQueryManager; private bool _initialized = false; protected AbstractGraphProvider( IGlyphService glyphService, SVsServiceProvider serviceProvider, Workspace workspace, IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners) { _glyphService = glyphService; _serviceProvider = serviceProvider; var asyncListener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.GraphProvider); _graphQueryManager = new GraphQueryManager(workspace, asyncListener); } private void EnsureInitialized() { if (_initialized) { return; } var iconService = (IIconService)_serviceProvider.GetService(typeof(IIconService)); IconHelper.Initialize(_glyphService, iconService); _initialized = true; } internal static List<IGraphQuery> GetGraphQueries(IGraphContext context) { var graphQueries = new List<IGraphQuery>(); if (context.Direction == GraphContextDirection.Self && context.RequestedProperties.Contains(DgmlNodeProperties.ContainsChildren)) { graphQueries.Add(new ContainsChildrenGraphQuery()); } if (context.Direction == GraphContextDirection.Contains || (context.Direction == GraphContextDirection.Target && context.LinkCategories.Contains(CodeLinkCategories.Contains))) { graphQueries.Add(new ContainsGraphQuery()); } if (context.LinkCategories.Contains(CodeLinkCategories.InheritsFrom)) { if (context.Direction == GraphContextDirection.Target) { graphQueries.Add(new InheritsGraphQuery()); } else if (context.Direction == GraphContextDirection.Source) { graphQueries.Add(new InheritedByGraphQuery()); } } if (context.LinkCategories.Contains(CodeLinkCategories.SourceReferences)) { graphQueries.Add(new IsUsedByGraphQuery()); } if (context.LinkCategories.Contains(CodeLinkCategories.Calls)) { if (context.Direction == GraphContextDirection.Target) { graphQueries.Add(new CallsGraphQuery()); } else if (context.Direction == GraphContextDirection.Source) { graphQueries.Add(new IsCalledByGraphQuery()); } } if (context.LinkCategories.Contains(CodeLinkCategories.Implements)) { if (context.Direction == GraphContextDirection.Target) { graphQueries.Add(new ImplementsGraphQuery()); } else if (context.Direction == GraphContextDirection.Source) { graphQueries.Add(new ImplementedByGraphQuery()); } } if (context.LinkCategories.Contains(RoslynGraphCategories.Overrides)) { if (context.Direction == GraphContextDirection.Source) { graphQueries.Add(new OverridesGraphQuery()); } else if (context.Direction == GraphContextDirection.Target) { graphQueries.Add(new OverriddenByGraphQuery()); } } if (context.Direction == GraphContextDirection.Custom) { var searchParameters = context.GetValue<ISolutionSearchParameters>(typeof(ISolutionSearchParameters).GUID.ToString()); if (searchParameters != null) { // WARNING: searchParameters.SearchQuery returns an IVsSearchQuery object, which // is a COM type. Therefore, it's probably best to grab the values we want now // rather than get surprised by COM marshalling later. graphQueries.Add(new SearchGraphQuery(searchParameters.SearchQuery.SearchString)); } } return graphQueries; } public void BeginGetGraphData(IGraphContext context) { EnsureInitialized(); var graphQueries = GetGraphQueries(context); if (graphQueries.Count > 0) { _graphQueryManager.AddQueries(context, graphQueries); } else { // It's an unknown query type, so we're done context.OnCompleted(); } } public IEnumerable<GraphCommand> GetCommands(IEnumerable<GraphNode> nodes) { EnsureInitialized(); // Only nodes that explicitly state that they contain children (e.g., source files) and named types should // be expandable. if (nodes.Any(n => n.Properties.Any(p => p.Key == DgmlNodeProperties.ContainsChildren)) || nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType))) { yield return new GraphCommand( GraphCommandDefinition.Contains, targetCategories: null, linkCategories: new[] { GraphCommonSchema.Contains }, trackChanges: true); } // All graph commands below this point apply only to Roslyn-owned nodes. if (!nodes.All(n => IsRoslynNode(n))) { yield break; } // Only show 'Base Types' and 'Derived Types' on a class or interface. if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) && IsAnyTypeKind(n, TypeKind.Class, TypeKind.Interface, TypeKind.Struct, TypeKind.Enum, TypeKind.Delegate))) { yield return new GraphCommand( GraphCommandDefinition.BaseTypes, targetCategories: null, linkCategories: new[] { CodeLinkCategories.InheritsFrom }, trackChanges: true); yield return new GraphCommand( GraphCommandDefinition.DerivedTypes, targetCategories: null, linkCategories: new[] { CodeLinkCategories.InheritsFrom }, trackChanges: true); } // Only show 'Calls' on an applicable member in a class or struct if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property, SymbolKind.Field))) { yield return new GraphCommand( GraphCommandDefinition.Calls, targetCategories: null, linkCategories: new[] { CodeLinkCategories.Calls }, trackChanges: true); } // Only show 'Is Called By' on an applicable member in a class or struct if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) && IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct))) { yield return new GraphCommand( GraphCommandDefinition.IsCalledBy, targetCategories: null, linkCategories: new[] { CodeLinkCategories.Calls }, trackChanges: true); } // Show 'Is Used By' yield return new GraphCommand( GraphCommandDefinition.IsUsedBy, targetCategories: new[] { CodeNodeCategories.SourceLocation }, linkCategories: new[] { CodeLinkCategories.SourceReferences }, trackChanges: true); // Show 'Implements' on a class or struct, or an applicable member in a class or struct. if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) && IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct))) { yield return new GraphCommand( s_implementsCommandDefinition, targetCategories: null, linkCategories: new[] { CodeLinkCategories.Implements }, trackChanges: true); } // Show 'Implements' on public, non-static members of a class or struct. Note: we should // also show it on explicit interface impls in C#. if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) && IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) && !GetModifiers(n).IsStatic)) { if (nodes.Any(n => CheckAccessibility(n, Accessibility.Public) || HasExplicitInterfaces(n))) { yield return new GraphCommand( s_implementsCommandDefinition, targetCategories: null, linkCategories: new[] { CodeLinkCategories.Implements }, trackChanges: true); } } // Show 'Implemented By' on an interface. if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) && IsAnyTypeKind(n, TypeKind.Interface))) { yield return new GraphCommand( s_implementedByCommandDefinition, targetCategories: null, linkCategories: new[] { CodeLinkCategories.Implements }, trackChanges: true); } // Show 'Implemented By' on any member of an interface. if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) && IsAnyTypeKind(n, TypeKind.Interface))) { yield return new GraphCommand( s_implementedByCommandDefinition, targetCategories: null, linkCategories: new[] { CodeLinkCategories.Implements }, trackChanges: true); } // Show 'Overrides' on any applicable member of a class or struct if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) && IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) && GetModifiers(n).IsOverride)) { yield return new GraphCommand( s_overridesCommandDefinition, targetCategories: null, linkCategories: new[] { RoslynGraphCategories.Overrides }, trackChanges: true); } // Show 'Overridden By' on any applicable member of a class or struct if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) && IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) && IsOverridable(n))) { yield return new GraphCommand( s_overriddenByCommandDefinition, targetCategories: null, linkCategories: new[] { RoslynGraphCategories.Overrides }, trackChanges: true); } } private bool IsOverridable(GraphNode node) { var modifiers = GetModifiers(node); return (modifiers.IsVirtual || modifiers.IsAbstract || modifiers.IsOverride) && !modifiers.IsSealed; } private DeclarationModifiers GetModifiers(GraphNode node) { return (DeclarationModifiers)node[RoslynGraphProperties.SymbolModifiers]; } private bool CheckAccessibility(GraphNode node, Accessibility accessibility) { return node[RoslynGraphProperties.DeclaredAccessibility].Equals(accessibility); } private bool HasExplicitInterfaces(GraphNode node) { return ((IList<SymbolKey>)node[RoslynGraphProperties.ExplicitInterfaceImplementations]).Count > 0; } private bool IsRoslynNode(GraphNode node) { return node[RoslynGraphProperties.SymbolKind] != null && node[RoslynGraphProperties.TypeKind] != null; } private bool IsAnySymbolKind(GraphNode node, params SymbolKind[] symbolKinds) { return symbolKinds.Any(k => k.Equals(node[RoslynGraphProperties.SymbolKind])); } private bool IsAnyTypeKind(GraphNode node, params TypeKind[] typeKinds) { return typeKinds.Any(k => node[RoslynGraphProperties.TypeKind].Equals(k)); } private static readonly GraphCommandDefinition s_overridesCommandDefinition = new GraphCommandDefinition("Overrides", ServicesVSResources.Overrides, GraphContextDirection.Target, 700); private static readonly GraphCommandDefinition s_overriddenByCommandDefinition = new GraphCommandDefinition("OverriddenBy", ServicesVSResources.OverriddenBy, GraphContextDirection.Source, 700); private static readonly GraphCommandDefinition s_implementsCommandDefinition = new GraphCommandDefinition("Implements", ServicesVSResources.Implements, GraphContextDirection.Target, 600); private static readonly GraphCommandDefinition s_implementedByCommandDefinition = new GraphCommandDefinition("ImplementedBy", ServicesVSResources.ImplementedBy, GraphContextDirection.Source, 600); public T GetExtension<T>(GraphObject graphObject, T previous) where T : class { var graphNode = graphObject as GraphNode; if (graphNode != null) { // If this is not a Roslyn node, bail out. // TODO: The check here is to see if the SymbolId property exists on the node // and if so, that's been created by us. However, eventually we'll want to extend // this to other scenarios where C#\VB nodes that aren't created by us are passed in. if (graphNode.GetValue<SymbolKey?>(RoslynGraphProperties.SymbolId) == null) { return null; } if (typeof(T) == typeof(IGraphNavigateToItem)) { return new GraphNavigatorExtension(PrimaryWorkspace.Workspace) as T; } if (typeof(T) == typeof(IGraphFormattedLabel)) { return new GraphFormattedLabelExtension() as T; } } return null; } public Graph Schema { get { return null; } } } }
//--------------------------------------------------------------------------- // <copyright file="FixedPage.cs" company="Microsoft"> // Copyright (C) 2003 by Microsoft Corporation. All rights reserved. // </copyright> // // Description: // Implements the FixedPage element // // History: // 06/03/2003 - Zhenbin Xu (ZhenbinX) - Created. // // http://edocs/payloads/Payloads%20Features/FixedPanelPage.mht // //--------------------------------------------------------------------------- namespace System.Windows.Documents { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO.Packaging; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Documents.DocumentStructures; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Navigation; using System.Windows.Shapes; using MS.Internal; using MS.Internal.Documents; using MS.Internal.Utility; using BuildInfo = MS.Internal.PresentationFramework.BuildInfo; //===================================================================== /// <summary> /// FixedPage is the container element for a metafile that represents /// a single page of portable, high-fidelity content. /// /// As an object that represents a static page of content, the primary /// usage scenario for a FixedPage is inside a FixedDocument, a control /// that is specialized to represent FixedPages to the pagination architecture. /// The secondary scenario is to place a FixedPage inside a generic paginating /// control such as the FlowDocument; for this scenario, the FixedPage is configured /// to automatically set page breaks at the beginning and end of its content. /// </summary> [ContentProperty("Children")] public sealed class FixedPage : FrameworkElement, IAddChildInternal, IFixedNavigate, IUriContext { //-------------------------------------------------------------------- // // Constructors // //--------------------------------------------------------------------- #region Constructors static FixedPage() { FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata(FlowDirection.LeftToRight, FrameworkPropertyMetadataOptions.AffectsParentArrange); metadata.CoerceValueCallback = new CoerceValueCallback(CoerceFlowDirection); FlowDirectionProperty.OverrideMetadata(typeof(FixedPage), metadata); // This puts the origin always at the top left of the page and prevents mirroring unless this is overridden. } /// <summary> /// Default FixedPage constructor /// </summary> /// <remarks> /// Automatic determination of current Dispatcher. Use alternative constructor /// that accepts a Dispatcher for best performance. /// </remarks> public FixedPage() : base() { Init(); } #endregion Constructors //-------------------------------------------------------------------- // // Public Methods // //--------------------------------------------------------------------- #region Public Methods /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return new System.Windows.Automation.Peers.FixedPageAutomationPeer(this); } /// <summary> /// Responds to mouse wheel event, used to update debug visuals. /// MouseWheelEvent handler, initializes the context menu. /// </summary> protected override void OnPreviewMouseWheel(MouseWheelEventArgs e) { #if DEBUG if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) { int delta = e.Delta; e.Handled = true; if (delta > 0) { _drawDebugVisual--; } else { _drawDebugVisual++; } _drawDebugVisual = _drawDebugVisual % (int)DrawDebugVisual.LastOne; if (_drawDebugVisual < 0) { _drawDebugVisual += (int)DrawDebugVisual.LastOne; } InvalidateVisual(); // // For container, the first child of element is always a Path with Fill. // if (_uiElementCollection.Count != 0) { Path path = _uiElementCollection[0] as Path; if (path != null) { if (_drawDebugVisual == 0) { path.Visibility = Visibility.Visible; } else { path.Visibility = Visibility.Hidden; } } } } #endif } /// <summary> /// Override from UIElement /// </summary> protected override void OnRender(DrawingContext dc) { // Draw background in rectangle inside border. Brush background = this.Background; if (background != null) { dc.DrawRectangle(background, null, new Rect(0, 0, RenderSize.Width, RenderSize.Height)); } #if DEBUG AdornerLayer al = AdornerLayer.GetAdornerLayer(this); if (al != null) { Adorner[] adorners = al.GetAdorners(this); if (adorners != null && adorners.Length > 0) { al.Update(this); } } #endif } ///<summary> /// This method is called to Add the object as a child of the Panel. This method is used primarily /// by the parser. ///</summary> /// <exception cref="ArgumentNullException">value is NULL.</exception> /// <exception cref="ArgumentException">value is not of type UIElement.</exception> ///<param name="value"> /// The object to add as a child; it must be a UIElement. ///</param> /// <ExternalAPI/> void IAddChild.AddChild (Object value) { if (value == null) { throw new ArgumentNullException("value"); } UIElement uie = value as UIElement; if (uie == null) { throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(UIElement)), "value"); } Children.Add(uie); } ///<summary> /// This method is called by the parser when text appears under the tag in markup. /// As default Panels do not support text, calling this method has no effect if the /// text is all whitespace. Passing non-whitespace text throws an exception. ///</summary> /// <exception cref="ArgumentException">text contains non-whitespace text.</exception> ///<param name="text"> /// Text to add as a child. ///</param> void IAddChild.AddText (string text) { XamlSerializerUtil.ThrowIfNonWhiteSpaceInAddText(text, this); } /// <summary> /// Reads the attached property Left from the given element. /// </summary> /// <exception cref="ArgumentNullException">element is NULL.</exception> /// <param name="element">The element from which to read the Left attached property.</param> /// <returns>The property's Length value.</returns> /// <seealso cref="Canvas.LeftProperty" /> [TypeConverter("System.Windows.LengthConverter, PresentationFramework, Version=" + BuildInfo.WCP_VERSION + ", Culture=neutral, PublicKeyToken=" + BuildInfo.WCP_PUBLIC_KEY_TOKEN + ", Custom=null")] [AttachedPropertyBrowsableForChildren()] public static double GetLeft(UIElement element) { if (element == null) { throw new ArgumentNullException("element"); } return (double)element.GetValue(LeftProperty); } /// <summary> /// Writes the attached property Left to the given element. /// </summary> /// <exception cref="ArgumentNullException">element is NULL.</exception> /// <param name="element">The element to which to write the Left attached property.</param> /// <param name="length">The Length to set</param> /// <seealso cref="Canvas.LeftProperty" /> public static void SetLeft(UIElement element, double length) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(LeftProperty, length); } /// <summary> /// Reads the attached property Top from the given element. /// </summary> /// <exception cref="ArgumentNullException">element is NULL.</exception> /// <param name="element">The element from which to read the Top attached property.</param> /// <returns>The property's Length value.</returns> /// <seealso cref="Canvas.TopProperty" /> [TypeConverter("System.Windows.LengthConverter, PresentationFramework, Version=" + BuildInfo.WCP_VERSION + ", Culture=neutral, PublicKeyToken=" + BuildInfo.WCP_PUBLIC_KEY_TOKEN + ", Custom=null")] [AttachedPropertyBrowsableForChildren()] public static double GetTop(UIElement element) { if (element == null) { throw new ArgumentNullException("element"); } return (double)element.GetValue(TopProperty); } /// <summary> /// Writes the attached property Top to the given element. /// </summary> /// <exception cref="ArgumentNullException">element is NULL.</exception> /// <param name="element">The element to which to write the Top attached property.</param> /// <param name="length">The Length to set</param> /// <seealso cref="Canvas.TopProperty" /> public static void SetTop(UIElement element, double length) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(TopProperty, length); } /// <summary> /// Reads the attached property Right from the given element. /// </summary> /// <exception cref="ArgumentNullException">element is NULL.</exception> /// <param name="element">The element from which to read the Right attached property.</param> /// <returns>The property's Length value.</returns> /// <seealso cref="Canvas.RightProperty" /> [TypeConverter("System.Windows.LengthConverter, PresentationFramework, Version=" + BuildInfo.WCP_VERSION + ", Culture=neutral, PublicKeyToken=" + BuildInfo.WCP_PUBLIC_KEY_TOKEN + ", Custom=null")] [AttachedPropertyBrowsableForChildren()] public static double GetRight(UIElement element) { if (element == null) { throw new ArgumentNullException("element"); } return (double)element.GetValue(RightProperty); } /// <summary> /// Writes the attached property Right to the given element. /// </summary> /// <exception cref="ArgumentNullException">element is NULL.</exception> /// <param name="element">The element to which to write the Right attached property.</param> /// <param name="length">The Length to set</param> /// <seealso cref="Canvas.RightProperty" /> public static void SetRight(UIElement element, double length) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(RightProperty, length); } /// <summary> /// Reads the attached property Bottom from the given element. /// </summary> /// <exception cref="ArgumentNullException">element is NULL.</exception> /// <param name="element">The element from which to read the Bottom attached property.</param> /// <returns>The property's Length value.</returns> /// <seealso cref="Canvas.BottomProperty" /> [TypeConverter("System.Windows.LengthConverter, PresentationFramework, Version=" + BuildInfo.WCP_VERSION + ", Culture=neutral, PublicKeyToken=" + BuildInfo.WCP_PUBLIC_KEY_TOKEN + ", Custom=null")] [AttachedPropertyBrowsableForChildren()] public static double GetBottom(UIElement element) { if (element == null) { throw new ArgumentNullException("element"); } return (double)element.GetValue(BottomProperty); } /// <summary> /// Writes the attached property Bottom to the given element. /// </summary> /// <exception cref="ArgumentNullException">element is NULL.</exception> /// <param name="element">The element to which to write the Bottom attached property.</param> /// <param name="length">The Length to set</param> /// <seealso cref="Canvas.BottomProperty" /> public static void SetBottom(UIElement element, double length) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(BottomProperty, length); } /// <summary> /// Reads the attached property NavigateUri from the given element. /// </summary> /// <exception cref="ArgumentNullException">element is NULL.</exception> /// <remarks>Should be kept here for compatibility since the attached property has moved from FixedPage to Hyperlink.</remarks> [AttachedPropertyBrowsableForChildren()] public static Uri GetNavigateUri(UIElement element) { if (element == null) { throw new ArgumentNullException("element"); } return (Uri)element.GetValue(NavigateUriProperty); } /// <summary> /// Writes the attached property NavigateUri to the given element. /// </summary> /// <exception cref="ArgumentNullException">element is NULL.</exception> /// <remarks>Should be kept here for compatibility since the attached property has moved from FixedPage to Hyperlink.</remarks> public static void SetNavigateUri(UIElement element, Uri uri) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(NavigateUriProperty, uri); } #endregion #region IUriContext /// <summary> /// <see cref="IUriContext.BaseUri" /> /// </summary> Uri IUriContext.BaseUri { get { return (Uri) GetValue(BaseUriHelper.BaseUriProperty); } set { SetValue(BaseUriHelper.BaseUriProperty, value); } } /// <summary> /// Returns enumerator to logical children. /// </summary> protected internal override IEnumerator LogicalChildren { get { return this.Children.GetEnumerator(); } } #endregion IUriContext //-------------------------------------------------------------------- // // Public Properties // //--------------------------------------------------------------------- #region Public Properties /// <summary> /// Returns a UIElementCollection of children for user to add/remove children manually /// Returns null if Panel is data-bound (no manual control of children is possible, /// the associated ItemsControl completely overrides children) /// Note: the derived Panel classes should never use this collection for any /// internal purposes! They should use Children instead, because Children /// is always present and either is a mirror of public Children collection (in case of Direct Panel) /// or is generated from data binding. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public UIElementCollection Children { get { if(_uiElementCollection == null) //nobody used it yet { _uiElementCollection = CreateUIElementCollection(this); } return _uiElementCollection; } } /// <summary> /// /// </summary> public static readonly DependencyProperty PrintTicketProperty = DependencyProperty.RegisterAttached( "PrintTicket", typeof(object), typeof(FixedPage), new FrameworkPropertyMetadata((object)null)); /// <summary> /// Get/Set PrintTicket Property /// </summary> public object PrintTicket { get { return GetValue(PrintTicketProperty); } set { SetValue(PrintTicketProperty,value); } } /// <summary> /// The Background property defines the brush used to fill the area between borders. /// </summary> public Brush Background { get { return (Brush) GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } /// <summary> /// DependencyProperty for <see cref="Background" /> property. /// </summary> public static readonly DependencyProperty BackgroundProperty = Panel.BackgroundProperty.AddOwner( typeof(FixedPage), new FrameworkPropertyMetadata((Brush)Brushes.White, FrameworkPropertyMetadataOptions.AffectsRender)); /// <summary> /// This is the dependency property registered for the Canvas' Left attached property. /// /// The Left property is read by a Canvas on its children to determine where to position them. /// The child's offset from this property does not have an effect on the Canvas' own size. /// If you want offset to affect size, set the child's Margin property instead. /// Conflict between the Left and Right properties is resolved in favor of Left. /// Percentages are with respect to the Canvas' size. /// </summary> /// <seealso cref="FrameworkElement.Margin" /> public static readonly DependencyProperty LeftProperty = DependencyProperty.RegisterAttached( "Left", typeof(double), typeof(FixedPage), new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsParentArrange)); /// <summary> /// This is the dependency property registered for the Canvas' Top attached property. /// /// The Top property is read by a Canvas on its children to determine where to position them. /// The child's offset from this property does not have an effect on the Canvas' own size. /// If you want offset to affect size, set the child's Margin property instead. /// Conflict between the Top and Bottom properties is resolved in favor of Top. /// Percentages are with respect to the Canvas' size. /// </summary> /// <seealso cref="FrameworkElement.Margin" /> public static readonly DependencyProperty TopProperty = DependencyProperty.RegisterAttached( "Top", typeof(double), typeof(FixedPage), new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsParentArrange)); /// <summary> /// This is the dependency property registered for the Canvas' Right attached property. /// /// The Right property is read by a Canvas on its children to determine where to position them. /// The child's offset from this property does not have an effect on the Canvas' own size. /// If you want offset to affect size, set the child's Margin property instead. /// Conflict between the Left and Right properties is resolved in favor of Right. /// Percentages are with respect to the Canvas' size. /// </summary> /// <seealso cref="FrameworkElement.Margin" /> public static readonly DependencyProperty RightProperty = DependencyProperty.RegisterAttached( "Right", typeof(double), typeof(FixedPage), new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsParentArrange)); /// <summary> /// This is the dependency property registered for the Canvas' Bottom attached property. /// /// The Bottom property is read by a Canvas on its children to determine where to position them. /// The child's offset from this property does not have an effect on the Canvas' own size. /// If you want offset to affect size, set the child's Margin property instead. /// Conflict between the Top and Bottom properties is resolved in favor of Bottom. /// Percentages are with respect to the Canvas' size. /// </summary> /// <seealso cref="FrameworkElement.Margin" /> public static readonly DependencyProperty BottomProperty = DependencyProperty.RegisterAttached( "Bottom", typeof(double), typeof(FixedPage), new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsParentArrange)); /// <summary> /// The DependencyProperty for the ContentBox property. /// </summary> public Rect ContentBox { get { return (Rect) GetValue(ContentBoxProperty); } set { SetValue(ContentBoxProperty, value); } } /// <summary> /// The DependencyProperty for the ContentBox property. /// </summary> public static readonly DependencyProperty ContentBoxProperty = DependencyProperty.Register( "ContentBox", typeof(Rect), typeof(FixedPage), new FrameworkPropertyMetadata(Rect.Empty)); /// <summary> /// The DependencyProperty for the BleedBox property. /// </summary> public Rect BleedBox { get { return (Rect) GetValue(BleedBoxProperty); } set { SetValue(BleedBoxProperty, value); } } /// <summary> /// The DependencyProperty for the BleedBox property. /// </summary> public static readonly DependencyProperty BleedBoxProperty = DependencyProperty.Register( "BleedBox", typeof(Rect), typeof(FixedPage), new FrameworkPropertyMetadata(Rect.Empty)); /// <summary> /// Contains the target URI to navigate when a hyperlink is clicked /// </summary> public static readonly DependencyProperty NavigateUriProperty = DependencyProperty.RegisterAttached( "NavigateUri", typeof(Uri), typeof(FixedPage), new FrameworkPropertyMetadata( (Uri) null, new PropertyChangedCallback(Hyperlink.OnNavigateUriChanged), new CoerceValueCallback(Hyperlink.CoerceNavigateUri))); #endregion protected internal override void OnVisualParentChanged(DependencyObject oldParent) { base.OnVisualParentChanged(oldParent); if (oldParent == null) { HighlightVisual highlightVisual = HighlightVisual.GetHighlightVisual(this); AdornerLayer al = AdornerLayer.GetAdornerLayer(this); if (highlightVisual == null && al != null) { //Get Page Content PageContent pc = LogicalTreeHelper.GetParent(this) as PageContent; if (pc != null) { //Get FixedDocument FixedDocument doc = LogicalTreeHelper.GetParent(pc) as FixedDocument; if (doc != null) { if (al != null) { //The Text Selection adorner must have predefined ZOrder MaxInt/2, //we assign the ZOrder to annotation adorners respectively int zOrder = System.Int32.MaxValue / 2; al.Add(new HighlightVisual(doc, this),zOrder); } } } } #if DEBUG DebugVisualAdorner debugVisualAd = DebugVisualAdorner.GetDebugVisual(this); if (debugVisualAd == null && al != null) { al.Add(new DebugVisualAdorner(this), System.Int32.MaxValue / 4); } #endif } } private static object CoerceFlowDirection(DependencyObject page, Object flowDirection) { return FlowDirection.LeftToRight; } internal static bool CanNavigateToUri(Uri uri) { // Is http:, https:, mailto:, or file:? if (!uri.IsAbsoluteUri || uri.IsUnc || uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeMailto || // Automation will request navigation to pack Uris when automating links withing a document (uri.Scheme == PackUriHelper.UriSchemePack && !String.IsNullOrEmpty(uri.Fragment))) { return true; } else { return SecurityHelper.CallerHasWebPermission(uri); } } internal static Uri GetLinkUri(IInputElement element, Uri inputUri) { DependencyObject dpo = element as DependencyObject; Debug.Assert(dpo != null, "GetLinkUri shouldn't be called for non-DependencyObjects."); if (inputUri != null && (CanNavigateToUri(inputUri) || (inputUri.Scheme == PackUriHelper.UriSchemePack && !String.IsNullOrEmpty(inputUri.Fragment)))) // We want to allow navigation to pack:// Uris as we may get these from automation, but we // wouldn't support this if an actual Uri were given as a pack:// Uri { // // First remove the fragment, this is to prevent escape in file URI case, for example, // if the inputUri = "..\..\myFile.xaml#fragment", without removing the fragment first, // the absoluteUri would be "file:///...../myFile.xaml%23fragment", note # is escaped to // %23. // If indeed the file contains # such as "This#File.xaml", it should set // FixedPage.NavigateUri="This%23File.xaml" // // // Copy from BindUriHelper.GetFragment STARTS. // It should have a version return #, otherwise, you can // not tell betweeen myFile.xaml and myFile.xaml# // Uri workuri = inputUri; if (inputUri.IsAbsoluteUri == false) { // this is a relative uri, and Fragement() doesn't work with relative uris. The base uri is completley irrelevant // here and will never affect the returned fragment, but the method requires something to be there. Therefore, // we will use "http://microsoft.com" as a convenient substitute. workuri = new Uri(new Uri("http://microsoft.com/"), inputUri); } // Copy from BindUriHelper.GetFragment ENDS. // the fragmene will include # sign String fragment = workuri.Fragment; int fragmentLength = (fragment == null) ? 0 : fragment.Length; if (fragmentLength != 0) { String inputUriString = inputUri.ToString(); String inputUriStringWithoutFragment = inputUriString.Substring(0, inputUriString.IndexOf('#')); inputUri = new Uri(inputUriStringWithoutFragment, UriKind.RelativeOrAbsolute); //Only Check for the startpart uri if the hyperlink is relative, else it's not part of the package if (inputUri.IsAbsoluteUri == false) { String startPartUriString = GetStartPartUriString(dpo); if (startPartUriString != null) { inputUri = new Uri(startPartUriString, UriKind.RelativeOrAbsolute); } } } // // Resolve to absolute URI // Uri baseUri = BaseUriHelper.GetBaseUri(dpo); Uri absoluteUri = BindUriHelper.GetUriToNavigate(dpo, baseUri, inputUri); if (fragmentLength != 0) { StringBuilder absoluteUriString = new StringBuilder(absoluteUri.ToString()); absoluteUriString.Append(fragment); absoluteUri = new Uri(absoluteUriString.ToString(), UriKind.RelativeOrAbsolute); } return absoluteUri; } return null; } //-------------------------------------------------------------------- // // Public Events // //--------------------------------------------------------------------- //-------------------------------------------------------------------- // // Protected Methods // //--------------------------------------------------------------------- #region Protected Methods /// <summary> /// Gets the Visual children count. /// </summary> protected override int VisualChildrenCount { get { if (_uiElementCollection == null) { return 0; } else { return _uiElementCollection.Count; } } } /// <summary> /// Gets the Visual child at the specified index. /// </summary> protected override Visual GetVisualChild(int index) { if (_uiElementCollection == null) { throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } return _uiElementCollection[index]; } /// <summary> /// Creates a new UIElementCollection. Panel-derived class can create its own version of /// UIElementCollection -derived class to add cached information to every child or to /// intercept any Add/Remove actions (for example, for incremental layout update) /// </summary> private UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent) { return new UIElementCollection(this, logicalParent); } /// <summary> /// Updates DesiredSize of the Canvas. Called by parent UIElement. This is the first pass of layout. /// </summary> /// <remarks> /// Canvas measures each of its children accounting for any of their FrameworkElement properties. /// Children will be passed either the parent's constraint less any margin on the child or their /// explicitly specified (Min/Max)Width/Height properties. /// /// If it has enough space, Canvas will return a size large enough to accommodate all children's /// desired sizes and margins. Children's Top/Left/Bottom/Right properties are not considered in /// this method. If it does not have enough space to accommodate its children in a dimension, this /// will simply return the full constraint in that dimension. /// </remarks> /// <param name="constraint">Constraint size is an "upper limit" that Canvas should not exceed.</param> /// <returns>Canvas' desired size.</returns> protected override Size MeasureOverride(Size constraint) { Size childConstraint = new Size(Double.PositiveInfinity, Double.PositiveInfinity); foreach (UIElement child in Children) { child.Measure(childConstraint); } return new Size(); } /// <summary> /// Canvas computes a position for each of its children taking into account their margin and /// attached Canvas properties: Top, Left, Bottom, and Right. If specified, Top or Left take /// priority over Bottom or Right. /// /// Canvas will also arrange each of its children. /// </summary> /// <param name="arrangeSize">Size that Canvas will assume to position children.</param> protected override Size ArrangeOverride(Size arrangeSize) { //Canvas arranges children at their DesiredSize. //This means that Margin on children is actually respected and added //to the size of layout partition for a child. //Therefore, is Margin is 10 and Left is 20, the child's ink will start at 30. foreach (UIElement child in Children) { double x = 0; double y = 0; //Compute offset of the child: //If Left is specified, then Right is ignored //If Left is not specified, then Right is used //If both are not there, then 0 double left = GetLeft(child); if(!DoubleUtil.IsNaN(left)) { x = left; } else { double right = GetRight(child); if(!DoubleUtil.IsNaN(right)) { x = arrangeSize.Width - child.DesiredSize.Width - right; } } double top = GetTop(child); if(!DoubleUtil.IsNaN(top)) { y = top; } else { double bottom = GetBottom(child); if(!DoubleUtil.IsNaN(bottom)) { y = arrangeSize.Height - child.DesiredSize.Height - bottom; } } child.Arrange(new Rect(new Point(x, y), child.DesiredSize)); } return arrangeSize; } #endregion //-------------------------------------------------------------------- // // Internal Methods // //--------------------------------------------------------------------- #region Internal methods void IFixedNavigate.NavigateAsync(string elementID) { FixedHyperLink.NavigateToElement(this, elementID); } UIElement IFixedNavigate.FindElementByID(string elementID, out FixedPage rootFixedPage) { UIElement uiElementRet = null; rootFixedPage = this; // We need iterate through the PageContentCollect first. UIElementCollection elementCollection = this.Children; UIElement uiElement; DependencyObject node ; for (int i = 0, n = elementCollection.Count; i < n; i++) { uiElement = elementCollection[i]; node = LogicalTreeHelper.FindLogicalNode(uiElement, elementID); if (node != null) { uiElementRet = node as UIElement; break; } } return uiElementRet; } // Create a FixedNode representing this glyphs or image internal FixedNode CreateFixedNode(int pageIndex, UIElement e) { // Should we check here to make sure this is a selectable element? Debug.Assert(e != null); return _CreateFixedNode(pageIndex, e); } internal Glyphs GetGlyphsElement(FixedNode node) { return GetElement(node) as Glyphs; } // FixedNode represents a leaf node. It contains a path // from root to the leaf in the form of child index. // [Level1 ChildIndex] [Level2 ChildIndex] [Level3 ChildIndex]... internal DependencyObject GetElement(FixedNode node) { int currentLevelIndex = node[1]; if (!(currentLevelIndex >= 0 && currentLevelIndex <= this.Children.Count)) { return null; } #if DEBUG if (node.ChildLevels > 1) { DocumentsTrace.FixedFormat.FixedDocument.Trace(string.Format("FixedPage.GetUIElement {0} is nested element", node)); } #endif DependencyObject element = this.Children[currentLevelIndex]; for (int level = 2; level <= node.ChildLevels; level++) { // Follow the path if necessary currentLevelIndex = node[level]; if (element is Canvas) { // Canvas is a known S0 grouping element. // Boundary Node only would appear in first level! Debug.Assert(currentLevelIndex >= 0 && currentLevelIndex <= ((Canvas)element).Children.Count); element = ((Canvas)element).Children[currentLevelIndex]; } else { DocumentsTrace.FixedFormat.FixedDocument.Trace(string.Format("FixedPage.GeElement {0} is non S0 grouping element in L[{1}]!", node, level)); IEnumerable currentChildrens = LogicalTreeHelper.GetChildren((DependencyObject)element); if (currentChildrens == null) { DocumentsTrace.FixedFormat.FixedDocument.Trace(string.Format("FixedPage.GetElement {0} is NOT a grouping element in L[{1}]!!!", node, level)); return null; } // We have no uniform way to do random access for this element. // This should never happen for S0 conforming document. int childIndex = -1; IEnumerator itor = currentChildrens.GetEnumerator(); while (itor.MoveNext()) { childIndex++; if (childIndex == currentLevelIndex) { element = (DependencyObject)itor.Current; break; } } } } #if DEBUG if (!(element is Glyphs)) { DocumentsTrace.FixedFormat.FixedDocument.Trace(string.Format("FixedPage.GetElement{0} is non-Glyphs", node)); } #endif return element; } #endregion Internal Methods #region Internal Properties internal String StartPartUriString { get { return _startPartUriString; } set { _startPartUriString = value; } } private String _startPartUriString; #if DEBUG internal FixedPageStructure FixedPageStructure { get { return _fixedPageStructure; } set { _fixedPageStructure = value; } } internal int DrawDebugVisualSelection { get { return _drawDebugVisual; } } #endif #endregion Internal Properties //-------------------------------------------------------------------- // // private Properties // //--------------------------------------------------------------------- private UIElementCollection _uiElementCollection; //-------------------------------------------------------------------- // // Private Methods // //--------------------------------------------------------------------- #region Private Methods private void Init() { if (XpsValidatingLoader.DocumentMode) { this.InheritanceBehavior = InheritanceBehavior.SkipAllNext; } } internal StoryFragments GetPageStructure() { StoryFragments sf; sf = FixedDocument.GetStoryFragments(this); return sf; } internal int[] _CreateChildIndex(DependencyObject e) { ArrayList childPath = new ArrayList(); while (e != this) { DependencyObject parent = LogicalTreeHelper.GetParent(e); int childIndex = -1; if (parent is FixedPage) { childIndex = ((FixedPage)parent).Children.IndexOf((UIElement)e); } else if (parent is Canvas) { childIndex = ((Canvas)parent).Children.IndexOf((UIElement)e); } else { IEnumerable currentChildrens = LogicalTreeHelper.GetChildren(parent); Debug.Assert(currentChildrens != null); // We have no uniform way to do random access for this element. // This should never happen for S0 conforming document. IEnumerator itor = currentChildrens.GetEnumerator(); while (itor.MoveNext()) { childIndex++; if (itor.Current == e) { break; } } } childPath.Insert(0, childIndex); e = parent; } while (e != this) ; return (int[])childPath.ToArray(typeof(int)); } // Making this function private and only expose the versions // that take S0 elements as parameter. private FixedNode _CreateFixedNode(int pageIndex, UIElement e) { return FixedNode.Create(pageIndex, _CreateChildIndex(e)); } /// <summary> /// This function walks the logical tree for the FixedDocumentSequence and then /// retrieves its URI. We use this Uri for fragment navigation during a FixedPage.OnClick /// event. /// </summary> /// <param name="current"></param> /// <returns></returns> private static String GetStartPartUriString(DependencyObject current) { //1) Get FixedPage from DependcyObject's InheritanceObject property DependencyObject obj = current; FixedPage fixedPage = current as FixedPage; while (fixedPage == null && obj != null) { obj = obj.InheritanceParent; fixedPage = obj as FixedPage; } if (fixedPage == null) { return null; } //2) Check if fixedPage StartPartUri is null if (fixedPage.StartPartUriString == null) { //3) Walk Logical Tree to the FixedDocumentSequence DependencyObject parent = LogicalTreeHelper.GetParent(current); while (parent != null) { FixedDocumentSequence docSequence = parent as FixedDocumentSequence; if (docSequence != null) { //4) Retrieve DocumentSequence Uri Uri startPartUri = ((IUriContext)docSequence).BaseUri; if (startPartUri != null) { String startPartUriString = startPartUri.ToString(); // If there is a fragment we need to strip it off String fragment = startPartUri.Fragment; int fragmentLength = (fragment == null) ? 0 : fragment.Length; if (fragmentLength != 0) { fixedPage.StartPartUriString = startPartUriString.Substring(0, startPartUriString.IndexOf('#')); } else { fixedPage.StartPartUriString = startPartUri.ToString(); } } break; } parent = LogicalTreeHelper.GetParent(parent); } //If we don't have a starting part Uri, assign fixedPage.StartPartUriString to Empty so //we don't try to look it up again. if (fixedPage.StartPartUriString == null) { fixedPage.StartPartUriString = String.Empty; } } if (fixedPage.StartPartUriString == String.Empty) { return null; } else { return fixedPage.StartPartUriString; } } #endregion //-------------------------------------------------------------------- // // Private Fields // //--------------------------------------------------------------------- #if DEBUG private FixedPageStructure _fixedPageStructure; // // The debugging features: set to true will draw the bounding box for each // line from the analyzed layout results. // private int _drawDebugVisual = 0; #endif } #if DEBUG internal sealed class DebugVisualAdorner: Adorner { internal DebugVisualAdorner(FixedPage page) : base(page) { _fixedPage = page; } override protected void OnRender(DrawingContext dc) { if (_fixedPage.DrawDebugVisualSelection == (int) DrawDebugVisual.None) { return; } FixedPageStructure pageStructure = _fixedPage.FixedPageStructure; Debug.Assert(pageStructure != null); if (_fixedPage.DrawDebugVisualSelection == (int) DrawDebugVisual.Glyphs) { if (pageStructure.FixedNodes != null) { _RenderMarkupOrder(dc, pageStructure.FixedNodes); } } else if (_fixedPage.DrawDebugVisualSelection == (int) DrawDebugVisual.Lines) { pageStructure.RenderLines(dc); } else { if (pageStructure.FixedSOMPage != null) { pageStructure.FixedSOMPage.Render(dc, null, (DrawDebugVisual) _fixedPage.DrawDebugVisualSelection); } else { //Explicit document structure FlowNode[] pageNodes = _fixedPage.FixedPageStructure.FlowNodes; int flowOrder = 0; foreach (FlowNode node in pageNodes) { if (node != null && node.FixedSOMElements != null) { foreach (FixedSOMElement somElement in node.FixedSOMElements) { somElement.Render(dc, flowOrder.ToString(), (DrawDebugVisual) _fixedPage.DrawDebugVisualSelection); flowOrder++; } } } } } } internal static DebugVisualAdorner GetDebugVisual(FixedPage page) { AdornerLayer al = AdornerLayer.GetAdornerLayer(page); DebugVisualAdorner debugVisualAd; if (al == null) { return null; } Adorner[] adorners = al.GetAdorners(page); if (adorners != null) { foreach (Adorner ad in adorners) { debugVisualAd = ad as DebugVisualAdorner; if (debugVisualAd != null) { return debugVisualAd; } } } return null; } private void _RenderMarkupOrder(DrawingContext dc, List<FixedNode> markupOrder) { int order = 0; foreach (FixedNode node in markupOrder) { DependencyObject ob = _fixedPage.GetElement(node); Glyphs glyphs = ob as Glyphs; Path path = ob as Path; if (glyphs != null) { GlyphRun glyphRun = glyphs.ToGlyphRun(); Rect alignmentBox = glyphRun.ComputeAlignmentBox(); alignmentBox.Offset(glyphs.OriginX, glyphs.OriginY); GeneralTransform transform = glyphs.TransformToAncestor(_fixedPage); alignmentBox = transform.TransformBounds(alignmentBox); Pen pen = new Pen(Brushes.Green, 1); dc.DrawRectangle(null, pen , alignmentBox); _RenderLabel(dc, order.ToString(), alignmentBox); ++order; } else if (path != null) { Geometry renderGeom = path.RenderedGeometry; Pen backgroundPen = new Pen(Brushes.Black,1); dc.DrawGeometry(null, backgroundPen, renderGeom); _RenderLabel(dc, order.ToString(), renderGeom.Bounds); ++order; } } } private void _RenderLabel(DrawingContext dc, string label, Rect boundingRect) { FormattedText ft = new FormattedText(label, System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS, FlowDirection.LeftToRight, new Typeface("Arial"), 10, Brushes.White); Point labelLocation = new Point(boundingRect.Left-25, (boundingRect.Bottom + boundingRect.Top)/2 - 10); Geometry geom = ft.BuildHighlightGeometry(labelLocation); Pen backgroundPen = new Pen(Brushes.Black,1); dc.DrawGeometry(Brushes.Black, backgroundPen, geom); dc.DrawText(ft, labelLocation); } private FixedPage _fixedPage; } internal enum DrawDebugVisual { None = 0, Glyphs = 1, Lines = 2, TextRuns = 3, Paragraphs = 4, Groups = 5, LastOne = 6 } #endif }
using System; using UnityEngine; using System.Collections; using System.Collections.Generic; public class FTmxMap : FContainer { private List<XMLNode> _tilesets; protected List<string> _layerNames; private FNode _clipNode; // for tilemaps public int objectStartInt = 1; public FTmxMap () { _tilesets = new List<XMLNode>(); _layerNames = new List<string>(); } public void LoadTMX(string fileName) { // load xml document TextAsset dataAsset = (TextAsset) Resources.Load (fileName, typeof(TextAsset)); if(!dataAsset) { Debug.Log ("FTiledScene: Couldn't load the xml data from: " + fileName); } string fileContents = dataAsset.ToString(); Resources.UnloadAsset(dataAsset); // parse xml string XMLReader parser = new XMLReader(); XMLNode xmlNode = parser.read(fileContents); XMLNode rootNode = xmlNode.children[0] as XMLNode; // loop through all children foreach (XMLNode child in rootNode.children) { // save references to tilesets if (child.tagName == "tileset") { _tilesets.Add(child); } // create FTilemap for layer nodes if (child.tagName == "layer" && child.children.Count > 0) { AddChild(this.createTilemap(child)); } // create FContainers for layer nodes if (child.tagName == "objectgroup") { AddChild(this.createObjectLayer(child)); } } } protected string getTilesetNameForID(int num) { if (_tilesets.Count < 1) { Debug.Log("FTiledScene: No Tilesets found."); return ""; } XMLNode wantedNode = _tilesets[0]; // loop through tilesets foreach (XMLNode node in _tilesets) { // check if node attribute firstgid >= num int firstID = int.Parse (node.attributes["firstgid"]); if (firstID <= num) { wantedNode = node; } } // return the name of the file from wantedNode XMLNode imageNode = wantedNode.children[0] as XMLNode; string sourceString = imageNode.attributes["source"]; int startIndex = sourceString.LastIndexOf('/') + 1; string returnValue = sourceString.Substring( startIndex , sourceString.LastIndexOf('.') - startIndex); return returnValue; } protected string getTilesetExtensionForID(int num) { if (_tilesets.Count < 1) { Debug.Log("FTiledScene: No Tilesets found."); return ""; } XMLNode wantedNode = _tilesets[0]; // loop through tilesets foreach (XMLNode node in _tilesets) { // check if node attribute firstgid >= num int firstID = int.Parse (node.attributes["firstgid"]); if (firstID <= num) { wantedNode = node; } } // return the extension of the file from wantedNode XMLNode imageNode = wantedNode.children[0] as XMLNode; string sourceString = imageNode.attributes["source"]; int startIndex = sourceString.LastIndexOf('.') + 1; string returnValue = sourceString.Substring( startIndex ); return returnValue; } protected int getTilesetFirstIDForID(int num) { if (_tilesets.Count < 1) { Debug.Log("FTiledScene: No Tilesets found."); return -1; } XMLNode wantedNode = _tilesets[0]; // loop through tilesets foreach (XMLNode node in _tilesets) { // check if node attribute firstgid >= num int firstID = int.Parse (node.attributes["firstgid"]); if (firstID <= num) { wantedNode = node; } } // return the firstgid of the file from wantedNode int startIndex = int.Parse (wantedNode.attributes["firstgid"]); return startIndex; } virtual protected FNode createObjectLayer(XMLNode node) { // add objects to FContainers FContainer objectGroup = new FContainer(); foreach (XMLNode fObject in node.children) { if (fObject.tagName == "object") { if (fObject.attributes.ContainsKey("gid")) { // create FSprite (override that function for specific class changes) objectGroup.AddChild(this.createTileObject(fObject)); } else { FNode newObject = this.createObject(fObject); if (newObject != null) { objectGroup.AddChild(newObject); } } } } // remember name _layerNames.Add (node.attributes["name"]); // add to self return objectGroup; } virtual protected FNode createTilemap(XMLNode node) { XMLNode csvData = new XMLNode(); XMLNode properties = new XMLNode(); foreach (XMLNode child in node.children) { if (child.tagName == "data") { csvData = child; } else if (child.tagName == "properties") { properties = child; } } // make sure encoding is set to csv if (csvData.attributes["encoding"] != "csv") { Debug.Log ("FTiledScene: Could not render layer data, encoding set to: " + csvData.attributes["encoding"]); return null; } // remember name _layerNames.Add (node.attributes["name"]); // skipZero, if this is true all filled tiles will be drawn without clipping bool skipZero = false; // do stuff with properties foreach (XMLNode property in properties.children) { // check each property if (property.attributes["name"] == "skipZero") { skipZero = bool.Parse(property.attributes["value"]); } } // get text for csv data string csvText = csvData.value; string firstFrame = csvText.Substring( 0, csvText.IndexOf(',') ); int firstID = int.Parse(firstFrame); // find name of tileset being used, assumes all tiles are from the same tileset string baseName = this.getTilesetNameForID(firstID); // create tilemap FTilemap tilemap = new FTilemap(baseName); if (!skipZero) { tilemap.clipToScreen = true; tilemap.clipNode = _clipNode; } tilemap.LoadText(csvText, skipZero); return tilemap; } virtual protected FNode createTileObject(XMLNode node) { // get id numbers needed int id = int.Parse(node.attributes["gid"]); int firstID = this.getTilesetFirstIDForID(id); // find parts of source image string baseName = this.getTilesetNameForID(id); int actualFrame = id - firstID + objectStartInt; // assemble whole name string name = baseName + "_" + actualFrame; // get x,y int givenX = int.Parse(node.attributes["x"]); int givenY = int.Parse(node.attributes["y"]); FSprite sprite = new FSprite(name); sprite.x = givenX + sprite.width / 2; sprite.y = -givenY + sprite.height / 2; return sprite; } virtual protected FNode createObject(XMLNode node) { // type string type = node.attributes["type"]; // get x,y int givenX = int.Parse(node.attributes["x"]); int givenY = int.Parse(node.attributes["y"]); // remove extension from type int startIndex = type.LastIndexOf('/') + 1; int endIndex = type.LastIndexOf('.'); int length = endIndex - startIndex; if (length < 0) { length = type.Length - startIndex; } string spriteElement = type.Substring( startIndex , length); FSprite sprite = new FSprite(spriteElement); sprite.x = givenX + sprite.width / 2; sprite.y = -givenY + sprite.height / 2; return sprite; } public FNode getLayerNamed(string name) { int i = 0; foreach (string check in _layerNames) { if (check == name) { return GetChildAt(i); } i++; } // Debug.Log("No layer named " + name + " found."); return null; } public FNode clipNode { get { return _clipNode; } set { _clipNode = value; } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System { public static class __Enum { public static IObservable<Tuple<System.Boolean, TEnum>> TryParse<TEnum>(IObservable<System.String> value) where TEnum : struct { return Observable.Select(value, (valueLambda) => { TEnum resultOutput = default(TEnum); var result = System.Enum.TryParse(valueLambda, out resultOutput); return Tuple.Create(result, resultOutput); }); } public static IObservable<Tuple<System.Boolean, TEnum>> TryParse<TEnum>(IObservable<System.String> value, IObservable<System.Boolean> ignoreCase) where TEnum : struct { return Observable.Zip(value, ignoreCase, (valueLambda, ignoreCaseLambda) => { TEnum resultOutput = default(TEnum); var result = System.Enum.TryParse(valueLambda, ignoreCaseLambda, out resultOutput); return Tuple.Create(result, resultOutput); }); } public static IObservable<System.Object> Parse(IObservable<System.Type> enumType, IObservable<System.String> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.Parse(enumTypeLambda, valueLambda)); } public static IObservable<System.Object> Parse(IObservable<System.Type> enumType, IObservable<System.String> value, IObservable<System.Boolean> ignoreCase) { return Observable.Zip(enumType, value, ignoreCase, (enumTypeLambda, valueLambda, ignoreCaseLambda) => System.Enum.Parse(enumTypeLambda, valueLambda, ignoreCaseLambda)); } public static IObservable<System.Type> GetUnderlyingType(IObservable<System.Type> enumType) { return Observable.Select(enumType, (enumTypeLambda) => System.Enum.GetUnderlyingType(enumTypeLambda)); } public static IObservable<System.Array> GetValues(IObservable<System.Type> enumType) { return Observable.Select(enumType, (enumTypeLambda) => System.Enum.GetValues(enumTypeLambda)); } public static IObservable<System.String> GetName(IObservable<System.Type> enumType, IObservable<System.Object> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.GetName(enumTypeLambda, valueLambda)); } public static IObservable<System.String[]> GetNames(IObservable<System.Type> enumType) { return Observable.Select(enumType, (enumTypeLambda) => System.Enum.GetNames(enumTypeLambda)); } public static IObservable<System.Object> ToObject(IObservable<System.Type> enumType, IObservable<System.Object> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.ToObject(enumTypeLambda, valueLambda)); } public static IObservable<System.Boolean> IsDefined(IObservable<System.Type> enumType, IObservable<System.Object> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.IsDefined(enumTypeLambda, valueLambda)); } public static IObservable<System.String> Format(IObservable<System.Type> enumType, IObservable<System.Object> value, IObservable<System.String> format) { return Observable.Zip(enumType, value, format, (enumTypeLambda, valueLambda, formatLambda) => System.Enum.Format(enumTypeLambda, valueLambda, formatLambda)); } public static IObservable<System.Boolean> Equals(this IObservable<System.Enum> EnumValue, IObservable<System.Object> obj) { return Observable.Zip(EnumValue, obj, (EnumValueLambda, objLambda) => EnumValueLambda.Equals(objLambda)); } public static IObservable<System.Int32> GetHashCode(this IObservable<System.Enum> EnumValue) { return Observable.Select(EnumValue, (EnumValueLambda) => EnumValueLambda.GetHashCode()); } public static IObservable<System.String> ToString(this IObservable<System.Enum> EnumValue) { return Observable.Select(EnumValue, (EnumValueLambda) => EnumValueLambda.ToString()); } public static IObservable<System.String> ToString(this IObservable<System.Enum> EnumValue, IObservable<System.String> format, IObservable<System.IFormatProvider> provider) { return Observable.Zip(EnumValue, format, provider, (EnumValueLambda, formatLambda, providerLambda) => EnumValueLambda.ToString(formatLambda, providerLambda)); } public static IObservable<System.Int32> CompareTo(this IObservable<System.Enum> EnumValue, IObservable<System.Object> target) { return Observable.Zip(EnumValue, target, (EnumValueLambda, targetLambda) => EnumValueLambda.CompareTo(targetLambda)); } public static IObservable<System.String> ToString(this IObservable<System.Enum> EnumValue, IObservable<System.String> format) { return Observable.Zip(EnumValue, format, (EnumValueLambda, formatLambda) => EnumValueLambda.ToString(formatLambda)); } public static IObservable<System.String> ToString(this IObservable<System.Enum> EnumValue, IObservable<System.IFormatProvider> provider) { return Observable.Zip(EnumValue, provider, (EnumValueLambda, providerLambda) => EnumValueLambda.ToString(providerLambda)); } public static IObservable<System.Boolean> HasFlag(this IObservable<System.Enum> EnumValue, IObservable<System.Enum> flag) { return Observable.Zip(EnumValue, flag, (EnumValueLambda, flagLambda) => EnumValueLambda.HasFlag(flagLambda)); } public static IObservable<System.TypeCode> GetTypeCode(this IObservable<System.Enum> EnumValue) { return Observable.Select(EnumValue, (EnumValueLambda) => EnumValueLambda.GetTypeCode()); } public static IObservable<System.Object> ToObject(IObservable<System.Type> enumType, IObservable<System.SByte> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.ToObject(enumTypeLambda, valueLambda)); } public static IObservable<System.Object> ToObject(IObservable<System.Type> enumType, IObservable<System.Int16> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.ToObject(enumTypeLambda, valueLambda)); } public static IObservable<System.Object> ToObject(IObservable<System.Type> enumType, IObservable<System.Int32> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.ToObject(enumTypeLambda, valueLambda)); } public static IObservable<System.Object> ToObject(IObservable<System.Type> enumType, IObservable<System.Byte> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.ToObject(enumTypeLambda, valueLambda)); } public static IObservable<System.Object> ToObject(IObservable<System.Type> enumType, IObservable<System.UInt16> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.ToObject(enumTypeLambda, valueLambda)); } public static IObservable<System.Object> ToObject(IObservable<System.Type> enumType, IObservable<System.UInt32> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.ToObject(enumTypeLambda, valueLambda)); } public static IObservable<System.Object> ToObject(IObservable<System.Type> enumType, IObservable<System.Int64> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.ToObject(enumTypeLambda, valueLambda)); } public static IObservable<System.Object> ToObject(IObservable<System.Type> enumType, IObservable<System.UInt64> value) { return Observable.Zip(enumType, value, (enumTypeLambda, valueLambda) => System.Enum.ToObject(enumTypeLambda, valueLambda)); } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERLevel; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G05_SubContinent_Child (editable child object).<br/> /// This is a generated base class of <see cref="G05_SubContinent_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="G04_SubContinent"/> collection. /// </remarks> [Serializable] public partial class G05_SubContinent_Child : BusinessBase<G05_SubContinent_Child> { #region State Fields [NotUndoable] private byte[] _rowVersion = new byte[] {}; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Sub Continent Child Name"); /// <summary> /// Gets or sets the Sub Continent Child Name. /// </summary> /// <value>The Sub Continent Child Name.</value> public string SubContinent_Child_Name { get { return GetProperty(SubContinent_Child_NameProperty); } set { SetProperty(SubContinent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G05_SubContinent_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="G05_SubContinent_Child"/> object.</returns> internal static G05_SubContinent_Child NewG05_SubContinent_Child() { return DataPortal.CreateChild<G05_SubContinent_Child>(); } /// <summary> /// Factory method. Loads a <see cref="G05_SubContinent_Child"/> object, based on given parameters. /// </summary> /// <param name="parentSubContinent_ID1">The ParentSubContinent_ID1 parameter of the G05_SubContinent_Child to fetch.</param> /// <returns>A reference to the fetched <see cref="G05_SubContinent_Child"/> object.</returns> internal static G05_SubContinent_Child GetG05_SubContinent_Child(int parentSubContinent_ID1) { return DataPortal.FetchChild<G05_SubContinent_Child>(parentSubContinent_ID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G05_SubContinent_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G05_SubContinent_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G05_SubContinent_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G05_SubContinent_Child"/> object from the database, based on given criteria. /// </summary> /// <param name="parentSubContinent_ID1">The Parent Sub Continent ID1.</param> protected void Child_Fetch(int parentSubContinent_ID1) { var args = new DataPortalHookArgs(parentSubContinent_ID1); OnFetchPre(args); using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var dal = dalManager.GetProvider<IG05_SubContinent_ChildDal>(); var data = dal.Fetch(parentSubContinent_ID1); Fetch(data); } OnFetchPost(args); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="G05_SubContinent_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name")); _rowVersion = dr.GetValue("RowVersion") as byte[]; var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="G05_SubContinent_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G04_SubContinent parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IG05_SubContinent_ChildDal>(); using (BypassPropertyChecks) { _rowVersion = dal.Insert( parent.SubContinent_ID, SubContinent_Child_Name ); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="G05_SubContinent_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(G04_SubContinent parent) { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IG05_SubContinent_ChildDal>(); using (BypassPropertyChecks) { _rowVersion = dal.Update( parent.SubContinent_ID, SubContinent_Child_Name, _rowVersion ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="G05_SubContinent_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(G04_SubContinent parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IG05_SubContinent_ChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.SubContinent_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright 2019 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.Graphics; using Android.Graphics.Drawables; using Android.OS; using Android.Widget; using ArcGISRuntime.Samples.Managers; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Portal; using Esri.ArcGISRuntime.Tasks.Offline; using Esri.ArcGISRuntime.UI.Controls; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Debug = System.Diagnostics.Debug; using Path = System.IO.Path; namespace ArcGISRuntimeXamarin.Samples.DownloadPreplannedMap { [Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Download preplanned map area", category: "Map", description: "Take a map offline using a preplanned map area.", instructions: "Select a map area from the Preplanned Map Areas list. Tap the button to download the selected area. The download progress will be shown in the Downloads list. When a download is complete, select it to display the offline map in the map view.", tags: new[] { "map area", "offline", "pre-planned", "preplanned" })] public class DownloadPreplannedMap : Activity { // Hold references to the UI controls. private MapView _myMapView; private LinearLayout _mapListView; private AlertDialog _progressView; private ProgressBar _progressBar; private TextView _helpLabel; private Button _showOnlineButton; // ID of a web map with preplanned map areas. private const string PortalItemId = "acc027394bc84c2fb04d1ed317aac674"; // Folder to store the downloaded mobile map packages. private string _offlineDataFolder; // Task for taking map areas offline. private OfflineMapTask _offlineMapTask; // Hold onto the original map. private Map _originalMap; // Hold a list of available map areas. private readonly List<PreplannedMapArea> _mapAreas = new List<PreplannedMapArea>(); // Most recently opened map package. private MobileMapPackage _mobileMapPackage; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Download a preplanned map area"; CreateLayout(); Initialize(); } private async void Initialize() { try { // The data manager provides a method to get a suitable offline data folder. _offlineDataFolder = Path.Combine(DataManager.GetDataFolder(), "SampleData", "DownloadPreplannedMapAreas"); // If temporary data folder doesn't exists, create it. if (!Directory.Exists(_offlineDataFolder)) { Directory.CreateDirectory(_offlineDataFolder); } // Create a portal to enable access to the portal item. ArcGISPortal portal = await ArcGISPortal.CreateAsync(); // Create the portal item from the portal item ID. PortalItem webMapItem = await PortalItem.CreateAsync(portal, PortalItemId); // Show the map. _originalMap = new Map(webMapItem); _myMapView.Map = _originalMap; // Create an offline map task for the web map item. _offlineMapTask = await OfflineMapTask.CreateAsync(webMapItem); // Find the available preplanned map areas. IReadOnlyList<PreplannedMapArea> preplannedAreas = await _offlineMapTask.GetPreplannedMapAreasAsync(); // Load each item, then add it to the list of areas. foreach (PreplannedMapArea area in preplannedAreas) { await area.LoadAsync(); _mapAreas.Add(area); } // Show the map areas in the UI. ConfigureMapsButtons(); // Hide the loading indicator. _progressView.Dismiss(); } catch (Exception ex) { // Something unexpected happened, show the error message. Debug.WriteLine(ex); new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("There was an error.").Show(); } } private void ShowOnlineClick(object sender, EventArgs e) { // Show the map. _myMapView.Map = _originalMap; // Disable the button. _showOnlineButton.Enabled = false; } private async Task DownloadMapAreaAsync(PreplannedMapArea mapArea) { // Close the current mobile package. _mobileMapPackage?.Close(); // Set up UI for downloading. _progressBar.SetProgress(0, false); _progressView.SetMessage("Downloading map area..."); _progressView.Show(); // Create folder path where the map package will be downloaded. string path = Path.Combine(_offlineDataFolder, mapArea.PortalItem.Title); // If the area is already downloaded, open it. if (Directory.Exists(path)) { try { // Open the offline map package. _mobileMapPackage = await MobileMapPackage.OpenAsync(path); // Open the first map in the package. _myMapView.Map = _mobileMapPackage.Maps.First(); // Update the UI. _progressView.SetMessage(""); _progressView.Dismiss(); _helpLabel.Text = "Opened offline area."; return; } catch (Exception e) { Debug.WriteLine(e); new AlertDialog.Builder(this).SetMessage(e.Message).SetTitle("Couldn't open offline area. Proceeding to take area offline.").Show(); } } // Create download parameters. DownloadPreplannedOfflineMapParameters parameters = await _offlineMapTask.CreateDefaultDownloadPreplannedOfflineMapParametersAsync(mapArea); // Set the update mode to not receive updates. parameters.UpdateMode = PreplannedUpdateMode.NoUpdates; // Create the job. DownloadPreplannedOfflineMapJob job = _offlineMapTask.DownloadPreplannedOfflineMap(parameters, path); // Set up event to update the progress bar while the job is in progress. job.ProgressChanged += OnJobProgressChanged; try { // Download the area. DownloadPreplannedOfflineMapResult results = await job.GetResultAsync(); // Set the update mode to not receive updates. parameters.UpdateMode = PreplannedUpdateMode.NoUpdates; // Handle possible errors and show them to the user. if (results.HasErrors) { // Accumulate all layer and table errors into a single message. string errors = ""; foreach (KeyValuePair<Layer, Exception> layerError in results.LayerErrors) { errors = $"{errors}\n{layerError.Key.Name} {layerError.Value.Message}"; } foreach (KeyValuePair<FeatureTable, Exception> tableError in results.TableErrors) { errors = $"{errors}\n{tableError.Key.TableName} {tableError.Value.Message}"; } // Show the message. new AlertDialog.Builder(this).SetMessage(errors).SetTitle("Warning!").Show(); } // Show the downloaded map. _myMapView.Map = results.OfflineMap; // Update the UI. _helpLabel.Text = "Downloaded offline area."; _showOnlineButton.Enabled = true; } catch (Exception ex) { // Report any errors. Debug.WriteLine(ex); new AlertDialog.Builder(this).SetMessage(ex.Message).SetTitle("Downloading map area failed.").Show(); } finally { _progressBar.SetProgress(0, false); _progressView.SetMessage(""); _progressView.Dismiss(); } } private void OnJobProgressChanged(object sender, EventArgs e) { // Because the event is raised on a background thread, the dispatcher must be used to // ensure that UI updates happen on the UI thread. RunOnUiThread(() => { // Update the UI with the progress. DownloadPreplannedOfflineMapJob downloadJob = sender as DownloadPreplannedOfflineMapJob; _progressBar.SetProgress(downloadJob.Progress, true); _progressView.SetMessage($"{downloadJob.Progress}%"); }); } private void DeleteButtonOnClick(object sender, EventArgs e) { try { // Set up UI for downloading. _progressView.SetMessage("Deleting map areas..."); _progressView.Show(); // Reset the map. _myMapView.Map = _originalMap; // Close the current mobile package. _mobileMapPackage?.Close(); // Delete all data from the temporary data folder. Directory.Delete(_offlineDataFolder, true); Directory.CreateDirectory(_offlineDataFolder); // Update the UI. _helpLabel.Text = "Deleted offline areas."; _showOnlineButton.Enabled = false; } catch (Exception ex) { // Report the error. Debug.WriteLine(ex); new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Deleting map areas failed.").Show(); } finally { _progressView.Dismiss(); } } private void CreateLayout() { // Create a new vertical layout for the app. LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Add a help label. _helpLabel = new TextView(this); _helpLabel.Text = "Select a map area to take offline."; layout.AddView(_helpLabel); // Add space for adding options for each map. _mapListView = new LinearLayout(this) { Orientation = Orientation.Horizontal }; layout.AddView(_mapListView); // Create a new layout for the buttons. LinearLayout buttonLayout = new LinearLayout(this) { Orientation = Orientation.Horizontal }; // Add button for deleting map areas. Button deleteButton = new Button(this) { Text = "Delete offline areas" }; deleteButton.Click += DeleteButtonOnClick; buttonLayout.AddView(deleteButton); // Add button for showing the original map. _showOnlineButton = new Button(this) { Text = "Show online map", Enabled = false }; _showOnlineButton.Click += ShowOnlineClick; buttonLayout.AddView(_showOnlineButton); // Add the buttons to the layout. layout.AddView(buttonLayout); // Add the map view to the layout. _myMapView = new MapView(this); layout.AddView(_myMapView); // Show the layout in the app. SetContentView(layout); // Create the progress dialog display. _progressBar = new ProgressBar(this); _progressBar.SetProgress(0, true); AlertDialog.Builder builder = new AlertDialog.Builder(this).SetView(_progressBar); builder.SetCancelable(true); _progressView = builder.Create(); } private async void ConfigureMapsButtons() { foreach (PreplannedMapArea mapArea in _mapAreas) { Button mapButton = new Button(this); mapButton.SetTextColor(Color.Black); mapButton.Background = Drawable.CreateFromStream(await mapArea.PortalItem.Thumbnail.GetEncodedBufferAsync(), ""); mapButton.Text = mapArea.PortalItem.Title.Substring(0, 6); mapButton.Click += async (o, e) => { await DownloadMapAreaAsync(mapArea); }; _mapListView.AddView(mapButton); LinearLayout.LayoutParams lparams = (LinearLayout.LayoutParams)mapButton.LayoutParameters; lparams.SetMargins(5, 5, 0, 5); mapButton.LayoutParameters = lparams; } } protected override void OnStop() { base.OnStop(); // Close the current mobile package. _mobileMapPackage?.Close(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// An IVisualStudioDocument which represents the secondary buffer to the workspace API. /// </summary> internal sealed class ContainedDocument : ForegroundThreadAffinitizedObject, IVisualStudioHostDocument { private const string ReturnReplacementString = @"{|r|}"; private const string NewLineReplacementString = @"{|n|}"; private const string HTML = "HTML"; private const string Razor = "Razor"; private const string XOML = "XOML"; private const char RazorExplicit = '@'; private const string CSharpRazorBlock = "{"; private const string VBRazorBlock = "code"; private const string HelperRazor = "helper"; private const string FunctionsRazor = "functions"; private static readonly EditOptions s_venusEditOptions = new EditOptions(new StringDifferenceOptions { DifferenceType = StringDifferenceTypes.Character, IgnoreTrimWhiteSpace = false }); private readonly AbstractContainedLanguage _containedLanguage; private readonly SourceCodeKind _sourceCodeKind; private readonly IComponentModel _componentModel; private readonly Workspace _workspace; private readonly ITextDifferencingSelectorService _differenceSelectorService; private readonly IOptionService _optionService; private readonly HostType _hostType; private readonly ReiteratedVersionSnapshotTracker _snapshotTracker; private readonly IFormattingRule _vbHelperFormattingRule; private readonly string _itemMoniker; public AbstractProject Project { get { return _containedLanguage.Project; } } public bool SupportsRename { get { return _hostType == HostType.Razor; } } public DocumentId Id { get; } public IReadOnlyList<string> Folders { get; } public TextLoader Loader { get; } public DocumentKey Key { get; } public ContainedDocument( AbstractContainedLanguage containedLanguage, SourceCodeKind sourceCodeKind, Workspace workspace, IVsHierarchy hierarchy, uint itemId, IComponentModel componentModel, IFormattingRule vbHelperFormattingRule) { Contract.ThrowIfNull(containedLanguage); _containedLanguage = containedLanguage; _sourceCodeKind = sourceCodeKind; _componentModel = componentModel; _workspace = workspace; _optionService = _workspace.Services.GetService<IOptionService>(); _hostType = GetHostType(); var rdt = (IVsRunningDocumentTable)componentModel.GetService<SVsServiceProvider>().GetService(typeof(SVsRunningDocumentTable)); IVsHierarchy sharedHierarchy; uint itemIdInSharedHierarchy; var isSharedHierarchy = LinkedFileUtilities.TryGetSharedHierarchyAndItemId(hierarchy, itemId, out sharedHierarchy, out itemIdInSharedHierarchy); var filePath = isSharedHierarchy ? rdt.GetMonikerForHierarchyAndItemId(sharedHierarchy, itemIdInSharedHierarchy) : rdt.GetMonikerForHierarchyAndItemId(hierarchy, itemId); // we couldn't look up the document moniker in RDT for a hierarchy/item pair // Since we only use this moniker as a key, we could fall back to something else, like the document name. if (filePath == null) { Debug.Assert(false, "Could not get the document moniker for an item in its hierarchy."); filePath = hierarchy.GetDocumentNameForHierarchyAndItemId(itemId); } if (Project.Hierarchy != null) { string moniker; Project.Hierarchy.GetCanonicalName(itemId, out moniker); _itemMoniker = moniker; } this.Key = new DocumentKey(Project, filePath); this.Id = DocumentId.CreateNewId(Project.Id, filePath); this.Folders = containedLanguage.Project.GetFolderNames(itemId); this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath); _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>(); _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer); _vbHelperFormattingRule = vbHelperFormattingRule; } private HostType GetHostType() { var projectionBuffer = _containedLanguage.DataBuffer as IProjectionBuffer; if (projectionBuffer != null) { if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(HTML))) { return HostType.HTML; } if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(Razor))) { return HostType.Razor; } } else { // XOML is set up differently. For XOML, the secondary buffer (i.e. SubjectBuffer) // is a projection buffer, while the primary buffer (i.e. DataBuffer) is not. Instead, // the primary buffer is a regular unprojected ITextBuffer with the HTML content type. if (_containedLanguage.DataBuffer.CurrentSnapshot.ContentType.IsOfType(HTML)) { return HostType.XOML; } } throw ExceptionUtilities.Unreachable; } public DocumentInfo GetInitialState() { return DocumentInfo.Create( this.Id, this.Name, folders: this.Folders, sourceCodeKind: _sourceCodeKind, loader: this.Loader, filePath: this.Key.Moniker); } public bool IsOpen { get { return true; } } #pragma warning disable 67 public event EventHandler UpdatedOnDisk; public event EventHandler<bool> Opened; public event EventHandler<bool> Closing; #pragma warning restore 67 IVisualStudioHostProject IVisualStudioHostDocument.Project { get { return this.Project; } } public ITextBuffer GetOpenTextBuffer() { return _containedLanguage.SubjectBuffer; } public SourceTextContainer GetOpenTextContainer() { return this.GetOpenTextBuffer().AsTextContainer(); } public IContentType ContentType { get { return _containedLanguage.SubjectBuffer.ContentType; } } public string Name { get { try { return Path.GetFileName(this.FilePath); } catch (ArgumentException) { return this.FilePath; } } } public SourceCodeKind SourceCodeKind { get { return _sourceCodeKind; } } public string FilePath { get { return Key.Moniker; } } public AbstractContainedLanguage ContainedLanguage { get { return _containedLanguage; } } public void Dispose() { _snapshotTracker.StopTracking(_containedLanguage.SubjectBuffer); this.ContainedLanguage.Dispose(); } public DocumentId FindProjectDocumentIdWithItemId(uint itemidInsertionPoint) { return Project.GetCurrentDocuments().SingleOrDefault(d => d.GetItemId() == itemidInsertionPoint).Id; } public uint FindItemIdOfDocument(Document document) { return Project.GetDocumentOrAdditionalDocument(document.Id).GetItemId(); } public void UpdateText(SourceText newText) { var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var originalSnapshot = subjectBuffer.CurrentSnapshot; var originalText = originalSnapshot.AsText(); var changes = newText.GetTextChanges(originalText); IEnumerable<int> affectedVisibleSpanIndices = null; var editorVisibleSpansInOriginal = SharedPools.Default<List<TextSpan>>().AllocateAndClear(); try { var originalDocument = _workspace.CurrentSolution.GetDocument(this.Id); editorVisibleSpansInOriginal.AddRange(GetEditorVisibleSpans()); var newChanges = FilterTextChanges(originalText, editorVisibleSpansInOriginal, changes).ToList(); if (newChanges.Count == 0) { // no change to apply return; } ApplyChanges(subjectBuffer, newChanges, editorVisibleSpansInOriginal, out affectedVisibleSpanIndices); AdjustIndentation(subjectBuffer, affectedVisibleSpanIndices); } finally { SharedPools.Default<HashSet<int>>().ClearAndFree((HashSet<int>)affectedVisibleSpanIndices); SharedPools.Default<List<TextSpan>>().ClearAndFree(editorVisibleSpansInOriginal); } } private IEnumerable<TextChange> FilterTextChanges(SourceText originalText, List<TextSpan> editorVisibleSpansInOriginal, IReadOnlyList<TextChange> changes) { // no visible spans or changes if (editorVisibleSpansInOriginal.Count == 0 || changes.Count == 0) { // return empty one yield break; } using (var pooledObject = SharedPools.Default<List<TextChange>>().GetPooledObject()) { var changeQueue = pooledObject.Object; changeQueue.AddRange(changes); var spanIndex = 0; var changeIndex = 0; for (; spanIndex < editorVisibleSpansInOriginal.Count; spanIndex++) { var visibleSpan = editorVisibleSpansInOriginal[spanIndex]; var visibleTextSpan = GetVisibleTextSpan(originalText, visibleSpan, uptoFirstAndLastLine: true); for (; changeIndex < changeQueue.Count; changeIndex++) { var change = changeQueue[changeIndex]; // easy case first if (change.Span.End < visibleSpan.Start) { // move to next change continue; } if (visibleSpan.End < change.Span.Start) { // move to next visible span break; } // make sure we are not replacing whitespace around start and at the end of visible span if (WhitespaceOnEdges(originalText, visibleTextSpan, change)) { continue; } if (visibleSpan.Contains(change.Span)) { yield return change; continue; } // now it is complex case where things are intersecting each other var subChanges = GetSubTextChanges(originalText, change, visibleSpan).ToList(); if (subChanges.Count > 0) { if (subChanges.Count == 1 && subChanges[0] == change) { // we can't break it. not much we can do here. just don't touch and ignore this change continue; } changeQueue.InsertRange(changeIndex + 1, subChanges); continue; } } } } } private bool WhitespaceOnEdges(SourceText text, TextSpan visibleTextSpan, TextChange change) { if (!string.IsNullOrWhiteSpace(change.NewText)) { return false; } if (change.Span.End <= visibleTextSpan.Start) { return true; } if (visibleTextSpan.End <= change.Span.Start) { return true; } return false; } private IEnumerable<TextChange> GetSubTextChanges(SourceText originalText, TextChange changeInOriginalText, TextSpan visibleSpanInOriginalText) { using (var changes = SharedPools.Default<List<TextChange>>().GetPooledObject()) { var leftText = originalText.ToString(changeInOriginalText.Span); var rightText = changeInOriginalText.NewText; var offsetInOriginalText = changeInOriginalText.Span.Start; if (TryGetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText, changes.Object)) { return changes.Object.ToList(); } return GetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText); } } private bool TryGetSubTextChanges( SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText, List<TextChange> changes) { // these are expensive. but hopely, we don't hit this as much except the boundary cases. using (var leftPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) using (var rightPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var spansInLeftText = leftPool.Object; var spansInRightText = rightPool.Object; if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText)) { for (var i = 0; i < spansInLeftText.Count; i++) { var spanInLeftText = spansInLeftText[i]; var spanInRightText = spansInRightText[i]; if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty) { continue; } var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); TextChange textChange; if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out textChange)) { changes.Add(textChange); } } return true; } return false; } } private IEnumerable<TextChange> GetSubTextChanges( SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText) { // these are expensive. but hopely, we don't hit this as much except the boundary cases. using (var leftPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject()) using (var rightPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject()) { var leftReplacementMap = leftPool.Object; var rightReplacementMap = rightPool.Object; string leftTextWithReplacement, rightTextWithReplacement; GetTextWithReplacements(leftText, rightText, leftReplacementMap, rightReplacementMap, out leftTextWithReplacement, out rightTextWithReplacement); var diffResult = DiffStrings(leftTextWithReplacement, rightTextWithReplacement); foreach (var difference in diffResult) { var spanInLeftText = AdjustSpan(diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left), leftReplacementMap); var spanInRightText = AdjustSpan(diffResult.RightDecomposition.GetSpanInOriginal(difference.Right), rightReplacementMap); var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); TextChange textChange; if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText.ToTextSpan(), out textChange)) { yield return textChange; } } } } private bool TryGetWhitespaceOnlyChanges(string leftText, string rightText, List<TextSpan> spansInLeftText, List<TextSpan> spansInRightText) { return TryGetWhitespaceGroup(leftText, spansInLeftText) && TryGetWhitespaceGroup(rightText, spansInRightText) && spansInLeftText.Count == spansInRightText.Count; } private bool TryGetWhitespaceGroup(string text, List<TextSpan> groups) { if (text.Length == 0) { groups.Add(new TextSpan(0, 0)); return true; } var start = 0; for (var i = 0; i < text.Length; i++) { var ch = text[i]; switch (ch) { case ' ': if (!TextAt(text, i - 1, ' ')) { start = i; } break; case '\r': case '\n': if (i == 0) { groups.Add(TextSpan.FromBounds(0, 0)); } else if (TextAt(text, i - 1, ' ')) { groups.Add(TextSpan.FromBounds(start, i)); } else if (TextAt(text, i - 1, '\n')) { groups.Add(TextSpan.FromBounds(start, i)); } start = i + 1; break; default: return false; } } if (start <= text.Length) { groups.Add(TextSpan.FromBounds(start, text.Length)); } return true; } private bool TextAt(string text, int index, char ch) { if (index < 0 || text.Length <= index) { return false; } return text[index] == ch; } private bool TryGetSubTextChange( SourceText originalText, TextSpan visibleSpanInOriginalText, string rightText, TextSpan spanInOriginalText, TextSpan spanInRightText, out TextChange textChange) { textChange = default(TextChange); var visibleFirstLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.Start); var visibleLastLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.End); // skip easy case // 1. things are out of visible span if (!visibleSpanInOriginalText.IntersectsWith(spanInOriginalText)) { return false; } // 2. there are no intersects var snippetInRightText = rightText.Substring(spanInRightText.Start, spanInRightText.Length); if (visibleSpanInOriginalText.Contains(spanInOriginalText) && visibleSpanInOriginalText.End != spanInOriginalText.End) { textChange = new TextChange(spanInOriginalText, snippetInRightText); return true; } // okay, more complex case. things are intersecting boundaries. var firstLineOfRightTextSnippet = snippetInRightText.GetFirstLineText(); var lastLineOfRightTextSnippet = snippetInRightText.GetLastLineText(); // there are 4 complex cases - these are all heuristic. not sure what better way I have. and the heristic is heavily based on // text differ's behavior. // 1. it is a single line if (visibleFirstLineInOriginalText.LineNumber == visibleLastLineInOriginalText.LineNumber) { // don't do anything return false; } // 2. replacement contains visible spans if (spanInOriginalText.Contains(visibleSpanInOriginalText)) { // header // don't do anything // body textChange = new TextChange( TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, visibleLastLineInOriginalText.Start), snippetInRightText.Substring(firstLineOfRightTextSnippet.Length, snippetInRightText.Length - firstLineOfRightTextSnippet.Length - lastLineOfRightTextSnippet.Length)); // footer // don't do anything return true; } // 3. replacement intersects with start if (spanInOriginalText.Start < visibleSpanInOriginalText.Start && visibleSpanInOriginalText.Start <= spanInOriginalText.End && spanInOriginalText.End < visibleSpanInOriginalText.End) { // header // don't do anything // body if (visibleFirstLineInOriginalText.EndIncludingLineBreak <= spanInOriginalText.End) { textChange = new TextChange( TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, spanInOriginalText.End), snippetInRightText.Substring(firstLineOfRightTextSnippet.Length)); return true; } return false; } // 4. replacement intersects with end if (visibleSpanInOriginalText.Start < spanInOriginalText.Start && spanInOriginalText.Start <= visibleSpanInOriginalText.End && visibleSpanInOriginalText.End <= spanInOriginalText.End) { // body if (spanInOriginalText.Start <= visibleLastLineInOriginalText.Start) { textChange = new TextChange( TextSpan.FromBounds(spanInOriginalText.Start, visibleLastLineInOriginalText.Start), snippetInRightText.Substring(0, snippetInRightText.Length - lastLineOfRightTextSnippet.Length)); return true; } // footer // don't do anything return false; } // if it got hit, then it means there is a missing case throw ExceptionUtilities.Unreachable; } private IHierarchicalDifferenceCollection DiffStrings(string leftTextWithReplacement, string rightTextWithReplacement) { var diffService = _differenceSelectorService.GetTextDifferencingService( _workspace.Services.GetLanguageServices(this.Project.Language).GetService<IContentTypeLanguageService>().GetDefaultContentType()); diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService; return diffService.DiffStrings(leftTextWithReplacement, rightTextWithReplacement, s_venusEditOptions.DifferenceOptions); } private void GetTextWithReplacements( string leftText, string rightText, List<ValueTuple<int, int>> leftReplacementMap, List<ValueTuple<int, int>> rightReplacementMap, out string leftTextWithReplacement, out string rightTextWithReplacement) { // to make diff works better, we choose replacement strings that don't appear in both texts. var returnReplacement = GetReplacementStrings(leftText, rightText, ReturnReplacementString); var newLineReplacement = GetReplacementStrings(leftText, rightText, NewLineReplacementString); leftTextWithReplacement = GetTextWithReplacementMap(leftText, returnReplacement, newLineReplacement, leftReplacementMap); rightTextWithReplacement = GetTextWithReplacementMap(rightText, returnReplacement, newLineReplacement, rightReplacementMap); } private static string GetReplacementStrings(string leftText, string rightText, string initialReplacement) { if (leftText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0) { return initialReplacement; } // okay, there is already one in the given text. const string format = "{{|{0}|{1}|{0}|}}"; for (var i = 0; true; i++) { var replacement = string.Format(format, i.ToString(), initialReplacement); if (leftText.IndexOf(replacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(replacement, StringComparison.Ordinal) < 0) { return replacement; } } } private string GetTextWithReplacementMap(string text, string returnReplacement, string newLineReplacement, List<ValueTuple<int, int>> replacementMap) { var delta = 0; var returnLength = returnReplacement.Length; var newLineLength = newLineReplacement.Length; var sb = StringBuilderPool.Allocate(); for (var i = 0; i < text.Length; i++) { var ch = text[i]; if (ch == '\r') { sb.Append(returnReplacement); delta += returnLength - 1; replacementMap.Add(ValueTuple.Create(i + delta, delta)); continue; } else if (ch == '\n') { sb.Append(newLineReplacement); delta += newLineLength - 1; replacementMap.Add(ValueTuple.Create(i + delta, delta)); continue; } sb.Append(ch); } return StringBuilderPool.ReturnAndFree(sb); } private Span AdjustSpan(Span span, List<ValueTuple<int, int>> replacementMap) { var start = span.Start; var end = span.End; for (var i = 0; i < replacementMap.Count; i++) { var positionAndDelta = replacementMap[i]; if (positionAndDelta.Item1 <= span.Start) { start = span.Start - positionAndDelta.Item2; } if (positionAndDelta.Item1 <= span.End) { end = span.End - positionAndDelta.Item2; } if (positionAndDelta.Item1 > span.End) { break; } } return Span.FromBounds(start, end); } public IEnumerable<TextSpan> GetEditorVisibleSpans() { var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var projectionDataBuffer = _containedLanguage.DataBuffer as IProjectionBuffer; if (projectionDataBuffer != null) { return projectionDataBuffer.CurrentSnapshot .GetSourceSpans() .Where(ss => ss.Snapshot.TextBuffer == subjectBuffer) .Select(s => s.Span.ToTextSpan()) .OrderBy(s => s.Start); } else { return SpecializedCollections.EmptyEnumerable<TextSpan>(); } } private static void ApplyChanges( IProjectionBuffer subjectBuffer, IEnumerable<TextChange> changes, IList<TextSpan> visibleSpansInOriginal, out IEnumerable<int> affectedVisibleSpansInNew) { using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null)) { var affectedSpans = SharedPools.Default<HashSet<int>>().AllocateAndClear(); affectedVisibleSpansInNew = affectedSpans; var currentVisibleSpanIndex = 0; foreach (var change in changes) { // Find the next visible span that either overlaps or intersects with while (currentVisibleSpanIndex < visibleSpansInOriginal.Count && visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start) { currentVisibleSpanIndex++; } // no more place to apply text changes if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count) { break; } var newText = change.NewText; var span = change.Span.ToSpan(); edit.Replace(span, newText); affectedSpans.Add(currentVisibleSpanIndex); } edit.Apply(); } } private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable<int> visibleSpanIndex) { if (!visibleSpanIndex.Any()) { return; } var snapshot = subjectBuffer.CurrentSnapshot; var document = _workspace.CurrentSolution.GetDocument(this.Id); var originalText = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); Contract.Requires(object.ReferenceEquals(originalText, snapshot.AsText())); var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer); var options = _workspace.Options .WithChangedOption(FormattingOptions.UseTabs, root.Language, !editorOptions.IsConvertTabsToSpacesEnabled()) .WithChangedOption(FormattingOptions.TabSize, root.Language, editorOptions.GetTabSize()) .WithChangedOption(FormattingOptions.IndentationSize, root.Language, editorOptions.GetIndentSize()); using (var pooledObject = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var spans = pooledObject.Object; spans.AddRange(this.GetEditorVisibleSpans()); using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null)) { foreach (var spanIndex in visibleSpanIndex) { var rule = GetBaseIndentationRule(root, originalText, spans, spanIndex); var visibleSpan = spans[spanIndex]; AdjustIndentationForSpan(document, edit, visibleSpan, rule, options); } edit.Apply(); } } } private void AdjustIndentationForSpan( Document document, ITextEdit edit, TextSpan visibleSpan, IFormattingRule baseIndentationRule, OptionSet options) { var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); using (var rulePool = SharedPools.Default<List<IFormattingRule>>().GetPooledObject()) using (var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var venusFormattingRules = rulePool.Object; var visibleSpans = spanPool.Object; venusFormattingRules.Add(baseIndentationRule); venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance); var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document)); var workspace = document.Project.Solution.Workspace; var changes = Formatter.GetFormattedTextChanges( root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) }, workspace, options, formattingRules, CancellationToken.None); visibleSpans.Add(visibleSpan); var newChanges = FilterTextChanges(document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span)); foreach (var change in newChanges) { edit.Replace(change.Span.ToSpan(), change.NewText); } } } public BaseIndentationFormattingRule GetBaseIndentationRule(SyntaxNode root, SourceText text, List<TextSpan> spans, int spanIndex) { if (_hostType == HostType.Razor) { var currentSpanIndex = spanIndex; TextSpan visibleSpan; TextSpan visibleTextSpan; GetVisibleAndTextSpan(text, spans, currentSpanIndex, out visibleSpan, out visibleTextSpan); var end = visibleSpan.End; var current = root.FindToken(visibleTextSpan.Start).Parent; while (current != null) { if (current.Span.Start == visibleTextSpan.Start) { var blockType = GetRazorCodeBlockType(visibleSpan.Start); if (blockType == RazorCodeBlockType.Explicit) { var baseIndentation = GetBaseIndentation(root, text, visibleSpan); return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule); } } if (current.Span.Start < visibleSpan.Start) { var blockType = GetRazorCodeBlockType(visibleSpan.Start); if (blockType == RazorCodeBlockType.Block || blockType == RazorCodeBlockType.Helper) { var baseIndentation = GetBaseIndentation(root, text, visibleSpan); return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule); } if (currentSpanIndex == 0) { break; } GetVisibleAndTextSpan(text, spans, --currentSpanIndex, out visibleSpan, out visibleTextSpan); continue; } current = current.Parent; } } var span = spans[spanIndex]; var indentation = GetBaseIndentation(root, text, span); return new BaseIndentationFormattingRule(root, span, indentation, _vbHelperFormattingRule); } private void GetVisibleAndTextSpan(SourceText text, List<TextSpan> spans, int spanIndex, out TextSpan visibleSpan, out TextSpan visibleTextSpan) { visibleSpan = spans[spanIndex]; visibleTextSpan = GetVisibleTextSpan(text, visibleSpan); if (visibleTextSpan.IsEmpty) { // span has no text in them visibleTextSpan = visibleSpan; } } private int GetBaseIndentation(SyntaxNode root, SourceText text, TextSpan span) { // Is this right? We should probably get this from the IVsContainedLanguageHost instead. var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer); var additionalIndentation = GetAdditionalIndentation(root, text, span); string baseIndentationString; int parent, indentSize, useTabs = 0, tabSize = 0; // Skip over the first line, since it's in "Venus space" anyway. var startingLine = text.Lines.GetLineFromPosition(span.Start); for (var line = startingLine; line.Start < span.End; line = text.Lines[line.LineNumber + 1]) { Marshal.ThrowExceptionForHR( this.ContainedLanguage.ContainedLanguageHost.GetLineIndent( line.LineNumber, out baseIndentationString, out parent, out indentSize, out useTabs, out tabSize)); if (!string.IsNullOrEmpty(baseIndentationString)) { return baseIndentationString.GetColumnFromLineOffset(baseIndentationString.Length, editorOptions.GetTabSize()) + additionalIndentation; } } return additionalIndentation; } private TextSpan GetVisibleTextSpan(SourceText text, TextSpan visibleSpan, bool uptoFirstAndLastLine = false) { var start = visibleSpan.Start; for (; start < visibleSpan.End; start++) { if (!char.IsWhiteSpace(text[start])) { break; } } var end = visibleSpan.End - 1; if (start <= end) { for (; start <= end; end--) { if (!char.IsWhiteSpace(text[end])) { break; } } } if (uptoFirstAndLastLine) { var firstLine = text.Lines.GetLineFromPosition(visibleSpan.Start); var lastLine = text.Lines.GetLineFromPosition(visibleSpan.End); if (firstLine.LineNumber < lastLine.LineNumber) { start = (start < firstLine.End) ? start : firstLine.End; end = (lastLine.Start < end + 1) ? end : lastLine.Start - 1; } } return (start <= end) ? TextSpan.FromBounds(start, end + 1) : default(TextSpan); } private int GetAdditionalIndentation(SyntaxNode root, SourceText text, TextSpan span) { if (_hostType == HostType.HTML) { return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } if (_hostType == HostType.Razor) { var type = GetRazorCodeBlockType(span.Start); // razor block if (type == RazorCodeBlockType.Block) { // more workaround for csharp razor case. when } for csharp razor code block is just typed, "}" exist // in both subject and surface buffer and there is no easy way to figure out who owns } just typed. // in this case, we let razor owns it. later razor will remove } from subject buffer if it is something // razor owns. if (this.Project.Language == LanguageNames.CSharp) { var textSpan = GetVisibleTextSpan(text, span); var end = textSpan.End - 1; if (end >= 0 && text[end] == '}') { var token = root.FindToken(end); var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>(); if (token.Span.Start == end && syntaxFact != null) { SyntaxToken openBrace; if (syntaxFact.TryGetCorrespondingOpenBrace(token, out openBrace) && !textSpan.Contains(openBrace.Span)) { return 0; } } } } // same as C#, but different text is in the buffer if (this.Project.Language == LanguageNames.VisualBasic) { var textSpan = GetVisibleTextSpan(text, span); var subjectSnapshot = _containedLanguage.SubjectBuffer.CurrentSnapshot; var end = textSpan.End - 1; if (end >= 0) { var ch = subjectSnapshot[end]; if (CheckCode(subjectSnapshot, textSpan.End, ch, VBRazorBlock, checkAt: false) || CheckCode(subjectSnapshot, textSpan.End, ch, FunctionsRazor, checkAt: false)) { var token = root.FindToken(end, findInsideTrivia: true); var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>(); if (token.Span.End == textSpan.End && syntaxFact != null) { if (syntaxFact.IsSkippedTokensTrivia(token.Parent)) { return 0; } } } } } return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } } return 0; } private RazorCodeBlockType GetRazorCodeBlockType(int position) { Debug.Assert(_hostType == HostType.Razor); var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var subjectSnapshot = subjectBuffer.CurrentSnapshot; var surfaceSnapshot = ((IProjectionBuffer)_containedLanguage.DataBuffer).CurrentSnapshot; var surfacePoint = surfaceSnapshot.MapFromSourceSnapshot(new SnapshotPoint(subjectSnapshot, position), PositionAffinity.Predecessor); if (!surfacePoint.HasValue) { // how this can happen? return RazorCodeBlockType.Implicit; } var ch = char.ToLower(surfaceSnapshot[Math.Max(surfacePoint.Value - 1, 0)]); // razor block if (IsCodeBlock(surfaceSnapshot, surfacePoint.Value, ch)) { return RazorCodeBlockType.Block; } if (ch == RazorExplicit) { return RazorCodeBlockType.Explicit; } if (CheckCode(surfaceSnapshot, surfacePoint.Value, HelperRazor)) { return RazorCodeBlockType.Helper; } return RazorCodeBlockType.Implicit; } private bool IsCodeBlock(ITextSnapshot surfaceSnapshot, int position, char ch) { if (this.Project.Language == LanguageNames.CSharp) { return CheckCode(surfaceSnapshot, position, ch, CSharpRazorBlock) || CheckCode(surfaceSnapshot, position, ch, FunctionsRazor, CSharpRazorBlock); } if (this.Project.Language == LanguageNames.VisualBasic) { return CheckCode(surfaceSnapshot, position, ch, VBRazorBlock) || CheckCode(surfaceSnapshot, position, ch, FunctionsRazor); } return false; } private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag, bool checkAt = true) { if (ch != tag[tag.Length - 1] || position < tag.Length) { return false; } var start = position - tag.Length; var razorTag = snapshot.GetText(start, tag.Length); return string.Equals(razorTag, tag, StringComparison.OrdinalIgnoreCase) && (!checkAt || snapshot[start - 1] == RazorExplicit); } private bool CheckCode(ITextSnapshot snapshot, int position, string tag) { int i = position - 1; if (i < 0) { return false; } for (; i >= 0; i--) { if (!char.IsWhiteSpace(snapshot[i])) { break; } } var ch = snapshot[i]; position = i + 1; return CheckCode(snapshot, position, ch, tag); } private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag1, string tag2) { if (!CheckCode(snapshot, position, ch, tag2, checkAt: false)) { return false; } return CheckCode(snapshot, position - tag2.Length, tag1); } public ITextUndoHistory GetTextUndoHistory() { // In Venus scenarios, the undo history is associated with the data buffer return _componentModel.GetService<ITextUndoHistoryRegistry>().GetHistory(_containedLanguage.DataBuffer); } public uint GetItemId() { AssertIsForeground(); if (_itemMoniker == null) { return (uint)VSConstants.VSITEMID.Nil; } uint itemId; return Project.Hierarchy.ParseCanonicalName(_itemMoniker, out itemId) == VSConstants.S_OK ? itemId : (uint)VSConstants.VSITEMID.Nil; } private enum RazorCodeBlockType { Block, Explicit, Implicit, Helper } private enum HostType { HTML, Razor, XOML } } }
using System; using System.Runtime.InteropServices; using System.Collections; using UnityEngine; /* * please don't use this code for sell a asset * user for free * developed by Poya @ http://gamesforsoul.com/ * BLOB support by Jonathan Derrough @ http://jderrough.blogspot.com/ * Modify and structure by Santiago Bustamante @ busta117@gmail.com * Android compatibility by Thomas Olsen @ olsen.thomas@gmail.com * * */ public class SqliteException : Exception { public SqliteException (string message) : base(message) { } } public class SqliteDatabase { private bool CanExQuery = true; const int SQLITE_OK = 0; const int SQLITE_ROW = 100; const int SQLITE_DONE = 101; const int SQLITE_INTEGER = 1; const int SQLITE_FLOAT = 2; const int SQLITE_TEXT = 3; const int SQLITE_BLOB = 4; const int SQLITE_NULL = 5; [DllImport("sqlite3", EntryPoint = "sqlite3_open")] private static extern int sqlite3_open (string filename, out IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_close")] private static extern int sqlite3_close (IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_prepare_v2")] private static extern int sqlite3_prepare_v2 (IntPtr db, string zSql, int nByte, out IntPtr ppStmpt, IntPtr pzTail); [DllImport("sqlite3", EntryPoint = "sqlite3_step")] private static extern int sqlite3_step (IntPtr stmHandle); [DllImport("sqlite3", EntryPoint = "sqlite3_finalize")] private static extern int sqlite3_finalize (IntPtr stmHandle); [DllImport("sqlite3", EntryPoint = "sqlite3_errmsg")] private static extern IntPtr sqlite3_errmsg (IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_column_count")] private static extern int sqlite3_column_count (IntPtr stmHandle); [DllImport("sqlite3", EntryPoint = "sqlite3_column_name")] private static extern IntPtr sqlite3_column_name (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_type")] private static extern int sqlite3_column_type (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_int")] private static extern int sqlite3_column_int (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_text")] private static extern IntPtr sqlite3_column_text (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_double")] private static extern double sqlite3_column_double (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_blob")] private static extern IntPtr sqlite3_column_blob (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_bytes")] private static extern int sqlite3_column_bytes (IntPtr stmHandle, int iCol); private IntPtr _connection; private bool IsConnectionOpen { get; set; } private string pathDB; #region Public Methods /// <summary> /// Initializes a new instance of the <see cref="SqliteDatabase"/> class. /// </summary> /// <param name='dbName'> /// Data Base name. (the file needs exist in the streamingAssets folder) /// </param> public SqliteDatabase (string dbName) { pathDB = System.IO.Path.Combine (Application.persistentDataPath, dbName); //if no exist the DB in the folder of persistent data (folder "Documents" on iOS) proceeds to copy it. if (!System.IO.File.Exists (pathDB)) { //original path string sourcePath = System.IO.Path.Combine (Application.streamingAssetsPath, dbName); if (sourcePath.Contains ("://")) { // Android WWW www = new WWW (sourcePath); // Wait for download to complete - not pretty at all but easy hack for now // and it would not take long since the data is on the local device. while (!www.isDone) {;} if (String.IsNullOrEmpty(www.error)) { System.IO.File.WriteAllBytes(pathDB, www.bytes); } else { CanExQuery = false; } } else { // Mac, Windows, Iphone //validate the existens of the DB in the original folder (folder "streamingAssets") if (System.IO.File.Exists (sourcePath)) { //copy file - alle systems except Android System.IO.File.Copy (sourcePath, pathDB, true); } else { CanExQuery = false; Debug.Log ("ERROR: the file DB named " + dbName + " doesn't exist in the StreamingAssets Folder, please copy it there."); } } } } private void Open () { this.Open (pathDB); } private void Open (string path) { if (IsConnectionOpen) { throw new SqliteException ("There is already an open connection"); } if (sqlite3_open (path, out _connection) != SQLITE_OK) { throw new SqliteException ("Could not open database file: " + path); } IsConnectionOpen = true; } private void Close () { if (IsConnectionOpen) { sqlite3_close (_connection); } IsConnectionOpen = false; } /// <summary> /// Executes a Update, Delete, etc query. /// </summary> /// <param name='query'> /// Query. /// </param> /// <exception cref='SqliteException'> /// Is thrown when the sqlite exception. /// </exception> public void ExecuteNonQuery (string query) { if (!CanExQuery) { Debug.Log ("ERROR: Can't execute the query, verify DB origin file"); return; } this.Open (); if (!IsConnectionOpen) { throw new SqliteException ("SQLite database is not open."); } IntPtr stmHandle = Prepare (query); if (sqlite3_step (stmHandle) != SQLITE_DONE) { throw new SqliteException ("Could not execute SQL statement."); } Finalize (stmHandle); this.Close (); } /// <summary> /// Executes a query that requires a response (SELECT, etc). /// </summary> /// <returns> /// Dictionary with the response data /// </returns> /// <param name='query'> /// Query. /// </param> /// <exception cref='SqliteException'> /// Is thrown when the sqlite exception. /// </exception> public DataTable ExecuteQuery (string query) { if (!CanExQuery) { Debug.Log ("ERROR: Can't execute the query, verify DB origin file"); return null; } this.Open (); if (!IsConnectionOpen) { throw new SqliteException ("SQLite database is not open."); } IntPtr stmHandle = Prepare (query); int columnCount = sqlite3_column_count (stmHandle); var dataTable = new DataTable (); for (int i = 0; i < columnCount; i++) { string columnName = Marshal.PtrToStringAnsi (sqlite3_column_name (stmHandle, i)); dataTable.Columns.Add (columnName); } //populate datatable while (sqlite3_step(stmHandle) == SQLITE_ROW) { object[] row = new object[columnCount]; for (int i = 0; i < columnCount; i++) { switch (sqlite3_column_type (stmHandle, i)) { case SQLITE_INTEGER: row [i] = sqlite3_column_int (stmHandle, i); break; case SQLITE_TEXT: IntPtr text = sqlite3_column_text (stmHandle, i); row [i] = Marshal.PtrToStringAnsi (text); break; case SQLITE_FLOAT: row [i] = sqlite3_column_double (stmHandle, i); break; case SQLITE_BLOB: IntPtr blob = sqlite3_column_blob (stmHandle, i); int size = sqlite3_column_bytes (stmHandle, i); byte[] data = new byte[size]; Marshal.Copy (blob, data, 0, size); row [i] = data; break; case SQLITE_NULL: row [i] = null; break; } } dataTable.AddRow (row); } Finalize (stmHandle); this.Close (); return dataTable; } public void ExecuteScript (string script) { string[] statements = script.Split (';'); foreach (string statement in statements) { if (!string.IsNullOrEmpty (statement.Trim ())) { ExecuteNonQuery (statement); } } } #endregion #region Private Methods private IntPtr Prepare (string query) { IntPtr stmHandle; if (sqlite3_prepare_v2 (_connection, query, query.Length, out stmHandle, IntPtr.Zero) != SQLITE_OK) { IntPtr errorMsg = sqlite3_errmsg (_connection); throw new SqliteException (Marshal.PtrToStringAnsi (errorMsg)); } return stmHandle; } private void Finalize (IntPtr stmHandle) { if (sqlite3_finalize (stmHandle) != SQLITE_OK) { throw new SqliteException ("Could not finalize SQL statement."); } } #endregion }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using NUnit.Framework; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Notifications; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Services.Implement; using Umbraco.Cms.Tests.Common.Builders; using Umbraco.Cms.Tests.Common.Testing; using Umbraco.Cms.Tests.Integration.Testing; namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Services { [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, PublishedRepositoryEvents = true)] public class MediaTypeServiceTests : UmbracoIntegrationTest { private MediaService MediaService => (MediaService)GetRequiredService<IMediaService>(); private IMediaTypeService MediaTypeService => GetRequiredService<IMediaTypeService>(); protected override void CustomTestSetup(IUmbracoBuilder builder) => builder .AddNotificationHandler<MediaMovedToRecycleBinNotification, ContentNotificationHandler>(); [Test] public void Get_With_Missing_Guid() { // Arrange // Act IMediaType result = MediaTypeService.Get(Guid.NewGuid()); // Assert Assert.IsNull(result); } [Test] public void Empty_Description_Is_Always_Null_After_Saving_Media_Type() { MediaType mediaType = MediaTypeBuilder.CreateSimpleMediaType("mediaType", "Media Type"); mediaType.Description = null; MediaTypeService.Save(mediaType); MediaType mediaType2 = MediaTypeBuilder.CreateSimpleMediaType("mediaType2", "Media Type 2"); mediaType2.Description = string.Empty; MediaTypeService.Save(mediaType2); Assert.IsNull(mediaType.Description); Assert.IsNull(mediaType2.Description); } [Test] public void Deleting_Media_Type_With_Hierarchy_Of_Media_Items_Moves_Orphaned_Media_To_Recycle_Bin() { IMediaType contentType1 = MediaTypeBuilder.CreateSimpleMediaType("test1", "Test1"); MediaTypeService.Save(contentType1); IMediaType contentType2 = MediaTypeBuilder.CreateSimpleMediaType("test2", "Test2"); MediaTypeService.Save(contentType2); IMediaType contentType3 = MediaTypeBuilder.CreateSimpleMediaType("test3", "Test3"); MediaTypeService.Save(contentType3); IMediaType[] contentTypes = new[] { contentType1, contentType2, contentType3 }; int parentId = -1; var ids = new List<int>(); for (int i = 0; i < 2; i++) { for (int index = 0; index < contentTypes.Length; index++) { IMediaType contentType = contentTypes[index]; Media contentItem = MediaBuilder.CreateSimpleMedia(contentType, "MyName_" + index + "_" + i, parentId); MediaService.Save(contentItem); parentId = contentItem.Id; ids.Add(contentItem.Id); } } // delete the first content type, all other content of different content types should be in the recycle bin MediaTypeService.Delete(contentTypes[0]); IEnumerable<IMedia> found = MediaService.GetByIds(ids); Assert.AreEqual(4, found.Count()); foreach (IMedia content in found) { Assert.IsTrue(content.Trashed); } } [Test] public void Deleting_Media_Types_With_Hierarchy_Of_Media_Items_Doesnt_Raise_Trashed_Event_For_Deleted_Items() { ContentNotificationHandler.MovedMediaToRecycleBin = MovedMediaToRecycleBin; try { IMediaType contentType1 = MediaTypeBuilder.CreateSimpleMediaType("test1", "Test1"); MediaTypeService.Save(contentType1); IMediaType contentType2 = MediaTypeBuilder.CreateSimpleMediaType("test2", "Test2"); MediaTypeService.Save(contentType2); IMediaType contentType3 = MediaTypeBuilder.CreateSimpleMediaType("test3", "Test3"); MediaTypeService.Save(contentType3); IMediaType[] contentTypes = new[] { contentType1, contentType2, contentType3 }; int parentId = -1; var ids = new List<int>(); for (int i = 0; i < 2; i++) { for (int index = 0; index < contentTypes.Length; index++) { IMediaType contentType = contentTypes[index]; Media contentItem = MediaBuilder.CreateSimpleMedia(contentType, "MyName_" + index + "_" + i, parentId); MediaService.Save(contentItem); parentId = contentItem.Id; ids.Add(contentItem.Id); } } foreach (IMediaType contentType in contentTypes.Reverse()) { MediaTypeService.Delete(contentType); } } finally { ContentNotificationHandler.MovedMediaToRecycleBin = null; } } private void MovedMediaToRecycleBin(MediaMovedToRecycleBinNotification notification) { foreach (MoveEventInfo<IMedia> item in notification.MoveInfoCollection) { // if this item doesn't exist then Fail! IMedia exists = MediaService.GetById(item.Entity.Id); if (exists == null) { Assert.Fail("The item doesn't exist"); } } } [Test] public void Can_Copy_MediaType_By_Performing_Clone() { // Arrange var mediaType = MediaTypeBuilder.CreateImageMediaType("Image2") as IMediaType; MediaTypeService.Save(mediaType); // Act IMediaType sut = mediaType.DeepCloneWithResetIdentities("Image2_2"); Assert.IsNotNull(sut); MediaTypeService.Save(sut); // Assert Assert.That(sut.HasIdentity, Is.True); Assert.AreEqual(mediaType.ParentId, sut.ParentId); Assert.AreEqual(mediaType.Level, sut.Level); Assert.AreEqual(mediaType.PropertyTypes.Count(), sut.PropertyTypes.Count()); Assert.AreNotEqual(mediaType.Id, sut.Id); Assert.AreNotEqual(mediaType.Key, sut.Key); Assert.AreNotEqual(mediaType.Path, sut.Path); Assert.AreNotEqual(mediaType.SortOrder, sut.SortOrder); Assert.AreNotEqual(mediaType.PropertyTypes.First(x => x.Alias.Equals("umbracoFile")).Id, sut.PropertyTypes.First(x => x.Alias.Equals("umbracoFile")).Id); Assert.AreNotEqual(mediaType.PropertyGroups.First(x => x.Name.Equals("Media")).Id, sut.PropertyGroups.First(x => x.Name.Equals("Media")).Id); } [Test] public void Can_Copy_MediaType_To_New_Parent_By_Performing_Clone() { // Arrange MediaType parentMediaType1 = MediaTypeBuilder.CreateSimpleMediaType("parent1", "Parent1"); MediaTypeService.Save(parentMediaType1); MediaType parentMediaType2 = MediaTypeBuilder.CreateSimpleMediaType("parent2", "Parent2", null, true); MediaTypeService.Save(parentMediaType2); var mediaType = MediaTypeBuilder.CreateImageMediaType("Image2") as IMediaType; MediaTypeService.Save(mediaType); // Act IMediaType clone = mediaType.DeepCloneWithResetIdentities("newcategory"); Assert.IsNotNull(clone); clone.RemoveContentType("parent1"); clone.AddContentType(parentMediaType2); clone.ParentId = parentMediaType2.Id; MediaTypeService.Save(clone); // Assert Assert.That(clone.HasIdentity, Is.True); IMediaType clonedMediaType = MediaTypeService.Get(clone.Id); IMediaType originalMediaType = MediaTypeService.Get(mediaType.Id); Assert.That(clonedMediaType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedMediaType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); Assert.AreEqual(clonedMediaType.Path, "-1," + parentMediaType2.Id + "," + clonedMediaType.Id); Assert.AreEqual(clonedMediaType.PropertyTypes.Count(), originalMediaType.PropertyTypes.Count()); Assert.AreNotEqual(clonedMediaType.ParentId, originalMediaType.ParentId); Assert.AreEqual(clonedMediaType.ParentId, parentMediaType2.Id); Assert.AreNotEqual(clonedMediaType.Id, originalMediaType.Id); Assert.AreNotEqual(clonedMediaType.Key, originalMediaType.Key); Assert.AreNotEqual(clonedMediaType.Path, originalMediaType.Path); Assert.AreNotEqual(clonedMediaType.PropertyTypes.First(x => x.Alias.StartsWith("umbracoFile")).Id, originalMediaType.PropertyTypes.First(x => x.Alias.StartsWith("umbracoFile")).Id); Assert.AreNotEqual(clonedMediaType.PropertyGroups.First(x => x.Name.StartsWith("Media")).Id, originalMediaType.PropertyGroups.First(x => x.Name.StartsWith("Media")).Id); } public class ContentNotificationHandler : INotificationHandler<MediaMovedToRecycleBinNotification> { public void Handle(MediaMovedToRecycleBinNotification notification) => MovedMediaToRecycleBin?.Invoke(notification); public static Action<MediaMovedToRecycleBinNotification> MovedMediaToRecycleBin { get; set; } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Razor.Editor; using Microsoft.AspNet.Razor.Generator; using Microsoft.AspNet.Razor.Parser; using Microsoft.AspNet.Razor.Parser.SyntaxTree; using Microsoft.AspNet.Razor.Test.Framework; using Microsoft.AspNet.Razor.Text; using Microsoft.AspNet.Razor.Tokenizer.Symbols; using Xunit; namespace Microsoft.AspNet.Razor.Test.Parser.Html { public class HtmlBlockTest : CsHtmlMarkupParserTestBase { [Fact] public void ParseBlockMethodThrowsArgNullExceptionOnNullContext() { // Arrange HtmlMarkupParser parser = new HtmlMarkupParser(); // Act and Assert var exception = Assert.Throws<InvalidOperationException>(() => parser.ParseBlock()); Assert.Equal(RazorResources.Parser_Context_Not_Set, exception.Message); } [Fact] public void ParseBlockHandlesOpenAngleAtEof() { ParseDocumentTest("@{" + Environment.NewLine + "<", new MarkupBlock( Factory.EmptyHtml(), new StatementBlock( Factory.CodeTransition(), Factory.MetaCode("{").Accepts(AcceptedCharacters.None), Factory.Code("\r\n").AsStatement(), new MarkupBlock( Factory.Markup("<")))), new RazorError( string.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,RazorResources.BlockName_Code, "}", "{"), 1, 0, 1)); } [Fact] public void ParseBlockHandlesOpenAngleWithProperTagFollowingIt() { ParseDocumentTest("@{" + Environment.NewLine + "<" + Environment.NewLine + "</html>", new MarkupBlock( Factory.EmptyHtml(), new StatementBlock( Factory.CodeTransition(), Factory.MetaCode("{").Accepts(AcceptedCharacters.None), Factory.Code("\r\n").AsStatement(), new MarkupBlock( Factory.Markup("<\r\n") ), new MarkupBlock( Factory.Markup(@"</html>").Accepts(AcceptedCharacters.None) ), Factory.EmptyCSharp().AsStatement() ) ), designTimeParser: true, expectedErrors: new[] { new RazorError(string.Format(RazorResources.ParseError_UnexpectedEndTag,"html"), 7, 2, 0), new RazorError(string.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,"code", "}", "{"), 1, 0, 1) }); } [Fact] public void TagWithoutCloseAngleDoesNotTerminateBlock() { ParseBlockTest("< " + Environment.NewLine + " ", new MarkupBlock( Factory.Markup("< \r\n ")), designTimeParser: true, expectedErrors: new RazorError(string.Format(RazorResources.ParseError_UnfinishedTag,string.Empty), 0, 0, 0)); } [Fact] public void ParseBlockAllowsStartAndEndTagsToDifferInCase() { SingleSpanBlockTest("<li><p>Foo</P></lI>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockReadsToEndOfLineIfFirstCharacterAfterTransitionIsColon() { ParseBlockTest("@:<li>Foo Bar Baz" + Environment.NewLine + "bork", new MarkupBlock( Factory.MarkupTransition(), Factory.MetaMarkup(":", HtmlSymbolType.Colon), Factory.Markup("<li>Foo Bar Baz\r\n") .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None)) )); } [Fact] public void ParseBlockStopsParsingSingleLineBlockAtEOFIfNoEOLReached() { ParseBlockTest("@:foo bar", new MarkupBlock( Factory.MarkupTransition(), Factory.MetaMarkup(":", HtmlSymbolType.Colon), Factory.Markup(@"foo bar") .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)) )); } [Fact] public void ParseBlockStopsAtMatchingCloseTagToStartTag() { SingleSpanBlockTest("<a><b></b></a><c></c>", "<a><b></b></a>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockParsesUntilMatchingEndTagIfFirstNonWhitespaceCharacterIsStartTag() { SingleSpanBlockTest("<baz><boz><biz></biz></boz></baz>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockAllowsUnclosedTagsAsLongAsItCanRecoverToAnExpectedEndTag() { SingleSpanBlockTest("<foo><bar><baz></foo>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockWithSelfClosingTagJustEmitsTag() { SingleSpanBlockTest("<foo />", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockCanHandleSelfClosingTagsWithinBlock() { SingleSpanBlockTest("<foo><bar /></foo>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockSupportsTagsWithAttributes() { ParseBlockTest("<foo bar=\"baz\"><biz><boz zoop=zork/></biz></foo>", new MarkupBlock( Factory.Markup("<foo"), new MarkupBlock(new AttributeBlockCodeGenerator("bar", new LocationTagged<string>(" bar=\"", 4, 0, 4), new LocationTagged<string>("\"", 13, 0, 13)), Factory.Markup(" bar=\"").With(SpanCodeGenerator.Null), Factory.Markup("baz").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 10, 0, 10), new LocationTagged<string>("baz", 10, 0, 10))), Factory.Markup("\"").With(SpanCodeGenerator.Null)), Factory.Markup("><biz><boz"), new MarkupBlock(new AttributeBlockCodeGenerator("zoop", new LocationTagged<string>(" zoop=", 24, 0, 24), new LocationTagged<string>(String.Empty, 34, 0, 34)), Factory.Markup(" zoop=").With(SpanCodeGenerator.Null), Factory.Markup("zork").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 30, 0, 30), new LocationTagged<string>("zork", 30, 0, 30)))), Factory.Markup("/></biz></foo>").Accepts(AcceptedCharacters.None))); } [Fact] public void ParseBlockAllowsCloseAngleBracketInAttributeValueIfDoubleQuoted() { ParseBlockTest("<foo><bar baz=\">\" /></foo>", new MarkupBlock( Factory.Markup("<foo><bar"), new MarkupBlock(new AttributeBlockCodeGenerator("baz", new LocationTagged<string>(" baz=\"", 9, 0, 9), new LocationTagged<string>("\"", 16, 0, 16)), Factory.Markup(" baz=\"").With(SpanCodeGenerator.Null), Factory.Markup(">").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), new LocationTagged<string>(">", 15, 0, 15))), Factory.Markup("\"").With(SpanCodeGenerator.Null)), Factory.Markup(" /></foo>").Accepts(AcceptedCharacters.None))); } [Fact] public void ParseBlockAllowsCloseAngleBracketInAttributeValueIfSingleQuoted() { ParseBlockTest("<foo><bar baz=\'>\' /></foo>", new MarkupBlock( Factory.Markup("<foo><bar"), new MarkupBlock(new AttributeBlockCodeGenerator("baz", new LocationTagged<string>(" baz='", 9, 0, 9), new LocationTagged<string>("'", 16, 0, 16)), Factory.Markup(" baz='").With(SpanCodeGenerator.Null), Factory.Markup(">").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), new LocationTagged<string>(">", 15, 0, 15))), Factory.Markup("'").With(SpanCodeGenerator.Null)), Factory.Markup(" /></foo>").Accepts(AcceptedCharacters.None))); } [Fact] public void ParseBlockAllowsSlashInAttributeValueIfDoubleQuoted() { ParseBlockTest("<foo><bar baz=\"/\"></bar></foo>", new MarkupBlock( Factory.Markup("<foo><bar"), new MarkupBlock(new AttributeBlockCodeGenerator("baz", new LocationTagged<string>(" baz=\"", 9, 0, 9), new LocationTagged<string>("\"", 16, 0, 16)), Factory.Markup(" baz=\"").With(SpanCodeGenerator.Null), Factory.Markup("/").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), new LocationTagged<string>("/", 15, 0, 15))), Factory.Markup("\"").With(SpanCodeGenerator.Null)), Factory.Markup("></bar></foo>").Accepts(AcceptedCharacters.None))); } [Fact] public void ParseBlockAllowsSlashInAttributeValueIfSingleQuoted() { ParseBlockTest("<foo><bar baz=\'/\'></bar></foo>", new MarkupBlock( Factory.Markup("<foo><bar"), new MarkupBlock(new AttributeBlockCodeGenerator("baz", new LocationTagged<string>(" baz='", 9, 0, 9), new LocationTagged<string>("'", 16, 0, 16)), Factory.Markup(" baz='").With(SpanCodeGenerator.Null), Factory.Markup("/").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), new LocationTagged<string>("/", 15, 0, 15))), Factory.Markup("'").With(SpanCodeGenerator.Null)), Factory.Markup("></bar></foo>").Accepts(AcceptedCharacters.None))); } [Fact] public void ParseBlockTerminatesAtEOF() { SingleSpanBlockTest("<foo>", "<foo>", BlockType.Markup, SpanKind.Markup, new RazorError(string.Format(RazorResources.ParseError_MissingEndTag,"foo"), new SourceLocation(0, 0, 0))); } [Fact] public void ParseBlockSupportsCommentAsBlock() { SingleSpanBlockTest("<!-- foo -->", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockSupportsCommentWithinBlock() { SingleSpanBlockTest("<foo>bar<!-- zoop -->baz</foo>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockProperlyBalancesCommentStartAndEndTags() { SingleSpanBlockTest("<!--<foo></bar>-->", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockTerminatesAtEOFWhenParsingComment() { SingleSpanBlockTest("<!--<foo>", "<!--<foo>", BlockType.Markup, SpanKind.Markup); } [Fact] public void ParseBlockOnlyTerminatesCommentOnFullEndSequence() { SingleSpanBlockTest("<!--<foo>--</bar>-->", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockTerminatesCommentAtFirstOccurrenceOfEndSequence() { SingleSpanBlockTest("<foo><!--<foo></bar-->--></foo>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockTreatsMalformedTagsAsContent() { SingleSpanBlockTest( "<foo></!-- bar --></foo>", "<foo></!-- bar -->", BlockType.Markup, SpanKind.Markup, AcceptedCharacters.None, new RazorError(string.Format(RazorResources.ParseError_MissingEndTag,"foo"), 0, 0, 0)); } [Fact] public void ParseBlockParsesSGMLDeclarationAsEmptyTag() { SingleSpanBlockTest("<foo><!DOCTYPE foo bar baz></foo>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockTerminatesSGMLDeclarationAtFirstCloseAngle() { SingleSpanBlockTest("<foo><!DOCTYPE foo bar> baz></foo>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockParsesXMLProcessingInstructionAsEmptyTag() { SingleSpanBlockTest("<foo><?xml foo bar baz?></foo>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockTerminatesXMLProcessingInstructionAtQuestionMarkCloseAnglePair() { SingleSpanBlockTest("<foo><?xml foo bar?> baz</foo>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockDoesNotTerminateXMLProcessingInstructionAtCloseAngleUnlessPreceededByQuestionMark() { SingleSpanBlockTest("<foo><?xml foo bar> baz?></foo>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockSupportsScriptTagsWithLessThanSignsInThem() { SingleSpanBlockTest(@"<script>if(foo<bar) { alert(""baz"");)</script>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockSupportsScriptTagsWithSpacedLessThanSignsInThem() { SingleSpanBlockTest(@"<script>if(foo < bar) { alert(""baz"");)</script>", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None); } [Fact] public void ParseBlockAcceptsEmptyTextTag() { ParseBlockTest("<text/>", new MarkupBlock( Factory.MarkupTransition("<text/>") )); } [Fact] public void ParseBlockAcceptsTextTagAsOuterTagButDoesNotRender() { ParseBlockTest("<text>Foo Bar <foo> Baz</text> zoop", new MarkupBlock( Factory.MarkupTransition("<text>"), Factory.Markup("Foo Bar <foo> Baz"), Factory.MarkupTransition("</text>"), Factory.Markup(" ").Accepts(AcceptedCharacters.None) )); } [Fact] public void ParseBlockRendersLiteralTextTagIfDoubled() { ParseBlockTest("<text><text>Foo Bar <foo> Baz</text></text> zoop", new MarkupBlock( Factory.MarkupTransition("<text>"), Factory.Markup("<text>Foo Bar <foo> Baz</text>"), Factory.MarkupTransition("</text>"), Factory.Markup(" ").Accepts(AcceptedCharacters.None) )); } [Fact] public void ParseBlockDoesNotConsiderPsuedoTagWithinMarkupBlock() { ParseBlockTest("<foo><text><bar></bar></foo>", new MarkupBlock( Factory.Markup("<foo><text><bar></bar></foo>").Accepts(AcceptedCharacters.None) )); } [Fact] public void ParseBlockStopsParsingMidEmptyTagIfEOFReached() { ParseBlockTest("<br/", new MarkupBlock( Factory.Markup("<br/") ), new RazorError(string.Format(RazorResources.ParseError_UnfinishedTag,"br"), SourceLocation.Zero)); } [Fact] public void ParseBlockCorrectlyHandlesSingleLineOfMarkupWithEmbeddedStatement() { ParseBlockTest("<div>Foo @if(true) {} Bar</div>", new MarkupBlock( Factory.Markup("<div>Foo "), new StatementBlock( Factory.CodeTransition(), Factory.Code("if(true) {}").AsStatement()), Factory.Markup(" Bar</div>").Accepts(AcceptedCharacters.None))); } [Fact] public void ParseBlockIgnoresTagsInContentsOfScriptTag() { ParseBlockTest(@"<script>foo<bar baz='@boz'></script>", new MarkupBlock( Factory.Markup("<script>foo<bar baz='"), new ExpressionBlock( Factory.CodeTransition(), Factory.Code("boz") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false) .Accepts(AcceptedCharacters.NonWhiteSpace)), Factory.Markup("'></script>") .Accepts(AcceptedCharacters.None))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using Xunit; public class SyncTextReader { // NOTE: These tests test the underlying SyncTextReader by // accessing the Console.In TextReader (which in fact is a SyncTextReader). static readonly string[] s_testLines = new string[] { "3232 Hello32 Hello 5032 Hello 50 532 Hello 50 5 aTrueaabcdbc1.23123.4561.23439505050System.ObjectHello World", "32", "", "32 Hello", "", "32 Hello 50", "", "32 Hello 50 5", "", "32 Hello 50 5 a", "", "True", "a", "abcd", "bc", "1.23", "123.456", "1.234", "39", "50", "50", "50", "System.Object", "Hello World", }; private static void Test(string content, Action action) { TextWriter savedStandardOutput = Console.Out; TextReader savedStandardInput = Console.In; try { using (MemoryStream memStream = new MemoryStream()) { // Write the content, but leave the stream open. using (StreamWriter sw = new StreamWriter(memStream, Encoding.Unicode, 1024, true)) { sw.Write(content); sw.Flush(); } memStream.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(memStream)) { Console.SetIn(sr); action(); } } } finally { TextWriter oldWriter = Console.Out; Console.SetOut(savedStandardOutput); oldWriter.Dispose(); TextReader oldReader = Console.In; Console.SetIn(savedStandardInput); oldReader.Dispose(); } } [Fact] public void ReadToEnd() { var expected = string.Join(Environment.NewLine, s_testLines); Test(expected, () => { // Given, When var result = Console.In.ReadToEnd(); // Then Assert.Equal(expected, result); Assert.Equal(-1, Console.Read()); // We should be at EOF now. }); } [Fact] public void ReadBlock() { var expected = new[] { 'H', 'e', 'l', 'l', 'o' }; Test(new string(expected), () => { // Given var buffer = new char[expected.Length]; // When var result = Console.In.ReadBlock(buffer, 0, 5); // Then Assert.Equal(5, result); Assert.Equal(expected, buffer); Assert.Equal(-1, Console.Read()); // We should be at EOF now. }); } [Fact] public void Read() { var expected = new[] { 'H', 'e', 'l', 'l', 'o' }; Test(new string(expected), () => { // Given var buffer = new char[expected.Length]; // When var result = Console.In.Read(buffer, 0, 5); // Then Assert.Equal(5, result); Assert.Equal(expected, buffer); Assert.Equal(-1, Console.Read()); // We should be at EOF now. }); } [Fact] public void Peek() { const string expected = "ABC"; Test(expected, () => { foreach (char expectedChar in expected) { Assert.Equal(expectedChar, Console.In.Peek()); Assert.Equal(expectedChar, Console.In.Read()); } }); } [Fact] public void ReadToEndAsync() { var expected = string.Join(Environment.NewLine, s_testLines); Test(expected, () => { // Given, When var result = Console.In.ReadToEndAsync().Result; // Then Assert.Equal(expected, result); Assert.Equal(-1, Console.Read()); // We should be at EOF now. }); } [Fact] public void ReadBlockAsync() { var expected = new[] { 'H', 'e', 'l', 'l', 'o' }; Test(new string(expected), () => { // Given var buffer = new char[expected.Length]; // When var result = Console.In.ReadBlockAsync(buffer, 0, 5).Result; // Then Assert.Equal(5, result); Assert.Equal(expected, buffer); Assert.Equal(-1, Console.Read()); // We should be at EOF now. // Invalid args Assert.Throws<ArgumentNullException>(() => { Console.In.ReadBlockAsync(null, 0, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { Console.In.ReadBlockAsync(new char[1], -1, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { Console.In.ReadBlockAsync(new char[1], 0, -1); }); Assert.Throws<ArgumentException>(() => { Console.In.ReadBlockAsync(new char[1], 1, 1); }); }); } [Fact] public void ReadAsync() { var expected = new[] { 'H', 'e', 'l', 'l', 'o' }; Test(new string(expected), () => { // Given var buffer = new char[expected.Length]; // When var result = Console.In.ReadAsync(buffer, 0, 5).Result; // Then Assert.Equal(5, result); Assert.Equal(expected, buffer); Assert.Equal(-1, Console.Read()); // We should be at EOF now. // Invalid args Assert.Throws<ArgumentNullException>(() => { Console.In.ReadAsync(null, 0, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { Console.In.ReadAsync(new char[1], -1, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { Console.In.ReadAsync(new char[1], 0, -1); }); Assert.Throws<ArgumentException>(() => { Console.In.ReadAsync(new char[1], 1, 1); }); }); } [Fact] public void ReadLineAsync() { var expected = string.Join(Environment.NewLine, s_testLines); Test(expected, () => { for (int i = 0; i < s_testLines.Length; i++) { // Given, When var result = Console.In.ReadLineAsync().Result; // Then Assert.Equal(s_testLines[i], result); } Assert.Equal(-1, Console.Read()); }); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using FluentNHibernate.Automapping.TestFixtures; using FluentNHibernate.Automapping.TestFixtures.CustomTypes; using FluentNHibernate.Conventions.Helpers.Builders; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.Mapping; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.Testing.FluentInterfaceTests; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.ApplyingToModel { [TestFixture] public class HasManyToManyCollectionConventionTests { private PersistenceModel model; [SetUp] public void CreatePersistenceModel() { model = new PersistenceModel(); } [Test] public void ShouldSetAccessProperty() { Convention(x => x.Access.Property()); VerifyModel(x => x.Access.ShouldEqual("property")); } [Test] public void ShouldSetBatchSizeProperty() { Convention(x => x.BatchSize(100)); VerifyModel(x => x.BatchSize.ShouldEqual(100)); } [Test] public void ShouldSetCacheProperty() { Convention(x => x.Cache.ReadWrite()); VerifyModel(x => x.Cache.Usage.ShouldEqual("read-write")); } [Test] public void ShouldSetCascadeProperty() { Convention(x => x.Cascade.None()); VerifyModel(x => x.Cascade.ShouldEqual("none")); } [Test] public void ShouldSetCheckConstraintProperty() { Convention(x => x.Check("constraint = 0")); VerifyModel(x => x.Check.ShouldEqual("constraint = 0")); } [Test] public void ShouldSetCollectionTypeProperty() { Convention(x => x.CollectionType<string>()); VerifyModel(x => x.CollectionType.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ShouldSetFetchProperty() { Convention(x => x.Fetch.Select()); VerifyModel(x => x.Fetch.ShouldEqual("select")); } [Test] public void ShouldSetGenericProperty() { Convention(x => x.Generic()); VerifyModel(x => x.Generic.ShouldBeTrue()); } [Test] public void ShouldSetInverseProperty() { Convention(x => x.Inverse()); VerifyModel(x => x.Inverse.ShouldBeTrue()); } [Test] public void ShouldSetParentKeyColumnNameProperty() { Convention(x => x.Key.Column("xxx")); VerifyModel(x => x.Key.Columns.First().Name.ShouldEqual("xxx")); } [Test] public void ShouldSetElementColumnNameProperty() { Convention(x => x.Element.Column("xxx")); VerifyModel(x => x.Element.Columns.First().Name.ShouldEqual("xxx")); } [Test] public void ShouldSetElementTypePropertyUsingGeneric() { Convention(x => x.Element.Type<string>()); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ShouldSetElementTypePropertyUsingTypeOf() { Convention(x => x.Element.Type(typeof(string))); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ShouldSetElementTypePropertyUsingString() { Convention(x => x.Element.Type(typeof(string).AssemblyQualifiedName)); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ShouldSetLazyProperty() { Convention(x => x.LazyLoad()); VerifyModel(x => x.Lazy.ShouldEqual(Lazy.True)); } [Test] public void ShouldSetOptimisticLockProperty() { Convention(x => x.OptimisticLock()); VerifyModel(x => x.OptimisticLock.ShouldEqual(true)); } [Test] public void ShouldSetPersisterProperty() { Convention(x => x.Persister<SecondCustomPersister>()); VerifyModel(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(SecondCustomPersister))); } [Test] public void ShouldSetSchemaProperty() { Convention(x => x.Schema("test")); VerifyModel(x => x.Schema.ShouldEqual("test")); } [Test] public void ShouldSetWhereProperty() { Convention(x => x.Where("y = 2")); VerifyModel(x => x.Where.ShouldEqual("y = 2")); } [Test] public void ShouldSetTableNameProperty() { Convention(x => x.Table("xxx")); VerifyModel(x => x.TableName.ShouldEqual("xxx")); } #region Helpers private void Convention(Action<ICollectionInstance> convention) { model.Conventions.Add(new CollectionConventionBuilder().Always(convention)); } private void VerifyModel(Action<CollectionMapping> modelVerification) { var classMap = new ClassMap<ExampleInheritedClass>(); classMap.Id(x => x.Id); var map = classMap.HasManyToMany(x => x.Children); model.Add(classMap); var generatedModels = model.BuildMappings(); var modelInstance = generatedModels .First(x => x.Classes.FirstOrDefault(c => c.Type == typeof(ExampleInheritedClass)) != null) .Classes.First() .Collections.First(); modelVerification(modelInstance); } #endregion } }
// // ApplicationPkcs7Mime.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Collections.Generic; using MimeKit.IO; namespace MimeKit.Cryptography { /// <summary> /// An S/MIME part with a Content-Type of application/pkcs7-mime. /// </summary> /// <remarks> /// An application/pkcs7-mime is an S/MIME part and may contain encrypted, /// signed or compressed data (or any combination of the above). /// </remarks> public class ApplicationPkcs7Mime : MimePart { /// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> class. /// </summary> /// <remarks> /// This constructor is used by <see cref="MimeKit.MimeParser"/>. /// </remarks> /// <param name="args">Information used by the constructor.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="args"/> is <c>null</c>. /// </exception> public ApplicationPkcs7Mime (MimeEntityConstructorArgs args) : base (args) { } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> class. /// </summary> /// <remarks> /// <para>Creates a new MIME part with a Content-Type of application/pkcs7-mime /// and the <paramref name="stream"/> as its content.</para> /// <para>Unless you are writing your own pkcs7 implementation, you'll probably /// want to use the <see cref="Compress(MimeEntity)"/>, /// <see cref="Encrypt(CmsRecipientCollection, MimeEntity)"/>, and/or /// <see cref="Sign(CmsSigner, MimeEntity)"/> method to create new instances /// of this class.</para> /// </remarks> /// <param name="type">The S/MIME type.</param> /// <param name="stream">The content stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="type"/> is not a valid value. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ApplicationPkcs7Mime (SecureMimeType type, Stream stream) : base ("application", "pkcs7-mime") { ContentDisposition = new ContentDisposition (ContentDisposition.Attachment); ContentTransferEncoding = ContentEncoding.Base64; ContentObject = new ContentObject (stream); switch (type) { case SecureMimeType.CompressedData: ContentType.Parameters["smime-type"] = "compressed-data"; ContentDisposition.FileName = "smime.p7z"; ContentType.Name = "smime.p7z"; break; case SecureMimeType.EnvelopedData: ContentType.Parameters["smime-type"] = "enveloped-data"; ContentDisposition.FileName = "smime.p7m"; ContentType.Name = "smime.p7m"; break; case SecureMimeType.SignedData: ContentType.Parameters["smime-type"] = "signed-data"; ContentDisposition.FileName = "smime.p7m"; ContentType.Name = "smime.p7m"; break; case SecureMimeType.CertsOnly: ContentType.Parameters["smime-type"] = "certs-only"; ContentDisposition.FileName = "smime.p7c"; ContentType.Name = "smime.p7c"; break; default: throw new ArgumentOutOfRangeException ("type"); } } /// <summary> /// Gets the value of the "smime-type" parameter. /// </summary> /// <remarks> /// Gets the value of the "smime-type" parameter. /// </remarks> /// <value>The value of the "smime-type" parameter.</value> public SecureMimeType SecureMimeType { get { var type = ContentType.Parameters["smime-type"]; if (type == null) return SecureMimeType.Unknown; switch (type.ToLowerInvariant ()) { case "compressed-data": return SecureMimeType.CompressedData; case "enveloped-data": return SecureMimeType.EnvelopedData; case "signed-data": return SecureMimeType.SignedData; case "certs-only": return SecureMimeType.CertsOnly; default: return SecureMimeType.Unknown; } } } /// <summary> /// Dispatches to the specific visit method for this MIME entity. /// </summary> /// <remarks> /// This default implementation for <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> nodes /// calls <see cref="MimeKit.MimeVisitor.VisitApplicationPkcs7Mime"/>. Override this /// method to call into a more specific method on a derived visitor class /// of the <see cref="MimeKit.MimeVisitor"/> class. However, it should still /// support unknown visitors by calling /// <see cref="MimeKit.MimeVisitor.VisitApplicationPkcs7Mime"/>. /// </remarks> /// <param name="visitor">The visitor.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="visitor"/> is <c>null</c>. /// </exception> public override void Accept (MimeVisitor visitor) { if (visitor == null) throw new ArgumentNullException ("visitor"); visitor.VisitApplicationPkcs7Mime (this); } /// <summary> /// Decompresses the content. /// </summary> /// <remarks> /// Decompresses the content using the specified <see cref="SecureMimeContext"/>. /// </remarks> /// <returns>The decompressed <see cref="MimeKit.MimeEntity"/>.</returns> /// <param name="ctx">The S/MIME context to use for decompressing.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="ctx"/> is <c>null</c>. /// </exception> /// <exception cref="System.InvalidOperationException"> /// The "smime-type" parameter on the Content-Type header is not "compressed-data". /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public MimeEntity Decompress (SecureMimeContext ctx) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (SecureMimeType != SecureMimeType.CompressedData) throw new InvalidOperationException (); using (var memory = new MemoryBlockStream ()) { ContentObject.DecodeTo (memory); memory.Position = 0; return ctx.Decompress (memory); } } /// <summary> /// Decompresses the content. /// </summary> /// <remarks> /// Decompresses the content using the default <see cref="SecureMimeContext"/>. /// </remarks> /// <returns>The decompressed <see cref="MimeKit.MimeEntity"/>.</returns> /// <exception cref="System.InvalidOperationException"> /// The "smime-type" parameter on the Content-Type header is not "compressed-data". /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public MimeEntity Decompress () { if (SecureMimeType != SecureMimeType.CompressedData) throw new InvalidOperationException (); using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) { return Decompress (ctx); } } /// <summary> /// Decrypts the content. /// </summary> /// <remarks> /// Decrypts the content using the specified <see cref="SecureMimeContext"/>. /// </remarks> /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns> /// <param name="ctx">The S/MIME context to use for decrypting.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="ctx"/> is <c>null</c>. /// </exception> /// <exception cref="System.InvalidOperationException"> /// The "smime-type" parameter on the Content-Type header is not "enveloped-data". /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public MimeEntity Decrypt (SecureMimeContext ctx) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (SecureMimeType != SecureMimeType.EnvelopedData) throw new InvalidOperationException (); using (var memory = new MemoryBlockStream ()) { ContentObject.DecodeTo (memory); memory.Position = 0; return ctx.Decrypt (memory); } } /// <summary> /// Decrypts the content. /// </summary> /// <remarks> /// Decrypts the content using the default <see cref="SecureMimeContext"/>. /// </remarks> /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns> /// <exception cref="System.InvalidOperationException"> /// The "smime-type" parameter on the Content-Type header is not "certs-only". /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public MimeEntity Decrypt () { using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) { return Decrypt (ctx); } } /// <summary> /// Imports the certificates contained in the content. /// </summary> /// <remarks> /// Imports the certificates contained in the content. /// </remarks> /// <param name="ctx">The S/MIME context to import certificates into.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="ctx"/> is <c>null</c>. /// </exception> /// <exception cref="System.InvalidOperationException"> /// The "smime-type" parameter on the Content-Type header is not "certs-only". /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public void Import (SecureMimeContext ctx) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (SecureMimeType != SecureMimeType.CertsOnly) throw new InvalidOperationException (); using (var memory = new MemoryBlockStream ()) { ContentObject.DecodeTo (memory); memory.Position = 0; ctx.Import (memory); } } /// <summary> /// Verifies the signed-data and returns the unencapsulated <see cref="MimeKit.MimeEntity"/>. /// </summary> /// <remarks> /// Verifies the signed-data and returns the unencapsulated <see cref="MimeKit.MimeEntity"/>. /// </remarks> /// <returns>The list of digital signatures.</returns> /// <param name="ctx">The S/MIME context to use for verifying the signature.</param> /// <param name="entity">The unencapsulated entity.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="ctx"/> is <c>null</c>. /// </exception> /// <exception cref="System.InvalidOperationException"> /// The "smime-type" parameter on the Content-Type header is not "signed-data". /// </exception> /// <exception cref="System.FormatException"> /// The extracted content could not be parsed as a MIME entity. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public DigitalSignatureCollection Verify (SecureMimeContext ctx, out MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (SecureMimeType != SecureMimeType.SignedData) throw new InvalidOperationException (); using (var memory = new MemoryBlockStream ()) { ContentObject.DecodeTo (memory); memory.Position = 0; return ctx.Verify (memory, out entity); } } /// <summary> /// Verifies the signed-data and returns the unencapsulated <see cref="MimeKit.MimeEntity"/>. /// </summary> /// <remarks> /// Verifies the signed-data and returns the unencapsulated <see cref="MimeKit.MimeEntity"/>. /// </remarks> /// <returns>The list of digital signatures.</returns> /// <param name="entity">The unencapsulated entity.</param> /// <exception cref="System.InvalidOperationException"> /// The "smime-type" parameter on the Content-Type header is not "signed-data". /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public DigitalSignatureCollection Verify (out MimeEntity entity) { using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) { return Verify (ctx, out entity); } } /// <summary> /// Compresses the specified entity. /// </summary> /// <remarks> /// <para>Compresses the specified entity using the specified <see cref="SecureMimeContext"/>.</para> /// <para><alert class="warning">Most mail clients, even among those that support S/MIME, /// do not support compression.</alert></para> /// </remarks> /// <returns>The compressed entity.</returns> /// <param name="ctx">The S/MIME context to use for compressing.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="ctx"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime Compress (SecureMimeContext ctx, MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (entity == null) throw new ArgumentNullException ("entity"); using (var memory = new MemoryBlockStream ()) { var options = FormatOptions.CloneDefault (); options.NewLineFormat = NewLineFormat.Dos; entity.WriteTo (options, memory); memory.Position = 0; return ctx.Compress (memory); } } /// <summary> /// Compresses the specified entity. /// </summary> /// <remarks> /// <para>Compresses the specified entity using the default <see cref="SecureMimeContext"/>.</para> /// <para><alert class="warning">Most mail clients, even among those that support S/MIME, /// do not support compression.</alert></para> /// </remarks> /// <returns>The compressed entity.</returns> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="entity"/> is <c>null</c>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime Compress (MimeEntity entity) { if (entity == null) throw new ArgumentNullException ("entity"); using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) { return Compress (ctx, entity); } } /// <summary> /// Encrypts the specified entity. /// </summary> /// <remarks> /// Encrypts the entity to the specified recipients using the supplied <see cref="SecureMimeContext"/>. /// </remarks> /// <returns>The encrypted entity.</returns> /// <param name="ctx">The S/MIME context to use for encrypting.</param> /// <param name="recipients">The recipients.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="ctx"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime Encrypt (SecureMimeContext ctx, CmsRecipientCollection recipients, MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var memory = new MemoryBlockStream ()) { var options = FormatOptions.CloneDefault (); options.NewLineFormat = NewLineFormat.Dos; entity.WriteTo (options, memory); memory.Position = 0; return ctx.Encrypt (recipients, memory); } } /// <summary> /// Encrypts the specified entity. /// </summary> /// <remarks> /// Encrypts the entity to the specified recipients using the default <see cref="SecureMimeContext"/>. /// </remarks> /// <returns>The encrypted entity.</returns> /// <param name="recipients">The recipients.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime Encrypt (CmsRecipientCollection recipients, MimeEntity entity) { if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) { return Encrypt (ctx, recipients, entity); } } /// <summary> /// Encrypts the specified entity. /// </summary> /// <remarks> /// Encrypts the entity to the specified recipients using the supplied <see cref="SecureMimeContext"/>. /// </remarks> /// <returns>The encrypted entity.</returns> /// <param name="ctx">The S/MIME context to use for encrypting.</param> /// <param name="recipients">The recipients.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="ctx"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// Valid certificates could not be found for one or more of the <paramref name="recipients"/>. /// </exception> /// <exception cref="CertificateNotFoundException"> /// A certificate could not be found for one or more of the <paramref name="recipients"/>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime Encrypt (SecureMimeContext ctx, IEnumerable<MailboxAddress> recipients, MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var memory = new MemoryBlockStream ()) { var options = FormatOptions.CloneDefault (); options.NewLineFormat = NewLineFormat.Dos; entity.WriteTo (options, memory); memory.Position = 0; return (ApplicationPkcs7Mime) ctx.Encrypt (recipients, memory); } } /// <summary> /// Encrypts the specified entity. /// </summary> /// <remarks> /// Encrypts the entity to the specified recipients using the default <see cref="SecureMimeContext"/>. /// </remarks> /// <returns>The encrypted entity.</returns> /// <param name="recipients">The recipients.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// Valid certificates could not be found for one or more of the <paramref name="recipients"/>. /// </exception> /// <exception cref="CertificateNotFoundException"> /// A certificate could not be found for one or more of the <paramref name="recipients"/>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime Encrypt (IEnumerable<MailboxAddress> recipients, MimeEntity entity) { if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) { return Encrypt (ctx, recipients, entity); } } /// <summary> /// Cryptographically signs the specified entity. /// </summary> /// <remarks> /// <para>Signs the entity using the supplied signer and <see cref="SecureMimeContext"/>.</para> /// <para>For better interoperability with other mail clients, you should use /// <see cref="MultipartSigned.Create(SecureMimeContext, CmsSigner, MimeEntity)"/> /// instead as the multipart/signed format is supported among a much larger /// subset of mail client software.</para> /// </remarks> /// <returns>The signed entity.</returns> /// <param name="ctx">The S/MIME context to use for signing.</param> /// <param name="signer">The signer.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="ctx"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime Sign (SecureMimeContext ctx, CmsSigner signer, MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (signer == null) throw new ArgumentNullException ("signer"); if (entity == null) throw new ArgumentNullException ("entity"); using (var memory = new MemoryBlockStream ()) { var options = FormatOptions.CloneDefault (); options.NewLineFormat = NewLineFormat.Dos; entity.WriteTo (options, memory); memory.Position = 0; return ctx.EncapsulatedSign (signer, memory); } } /// <summary> /// Cryptographically signs the specified entity. /// </summary> /// <remarks> /// <para>Signs the entity using the supplied signer.</para> /// <para>For better interoperability with other mail clients, you should use /// <see cref="MultipartSigned.Create(SecureMimeContext, CmsSigner, MimeEntity)"/> /// instead as the multipart/signed format is supported among a much larger /// subset of mail client software.</para> /// </remarks> /// <returns>The signed entity.</returns> /// <param name="signer">The signer.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime Sign (CmsSigner signer, MimeEntity entity) { if (signer == null) throw new ArgumentNullException ("signer"); if (entity == null) throw new ArgumentNullException ("entity"); using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) { return Sign (ctx, signer, entity); } } /// <summary> /// Cryptographically signs the specified entity. /// </summary> /// <remarks> /// <para>Signs the entity using the supplied signer, digest algorithm and <see cref="SecureMimeContext"/>.</para> /// <para>For better interoperability with other mail clients, you should use /// <see cref="MultipartSigned.Create(SecureMimeContext, CmsSigner, MimeEntity)"/> /// instead as the multipart/signed format is supported among a much larger /// subset of mail client software.</para> /// </remarks> /// <returns>The signed entity.</returns> /// <param name="ctx">The S/MIME context to use for signing.</param> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="ctx"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="CertificateNotFoundException"> /// A signing certificate could not be found for <paramref name="signer"/>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime Sign (SecureMimeContext ctx, MailboxAddress signer, DigestAlgorithm digestAlgo, MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (signer == null) throw new ArgumentNullException ("signer"); if (entity == null) throw new ArgumentNullException ("entity"); using (var memory = new MemoryBlockStream ()) { var options = FormatOptions.CloneDefault (); options.NewLineFormat = NewLineFormat.Dos; entity.WriteTo (options, memory); memory.Position = 0; return ctx.EncapsulatedSign (signer, digestAlgo, memory); } } /// <summary> /// Cryptographically signs the specified entity. /// </summary> /// <remarks> /// <para>Signs the entity using the supplied signer and digest algorithm.</para> /// <para>For better interoperability with other mail clients, you should use /// <see cref="MultipartSigned.Create(SecureMimeContext, CmsSigner, MimeEntity)"/> /// instead as the multipart/signed format is supported among a much larger /// subset of mail client software.</para> /// </remarks> /// <returns>The signed entity.</returns> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="CertificateNotFoundException"> /// A signing certificate could not be found for <paramref name="signer"/>. /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, MimeEntity entity) { if (signer == null) throw new ArgumentNullException ("signer"); if (entity == null) throw new ArgumentNullException ("entity"); using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) { return Sign (ctx, signer, digestAlgo, entity); } } /// <summary> /// Cryptographically signs and encrypts the specified entity. /// </summary> /// <remarks> /// Cryptographically signs entity using the supplied signer and then /// encrypts the result to the specified recipients. /// </remarks> /// <returns>The signed and encrypted entity.</returns> /// <param name="ctx">The S/MIME context to use for signing and encrypting.</param> /// <param name="signer">The signer.</param> /// <param name="recipients">The recipients.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="ctx"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime SignAndEncrypt (SecureMimeContext ctx, CmsSigner signer, CmsRecipientCollection recipients, MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (signer == null) throw new ArgumentNullException ("signer"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); return Encrypt (ctx, recipients, MultipartSigned.Create (ctx, signer, entity)); } /// <summary> /// Cryptographically signs and encrypts the specified entity. /// </summary> /// <remarks> /// Cryptographically signs entity using the supplied signer and then /// encrypts the result to the specified recipients. /// </remarks> /// <returns>The signed and encrypted entity.</returns> /// <param name="signer">The signer.</param> /// <param name="recipients">The recipients.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime SignAndEncrypt (CmsSigner signer, CmsRecipientCollection recipients, MimeEntity entity) { if (signer == null) throw new ArgumentNullException ("signer"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) { return SignAndEncrypt (ctx, signer, recipients, entity); } } /// <summary> /// Cryptographically signs and encrypts the specified entity. /// </summary> /// <remarks> /// Cryptographically signs entity using the supplied signer and then /// encrypts the result to the specified recipients. /// </remarks> /// <returns>The signed and encrypted entity.</returns> /// <param name="ctx">The S/MIME context to use for signing and encrypting.</param> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="recipients">The recipients.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="ctx"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="CertificateNotFoundException"> /// <para>A signing certificate could not be found for <paramref name="signer"/>.</para> /// <para>-or-</para> /// <para>A certificate could not be found for one or more of the <paramref name="recipients"/>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime SignAndEncrypt (SecureMimeContext ctx, MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, MimeEntity entity) { if (ctx == null) throw new ArgumentNullException ("ctx"); if (signer == null) throw new ArgumentNullException ("signer"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); return Encrypt (ctx, recipients, MultipartSigned.Create (ctx, signer, digestAlgo, entity)); } /// <summary> /// Cryptographically signs and encrypts the specified entity. /// </summary> /// <remarks> /// Cryptographically signs entity using the supplied signer and then /// encrypts the result to the specified recipients. /// </remarks> /// <returns>The signed and encrypted entity.</returns> /// <param name="signer">The signer.</param> /// <param name="digestAlgo">The digest algorithm to use for signing.</param> /// <param name="recipients">The recipients.</param> /// <param name="entity">The entity.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="signer"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="entity"/> is <c>null</c>.</para> /// </exception> /// <exception cref="CertificateNotFoundException"> /// <para>A signing certificate could not be found for <paramref name="signer"/>.</para> /// <para>-or-</para> /// <para>A certificate could not be found for one or more of the <paramref name="recipients"/>.</para> /// </exception> /// <exception cref="Org.BouncyCastle.Cms.CmsException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public static ApplicationPkcs7Mime SignAndEncrypt (MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, MimeEntity entity) { if (signer == null) throw new ArgumentNullException ("signer"); if (recipients == null) throw new ArgumentNullException ("recipients"); if (entity == null) throw new ArgumentNullException ("entity"); using (var ctx = (SecureMimeContext) CryptographyContext.Create ("application/pkcs7-mime")) { return SignAndEncrypt (ctx, signer, digestAlgo, recipients, entity); } } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System; using System.Reflection; using System.Threading.Tasks; using Scriban.Parsing; using Scriban.Syntax; namespace Scriban.Runtime { /// <summary> /// Generic function wrapper handling any kind of function parameters. /// </summary> public partial class DelegateCustomFunction : DynamicCustomFunction { private readonly Delegate _del; public DelegateCustomFunction(Delegate del) : base(del?.Method) { _del = del ?? throw new ArgumentNullException(nameof(del)); Target = del.Target; } public DelegateCustomFunction(object target, MethodInfo method) : base(method) { Target = target; } public object Target { get; } public override object Invoke(TemplateContext context, ScriptNode callerContext, ScriptArray scriptArguments, ScriptBlockStatement blockStatement) { Array paramArguments = null; var arguments = PrepareArguments(context, callerContext, scriptArguments, ref paramArguments); try { // Call the method via reflection var result = InvokeImpl(context, callerContext.Span, arguments); return result; } catch (TargetInvocationException exception) { if (exception.InnerException != null) { throw exception.InnerException; } throw new ScriptRuntimeException(callerContext.Span, $"Unexpected exception when calling {callerContext}"); } finally { context.ReleaseReflectionArguments(arguments); } } #if !SCRIBAN_NO_ASYNC public override async ValueTask<object> InvokeAsync(TemplateContext context, ScriptNode callerContext, ScriptArray scriptArguments, ScriptBlockStatement blockStatement) { Array paramArguments = null; var arguments = PrepareArguments(context, callerContext, scriptArguments, ref paramArguments); try { // Call the method via reflection var result = InvokeImpl(context, callerContext.Span, arguments); return IsAwaitable ? await ConfigureAwait(result) : result; } catch (TargetInvocationException exception) { if (exception.InnerException != null) { throw exception.InnerException; } throw new ScriptRuntimeException(callerContext.Span, $"Unexpected exception when calling {callerContext}"); } finally { context.ReleaseReflectionArguments(arguments); } } #endif public static DelegateCustomFunction Create(Action action) { if (action == null) throw new ArgumentNullException(nameof(action)); return new DelegateCustomAction(action); } public static DelegateCustomFunction Create<T>(Action<T> action) { if (action == null) throw new ArgumentNullException(nameof(action)); return new DelegateCustomAction<T>(action); } public static DelegateCustomFunction Create<T1, T2>(Action<T1, T2> action) { if (action == null) throw new ArgumentNullException(nameof(action)); return new DelegateCustomAction<T1, T2>(action); } public static DelegateCustomFunction Create<T1, T2, T3>(Action<T1, T2, T3> action) { if (action == null) throw new ArgumentNullException(nameof(action)); return new DelegateCustomAction<T1, T2, T3>(action); } public static DelegateCustomFunction Create<T1, T2, T3, T4>(Action<T1, T2, T3, T4> action) { if (action == null) throw new ArgumentNullException(nameof(action)); return new DelegateCustomAction<T1, T2, T3, T4>(action); } public static DelegateCustomFunction Create<T1, T2, T3, T4, T5>(Action<T1, T2, T3, T4, T5> action) { if (action == null) throw new ArgumentNullException(nameof(action)); return new DelegateCustomAction<T1, T2, T3, T4, T5>(action); } public static DelegateCustomFunction CreateFunc<TResult>(Func<TResult> func) { if (func == null) throw new ArgumentNullException(nameof(func)); return new InternalDelegateCustomFunction<TResult>(func); } public static DelegateCustomFunction CreateFunc<T1, TResult>(Func<T1, TResult> func) { if (func == null) throw new ArgumentNullException(nameof(func)); return new InternalDelegateCustomFunction<T1, TResult>(func); } public static DelegateCustomFunction CreateFunc<T1, T2, TResult>(Func<T1, T2, TResult> func) { if (func == null) throw new ArgumentNullException(nameof(func)); return new InternalDelegateCustomFunction<T1, T2, TResult>(func); } public static DelegateCustomFunction CreateFunc<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> func) { if (func == null) throw new ArgumentNullException(nameof(func)); return new InternalDelegateCustomFunction<T1, T2, T3, TResult>(func); } public static DelegateCustomFunction CreateFunc<T1, T2, T3, T4, TResult>(Func<T1, T2, T3, T4, TResult> func) { if (func == null) throw new ArgumentNullException(nameof(func)); return new InternalDelegateCustomFunction<T1, T2, T3, T4, TResult>(func); } public static DelegateCustomFunction CreateFunc<T1, T2, T3, T4, T5, TResult>(Func<T1, T2, T3, T4, T5, TResult> func) { if (func == null) throw new ArgumentNullException(nameof(func)); return new InternalDelegateCustomFunction<T1, T2, T3, T4, T5, TResult>(func); } protected virtual object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { return _del != null ? _del.DynamicInvoke(arguments) : Method.Invoke(Target, arguments); } private object[] PrepareArguments(TemplateContext context, ScriptNode callerContext, ScriptArray scriptArguments, ref Array paramsArguments) { // TODO: optimize arguments allocations var reflectArgs = context.GetOrCreateReflectionArguments(Parameters.Length); // Copy TemplateContext/SourceSpan parameters if (_hasTemplateContext) { reflectArgs[0] = context; if (_hasSpan) { reflectArgs[1] = callerContext.Span; } } // Convert arguments paramsArguments = null; if (_varParamKind == ScriptVarParamKind.LastParameter) { // 0 1 _firstIndexOfUserParameters _paramsIndex // [context, [span]], arg0, arg1..., ,argn, [varg0,varg1, ...] var varArgs = (ScriptArray)scriptArguments[scriptArguments.Count - 1]; // Copy all normal arguments var normalArgCount = scriptArguments.Count - 1; if (normalArgCount > 0) { scriptArguments.CopyTo(0, reflectArgs, _firstIndexOfUserParameters, normalArgCount); } paramsArguments = _paramsElementType == typeof(object) ? context.GetOrCreateReflectionArguments(varArgs.Count) : Array.CreateInstance(_paramsElementType, varArgs.Count); reflectArgs[_paramsIndex] = paramsArguments; // Convert each argument for(int i = 0; i < varArgs.Count; i++) { var destValue = context.ToObject(context.CurrentSpan, varArgs[i], _paramsElementType); paramsArguments.SetValue(destValue, i); } } else { scriptArguments.CopyTo(0, reflectArgs, _firstIndexOfUserParameters, scriptArguments.Count); } return reflectArgs; } /// <summary> /// A custom function taking one argument. /// </summary> /// <typeparam name="TResult">Type result</typeparam> private class InternalDelegateCustomFunction<TResult> : DelegateCustomFunction { public InternalDelegateCustomFunction(Func<TResult> func) : base(func) { Func = func; } public Func<TResult> Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { return Func(); } } /// <summary> /// A custom function taking one argument. /// </summary> /// <typeparam name="T">Func 0 arg type</typeparam> /// <typeparam name="TResult">Type result</typeparam> private class InternalDelegateCustomFunction<T, TResult> : DelegateCustomFunction { public InternalDelegateCustomFunction(Func<T, TResult> func) : base(func) { Func = func; } public Func<T, TResult> Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { var arg = (T)arguments[0]; return Func(arg); } } /// <summary> /// A custom action taking 1 argument. /// </summary> /// <typeparam name="T">Func 0 arg type</typeparam> private class DelegateCustomAction<T> : DelegateCustomFunction { public DelegateCustomAction(Action<T> func) : base(func) { Func = func; } public Action<T> Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { var arg = (T)arguments[0]; Func(arg); return null; } } /// <summary> /// A custom function taking 2 arguments. /// </summary> /// <typeparam name="T1">Func 0 arg type</typeparam> /// <typeparam name="T2">Func 1 arg type</typeparam> /// <typeparam name="TResult">Type result</typeparam> private class InternalDelegateCustomFunction<T1, T2, TResult> : DelegateCustomFunction { public InternalDelegateCustomFunction(Func<T1, T2, TResult> func) : base(func) { Func = func; } public Func<T1, T2, TResult> Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { var arg1 = (T1)arguments[0]; var arg2 = (T2)arguments[1]; return Func(arg1, arg2); } } /// <summary> /// A custom action taking 2 arguments. /// </summary> /// <typeparam name="T1">Func 0 arg type</typeparam> /// <typeparam name="T2">Func 1 arg type</typeparam> private class DelegateCustomAction<T1, T2> : DelegateCustomFunction { public DelegateCustomAction(Action<T1, T2> func) : base(func) { Func = func; } public Action<T1, T2> Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { var arg1 = (T1)arguments[0]; var arg2 = (T2)arguments[1]; Func(arg1, arg2); return null; } } /// <summary> /// A custom function taking 3 arguments. /// </summary> /// <typeparam name="T1">Func 0 arg type</typeparam> /// <typeparam name="T2">Func 1 arg type</typeparam> /// <typeparam name="T3">Func 2 arg type</typeparam> /// <typeparam name="TResult">Type result</typeparam> private class InternalDelegateCustomFunction<T1, T2, T3, TResult> : DelegateCustomFunction { public InternalDelegateCustomFunction(Func<T1, T2, T3, TResult> func) : base(func) { Func = func; } public Func<T1, T2, T3, TResult> Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { var arg1 = (T1)arguments[0]; var arg2 = (T2)arguments[1]; var arg3 = (T3)arguments[2]; return Func(arg1, arg2, arg3); } } /// <summary> /// A custom action taking 3 arguments. /// </summary> /// <typeparam name="T1">Func 0 arg type</typeparam> /// <typeparam name="T2">Func 1 arg type</typeparam> /// <typeparam name="T3">Func 2 arg type</typeparam> private class DelegateCustomAction<T1, T2, T3> : DelegateCustomFunction { public DelegateCustomAction(Action<T1, T2, T3> func) : base(func) { Func = func; } public Action<T1, T2, T3> Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { var arg1 = (T1)arguments[0]; var arg2 = (T2)arguments[1]; var arg3 = (T3)arguments[2]; Func(arg1, arg2, arg3); return null; } } /// <summary> /// A custom function taking 4 arguments. /// </summary> /// <typeparam name="T1">Func 0 arg type</typeparam> /// <typeparam name="T2">Func 1 arg type</typeparam> /// <typeparam name="T3">Func 2 arg type</typeparam> /// <typeparam name="T4">Func 3 arg type</typeparam> /// <typeparam name="TResult">Type result</typeparam> private class InternalDelegateCustomFunction<T1, T2, T3, T4, TResult> : DelegateCustomFunction { public InternalDelegateCustomFunction(Func<T1, T2, T3, T4, TResult> func) : base(func) { Func = func; } public Func<T1, T2, T3, T4, TResult> Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { var arg1 = (T1)arguments[0]; var arg2 = (T2)arguments[1]; var arg3 = (T3)arguments[2]; var arg4 = (T4)arguments[3]; return Func(arg1, arg2, arg3, arg4); } } /// <summary> /// A custom action taking 4 arguments. /// </summary> /// <typeparam name="T1">Func 0 arg type</typeparam> /// <typeparam name="T2">Func 1 arg type</typeparam> /// <typeparam name="T3">Func 2 arg type</typeparam> /// <typeparam name="T4">Func 3 arg type</typeparam> private class DelegateCustomAction<T1, T2, T3, T4> : DelegateCustomFunction { public DelegateCustomAction(Action<T1, T2, T3, T4> func) : base(func) { Func = func; } public Action<T1, T2, T3, T4> Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { var arg1 = (T1)arguments[0]; var arg2 = (T2)arguments[1]; var arg3 = (T3)arguments[2]; var arg4 = (T4)arguments[3]; Func(arg1, arg2, arg3, arg4); return null; } } /// <summary> /// A custom function taking 5 arguments. /// </summary> /// <typeparam name="T1">Func 0 arg type</typeparam> /// <typeparam name="T2">Func 1 arg type</typeparam> /// <typeparam name="T3">Func 2 arg type</typeparam> /// <typeparam name="T4">Func 3 arg type</typeparam> /// <typeparam name="T5">Func 4 arg type</typeparam> /// <typeparam name="TResult">Type result</typeparam> private class InternalDelegateCustomFunction<T1, T2, T3, T4, T5, TResult> : DelegateCustomFunction { public InternalDelegateCustomFunction(Func<T1, T2, T3, T4, T5, TResult> func) : base(func) { Func = func; } public Func<T1, T2, T3, T4, T5, TResult> Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { var arg1 = (T1)arguments[0]; var arg2 = (T2)arguments[1]; var arg3 = (T3)arguments[2]; var arg4 = (T4)arguments[3]; var arg5 = (T5)arguments[4]; return Func(arg1, arg2, arg3, arg4, arg5); } } /// <summary> /// A custom action taking 5 arguments. /// </summary> /// <typeparam name="T1">Func 0 arg type</typeparam> /// <typeparam name="T2">Func 1 arg type</typeparam> /// <typeparam name="T3">Func 2 arg type</typeparam> /// <typeparam name="T4">Func 3 arg type</typeparam> /// <typeparam name="T5">Func 4 arg type</typeparam> private class DelegateCustomAction<T1, T2, T3, T4, T5> : DelegateCustomFunction { public DelegateCustomAction(Action<T1, T2, T3, T4, T5> func) : base(func) { Func = func; } public Action<T1, T2, T3, T4, T5> Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { var arg1 = (T1)arguments[0]; var arg2 = (T2)arguments[1]; var arg3 = (T3)arguments[2]; var arg4 = (T4)arguments[3]; var arg5 = (T5)arguments[4]; Func(arg1, arg2, arg3, arg4, arg5); return null; } } } /// <summary> /// A custom action taking 1 argument. /// </summary> public class DelegateCustomAction : DelegateCustomFunction { public DelegateCustomAction(Action func) : base(func) { Func = func; } public Action Func { get; } protected override object InvokeImpl(TemplateContext context, SourceSpan span, object[] arguments) { Func(); return null; } } }
namespace KabMan.Forms { partial class NewSwitchForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NewSwitchForm)); KabMan.Controls.NameValuePair nameValuePair1 = new KabMan.Controls.NameValuePair(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule3 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); KabMan.Controls.NameValuePair nameValuePair2 = new KabMan.Controls.NameValuePair(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule2 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule1 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); KabMan.Controls.NameValuePair nameValuePair3 = new KabMan.Controls.NameValuePair(); KabMan.Controls.NameValuePair nameValuePair4 = new KabMan.Controls.NameValuePair(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule4 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); KabMan.Controls.NameValuePair nameValuePair5 = new KabMan.Controls.NameValuePair(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule5 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule6 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule7 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); KabMan.Controls.NameValuePair nameValuePair6 = new KabMan.Controls.NameValuePair(); KabMan.Controls.NameValuePair nameValuePair7 = new KabMan.Controls.NameValuePair(); KabMan.Controls.NameValuePair nameValuePair8 = new KabMan.Controls.NameValuePair(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule9 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule8 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule10 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); KabMan.Controls.NameValuePair nameValuePair9 = new KabMan.Controls.NameValuePair(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule11 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); KabMan.Controls.NameValuePair nameValuePair10 = new KabMan.Controls.NameValuePair(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule12 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); KabMan.Controls.NameValuePair nameValuePair11 = new KabMan.Controls.NameValuePair(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule14 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule conditionValidationRule13 = new DevExpress.XtraEditors.DXErrorProvider.ConditionValidationRule(); this.repositoryItemLookUpEdit13 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.btnSaveClose = new DevExpress.XtraEditors.SimpleButton(); this.btnClose = new DevExpress.XtraEditors.SimpleButton(); this.btnSave = new DevExpress.XtraEditors.SimpleButton(); this.CFirstTrunk = new KabMan.Controls.C_LookUpControl(); this.CSan = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit8 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CSanGroup = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit9 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CLcLength = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit2 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CLcCable = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit3 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CLcCount = new DevExpress.XtraEditors.SpinEdit(); this.CSwitchIP = new DevExpress.XtraEditors.TextEdit(); this.CSwitchSerial = new DevExpress.XtraEditors.TextEdit(); this.CBlech = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit1 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CBlechType = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit5 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CSwitchModel = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit4 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CCoreSwitch = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit6 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CSwitchType = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit7 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CVtPort = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit10 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CDataCenter = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit11 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CLocation = new KabMan.Controls.C_LookUpControl(); this.repositoryItemLookUpEdit12 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlGroup2 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlGroup3 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlGroup4 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlGroup6 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem10 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem8 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlGroup7 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem15 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem13 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem14 = new DevExpress.XtraLayout.LayoutControlItem(); this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem(); this.layoutControlItem16 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem17 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem19 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlGroup5 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem9 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem7 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem11 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem12 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem18 = new DevExpress.XtraLayout.LayoutControlItem(); this.CManagerValidator = new DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider(this.components); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit13)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CFirstTrunk.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CSan.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit8)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CSanGroup.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit9)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CLcLength.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CLcCable.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CLcCount.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CSwitchIP.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CSwitchSerial.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CBlech.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CBlechType.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit5)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CSwitchModel.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CCoreSwitch.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit6)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CSwitchType.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit7)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CVtPort.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit10)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CDataCenter.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit11)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CLocation.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit12)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup6)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem10)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem8)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup7)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem15)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem13)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem14)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem16)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem17)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem19)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup5)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem11)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem12)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem18)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CManagerValidator)).BeginInit(); this.SuspendLayout(); // // repositoryItemLookUpEdit13 // this.repositoryItemLookUpEdit13.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit13.Name = "repositoryItemLookUpEdit13"; this.repositoryItemLookUpEdit13.NullText = "Select Start Trunk Cable!"; // // layoutControl1 // this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.btnSaveClose); this.layoutControl1.Controls.Add(this.btnClose); this.layoutControl1.Controls.Add(this.btnSave); this.layoutControl1.Controls.Add(this.CFirstTrunk); this.layoutControl1.Controls.Add(this.CLcLength); this.layoutControl1.Controls.Add(this.CLcCable); this.layoutControl1.Controls.Add(this.CLcCount); this.layoutControl1.Controls.Add(this.CSwitchIP); this.layoutControl1.Controls.Add(this.CSwitchSerial); this.layoutControl1.Controls.Add(this.CBlech); this.layoutControl1.Controls.Add(this.CSwitchModel); this.layoutControl1.Controls.Add(this.CBlechType); this.layoutControl1.Controls.Add(this.CCoreSwitch); this.layoutControl1.Controls.Add(this.CSwitchType); this.layoutControl1.Controls.Add(this.CSan); this.layoutControl1.Controls.Add(this.CVtPort); this.layoutControl1.Controls.Add(this.CSanGroup); this.layoutControl1.Controls.Add(this.CDataCenter); this.layoutControl1.Controls.Add(this.CLocation); this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.layoutControl1.Location = new System.Drawing.Point(0, 0); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; this.layoutControl1.Size = new System.Drawing.Size(444, 615); this.layoutControl1.TabIndex = 0; this.layoutControl1.Text = "layoutControl1"; // // btnSaveClose // this.btnSaveClose.Location = new System.Drawing.Point(264, 582); this.btnSaveClose.Name = "btnSaveClose"; this.btnSaveClose.Size = new System.Drawing.Size(80, 22); this.btnSaveClose.StyleController = this.layoutControl1; this.btnSaveClose.TabIndex = 22; this.btnSaveClose.Text = "Save && Close"; this.btnSaveClose.Click += new System.EventHandler(this.btnSaveClose_Click); // // btnClose // this.btnClose.Location = new System.Drawing.Point(355, 582); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(80, 22); this.btnClose.StyleController = this.layoutControl1; this.btnClose.TabIndex = 21; this.btnClose.Text = "Close"; this.btnClose.Click += new System.EventHandler(this.cancelButton_Click); // // btnSave // this.btnSave.Location = new System.Drawing.Point(173, 582); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(80, 22); this.btnSave.StyleController = this.layoutControl1; this.btnSave.TabIndex = 20; this.btnSave.Text = "Save"; this.btnSave.Click += new System.EventHandler(this.defaultButton_Click); // // CFirstTrunk // this.CFirstTrunk.Columns = this.repositoryItemLookUpEdit13.Columns; this.CFirstTrunk.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CFirstTrunk.FormParameters"))); this.CFirstTrunk.Location = new System.Drawing.Point(78, 327); this.CFirstTrunk.Name = "CFirstTrunk"; this.CFirstTrunk.NullText = ""; nameValuePair1.Name = "@SanValue"; nameValuePair1.Value = null; this.CFirstTrunk.Parameters = new KabMan.Controls.NameValuePair[] { nameValuePair1}; this.CFirstTrunk.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.CFirstTrunk.Properties.NullText = ""; this.CFirstTrunk.RefreshButtonVisible = true; this.CFirstTrunk.Size = new System.Drawing.Size(360, 20); this.CFirstTrunk.StoredProcedure = null; this.CFirstTrunk.StyleController = this.layoutControl1; this.CFirstTrunk.TabIndex = 19; this.CFirstTrunk.TriggerControl = this.CSan; conditionValidationRule3.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule3.ErrorText = "This value is not valid"; conditionValidationRule3.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CFirstTrunk, conditionValidationRule3); this.CFirstTrunk.ValueMember = "Name"; this.CFirstTrunk.Triggering += new KabMan.Controls.TriggeringEventHandler(this.CFirstTrunk_Triggering); // // CSan // this.CSan.Columns = this.repositoryItemLookUpEdit8.Columns; this.CSan.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CSan.FormParameters"))); this.CSan.Location = new System.Drawing.Point(81, 293); this.CSan.Name = "CSan"; this.CSan.NullText = ""; nameValuePair2.Name = "@SanGroupID"; nameValuePair2.Value = null; this.CSan.Parameters = new KabMan.Controls.NameValuePair[] { nameValuePair2}; this.CSan.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.CSan.Properties.NullText = ""; this.CSan.RefreshButtonVisible = true; this.CSan.Size = new System.Drawing.Size(354, 20); this.CSan.StoredProcedure = null; this.CSan.StyleController = this.layoutControl1; this.CSan.TabIndex = 6; this.CSan.TriggerControl = this.CSanGroup; conditionValidationRule2.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule2.ErrorText = "This value is not valid"; conditionValidationRule2.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CSan, conditionValidationRule2); // // repositoryItemLookUpEdit8 // this.repositoryItemLookUpEdit8.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit8.Name = "repositoryItemLookUpEdit8"; this.repositoryItemLookUpEdit8.NullText = "Select SAN!"; // // CSanGroup // this.CSanGroup.AddButtonEnabled = true; this.CSanGroup.Columns = this.repositoryItemLookUpEdit9.Columns; this.CSanGroup.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CSanGroup.FormParameters"))); this.CSanGroup.Location = new System.Drawing.Point(81, 262); this.CSanGroup.Name = "CSanGroup"; this.CSanGroup.NullText = ""; this.CSanGroup.Parameters = new KabMan.Controls.NameValuePair[0]; this.CSanGroup.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CSanGroup.Properties.NullText = ""; this.CSanGroup.RefreshButtonVisible = true; this.CSanGroup.Size = new System.Drawing.Size(354, 20); this.CSanGroup.StoredProcedure = null; this.CSanGroup.StyleController = this.layoutControl1; this.CSanGroup.TabIndex = 4; this.CSanGroup.TriggerControl = null; conditionValidationRule1.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule1.ErrorText = "This value is not valid"; conditionValidationRule1.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CSanGroup, conditionValidationRule1); this.CSanGroup.EditValueChanged += new System.EventHandler(this.CSanGroup_EditValueChanged); // // repositoryItemLookUpEdit9 // this.repositoryItemLookUpEdit9.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.repositoryItemLookUpEdit9.Name = "repositoryItemLookUpEdit9"; this.repositoryItemLookUpEdit9.NullText = "Select San Group!"; // // CLcLength // this.CLcLength.AddButtonEnabled = true; this.CLcLength.Columns = this.repositoryItemLookUpEdit2.Columns; this.CLcLength.DisplayMember = "Length"; this.CLcLength.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CLcLength.FormParameters"))); this.CLcLength.Location = new System.Drawing.Point(81, 520); this.CLcLength.Name = "CLcLength"; this.CLcLength.NullText = ""; nameValuePair3.Name = "@CategoryID"; nameValuePair3.Value = "%"; nameValuePair4.Name = "@CategoryName"; nameValuePair4.Value = "LC"; this.CLcLength.Parameters = new KabMan.Controls.NameValuePair[] { nameValuePair3, nameValuePair4}; this.CLcLength.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CLcLength.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] { new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Length", "Length", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Near)}); this.CLcLength.Properties.NullText = ""; this.CLcLength.RefreshButtonVisible = true; this.CLcLength.Size = new System.Drawing.Size(182, 20); this.CLcLength.StoredProcedure = null; this.CLcLength.StyleController = this.layoutControl1; this.CLcLength.TabIndex = 16; this.CLcLength.TriggerControl = null; conditionValidationRule4.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule4.ErrorText = "This value is not valid"; conditionValidationRule4.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CLcLength, conditionValidationRule4); this.CLcLength.ValueMember = "Length"; this.CLcLength.EditValueChanged += new System.EventHandler(this.CLcLength_EditValueChanged); // // repositoryItemLookUpEdit2 // this.repositoryItemLookUpEdit2.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.repositoryItemLookUpEdit2.Name = "repositoryItemLookUpEdit2"; this.repositoryItemLookUpEdit2.NullText = "Select LC URM Length!"; // // CLcCable // this.CLcCable.Columns = this.repositoryItemLookUpEdit3.Columns; this.CLcCable.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CLcCable.FormParameters"))); this.CLcCable.Location = new System.Drawing.Point(81, 551); this.CLcCable.Name = "CLcCable"; this.CLcCable.NullText = ""; nameValuePair5.Name = "@Length"; nameValuePair5.Value = null; this.CLcCable.Parameters = new KabMan.Controls.NameValuePair[] { nameValuePair5}; this.CLcCable.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.CLcCable.Properties.NullText = ""; this.CLcCable.RefreshButtonVisible = true; this.CLcCable.Size = new System.Drawing.Size(354, 20); this.CLcCable.StoredProcedure = null; this.CLcCable.StyleController = this.layoutControl1; this.CLcCable.TabIndex = 15; this.CLcCable.TriggerControl = this.CLcLength; conditionValidationRule5.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule5.ErrorText = "This value is not valid"; conditionValidationRule5.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CLcCable, conditionValidationRule5); // // repositoryItemLookUpEdit3 // this.repositoryItemLookUpEdit3.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit3.Name = "repositoryItemLookUpEdit3"; this.repositoryItemLookUpEdit3.NullText = "Select LC URM Cable!"; // // CLcCount // this.CLcCount.EditValue = new decimal(new int[] { 1, 0, 0, 0}); this.CLcCount.Location = new System.Drawing.Point(345, 520); this.CLcCount.Name = "CLcCount"; this.CLcCount.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.CLcCount.Properties.MaxValue = new decimal(new int[] { -727379969, 232, 0, 0}); this.CLcCount.Properties.MinValue = new decimal(new int[] { 1, 0, 0, 0}); this.CLcCount.Size = new System.Drawing.Size(90, 20); this.CLcCount.StyleController = this.layoutControl1; this.CLcCount.TabIndex = 14; // // CSwitchIP // this.CSwitchIP.Location = new System.Drawing.Point(299, 121); this.CSwitchIP.Name = "CSwitchIP"; this.CSwitchIP.Properties.Mask.EditMask = "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(" + "25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; this.CSwitchIP.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx; this.CSwitchIP.Size = new System.Drawing.Size(136, 20); this.CSwitchIP.StyleController = this.layoutControl1; this.CSwitchIP.TabIndex = 13; conditionValidationRule6.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule6.ErrorText = "This value is not valid"; conditionValidationRule6.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CSwitchIP, conditionValidationRule6); // // CSwitchSerial // this.CSwitchSerial.Location = new System.Drawing.Point(81, 121); this.CSwitchSerial.Name = "CSwitchSerial"; this.CSwitchSerial.Size = new System.Drawing.Size(136, 20); this.CSwitchSerial.StyleController = this.layoutControl1; this.CSwitchSerial.TabIndex = 12; conditionValidationRule7.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule7.ErrorText = "This value is not valid"; conditionValidationRule7.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CSwitchSerial, conditionValidationRule7); // // CBlech // this.CBlech.Columns = this.repositoryItemLookUpEdit1.Columns; this.CBlech.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CBlech.FormParameters"))); this.CBlech.Location = new System.Drawing.Point(81, 465); this.CBlech.Name = "CBlech"; this.CBlech.NullText = ""; nameValuePair6.Name = "@BlechTypeID"; nameValuePair6.Value = null; nameValuePair7.Name = "@DataCenterID"; nameValuePair7.Value = null; nameValuePair8.Name = "@DeviceName"; nameValuePair8.Value = "Switch"; this.CBlech.Parameters = new KabMan.Controls.NameValuePair[] { nameValuePair6, nameValuePair7, nameValuePair8}; this.CBlech.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.CBlech.Properties.NullText = ""; this.CBlech.RefreshButtonVisible = true; this.CBlech.Size = new System.Drawing.Size(354, 20); this.CBlech.StoredProcedure = null; this.CBlech.StyleController = this.layoutControl1; this.CBlech.TabIndex = 11; this.CBlech.TriggerControl = this.CBlechType; conditionValidationRule9.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule9.ErrorText = "This value is not valid"; conditionValidationRule9.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CBlech, conditionValidationRule9); this.CBlech.Triggering += new KabMan.Controls.TriggeringEventHandler(this.CBlech_Triggering); // // repositoryItemLookUpEdit1 // this.repositoryItemLookUpEdit1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit1.Name = "repositoryItemLookUpEdit1"; this.repositoryItemLookUpEdit1.NullText = "Select Blech!"; // // CBlechType // this.CBlechType.AddButtonEnabled = true; this.CBlechType.Columns = this.repositoryItemLookUpEdit5.Columns; this.CBlechType.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CBlechType.FormParameters"))); this.CBlechType.Location = new System.Drawing.Point(81, 434); this.CBlechType.Name = "CBlechType"; this.CBlechType.NullText = ""; this.CBlechType.Parameters = new KabMan.Controls.NameValuePair[0]; this.CBlechType.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CBlechType.Properties.NullText = ""; this.CBlechType.RefreshButtonVisible = true; this.CBlechType.Size = new System.Drawing.Size(354, 20); this.CBlechType.StoredProcedure = null; this.CBlechType.StyleController = this.layoutControl1; this.CBlechType.TabIndex = 9; this.CBlechType.TriggerControl = null; conditionValidationRule8.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule8.ErrorText = "This value is not valid"; conditionValidationRule8.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CBlechType, conditionValidationRule8); // // repositoryItemLookUpEdit5 // this.repositoryItemLookUpEdit5.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.repositoryItemLookUpEdit5.Name = "repositoryItemLookUpEdit5"; this.repositoryItemLookUpEdit5.NullText = "Select Blech Type!"; // // CSwitchModel // this.CSwitchModel.AddButtonEnabled = true; this.CSwitchModel.Columns = this.repositoryItemLookUpEdit4.Columns; this.CSwitchModel.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CSwitchModel.FormParameters"))); this.CSwitchModel.Location = new System.Drawing.Point(81, 90); this.CSwitchModel.Name = "CSwitchModel"; this.CSwitchModel.NullText = ""; this.CSwitchModel.Parameters = new KabMan.Controls.NameValuePair[0]; this.CSwitchModel.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CSwitchModel.Properties.NullText = ""; this.CSwitchModel.RefreshButtonVisible = true; this.CSwitchModel.Size = new System.Drawing.Size(354, 20); this.CSwitchModel.StoredProcedure = null; this.CSwitchModel.StyleController = this.layoutControl1; this.CSwitchModel.TabIndex = 10; this.CSwitchModel.TriggerControl = null; conditionValidationRule10.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule10.ErrorText = "This value is not valid"; conditionValidationRule10.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CSwitchModel, conditionValidationRule10); // // repositoryItemLookUpEdit4 // this.repositoryItemLookUpEdit4.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit4.Name = "repositoryItemLookUpEdit4"; this.repositoryItemLookUpEdit4.NullText = "Select Switch Model!"; // // CCoreSwitch // this.CCoreSwitch.Columns = this.repositoryItemLookUpEdit6.Columns; this.CCoreSwitch.Enabled = false; this.CCoreSwitch.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CCoreSwitch.FormParameters"))); this.CCoreSwitch.Location = new System.Drawing.Point(81, 59); this.CCoreSwitch.Name = "CCoreSwitch"; this.CCoreSwitch.NullText = "Select Parent Core Switch!"; nameValuePair9.Name = "@TypeName"; nameValuePair9.Value = "%Core%"; this.CCoreSwitch.Parameters = new KabMan.Controls.NameValuePair[] { nameValuePair9}; this.CCoreSwitch.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.CCoreSwitch.Properties.NullText = "Select Parent Core Switch!"; this.CCoreSwitch.RefreshButtonVisible = true; this.CCoreSwitch.Size = new System.Drawing.Size(354, 20); this.CCoreSwitch.StoredProcedure = null; this.CCoreSwitch.StyleController = this.layoutControl1; this.CCoreSwitch.TabIndex = 8; this.CCoreSwitch.TriggerControl = null; // // repositoryItemLookUpEdit6 // this.repositoryItemLookUpEdit6.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit6.Name = "repositoryItemLookUpEdit6"; this.repositoryItemLookUpEdit6.NullText = "Select Parent Core Switch!"; // // CSwitchType // this.CSwitchType.AddButtonEnabled = true; this.CSwitchType.Columns = this.repositoryItemLookUpEdit7.Columns; this.CSwitchType.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CSwitchType.FormParameters"))); this.CSwitchType.Location = new System.Drawing.Point(81, 28); this.CSwitchType.Name = "CSwitchType"; this.CSwitchType.NullText = ""; this.CSwitchType.Parameters = new KabMan.Controls.NameValuePair[0]; this.CSwitchType.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CSwitchType.Properties.NullText = ""; this.CSwitchType.RefreshButtonVisible = true; this.CSwitchType.Size = new System.Drawing.Size(354, 20); this.CSwitchType.StoredProcedure = null; this.CSwitchType.StyleController = this.layoutControl1; this.CSwitchType.TabIndex = 7; this.CSwitchType.TriggerControl = null; conditionValidationRule11.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule11.ErrorText = "This value is not valid"; conditionValidationRule11.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CSwitchType, conditionValidationRule11); this.CSwitchType.EditValueChanged += new System.EventHandler(this.CSwitchType_EditValueChanged); // // repositoryItemLookUpEdit7 // this.repositoryItemLookUpEdit7.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit7.Name = "repositoryItemLookUpEdit7"; this.repositoryItemLookUpEdit7.NullText = "Select Switch Type!"; // // CVtPort // this.CVtPort.AddButtonEnabled = true; this.CVtPort.Columns = this.repositoryItemLookUpEdit10.Columns; this.CVtPort.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CVtPort.FormParameters"))); this.CVtPort.Location = new System.Drawing.Point(81, 379); this.CVtPort.Name = "CVtPort"; this.CVtPort.NullText = ""; nameValuePair10.Name = "@SanID"; nameValuePair10.Value = null; this.CVtPort.Parameters = new KabMan.Controls.NameValuePair[] { nameValuePair10}; this.CVtPort.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CVtPort.Properties.NullText = ""; this.CVtPort.RefreshButtonVisible = true; this.CVtPort.Size = new System.Drawing.Size(354, 20); this.CVtPort.StoredProcedure = null; this.CVtPort.StyleController = this.layoutControl1; this.CVtPort.TabIndex = 5; this.CVtPort.TriggerControl = this.CSan; conditionValidationRule12.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule12.ErrorText = "This value is not valid"; conditionValidationRule12.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CVtPort, conditionValidationRule12); // // repositoryItemLookUpEdit10 // this.repositoryItemLookUpEdit10.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit10.Name = "repositoryItemLookUpEdit10"; this.repositoryItemLookUpEdit10.NullText = "Select VT Port!"; // // CDataCenter // this.CDataCenter.Columns = this.repositoryItemLookUpEdit11.Columns; this.CDataCenter.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CDataCenter.FormParameters"))); this.CDataCenter.Location = new System.Drawing.Point(81, 207); this.CDataCenter.Name = "CDataCenter"; this.CDataCenter.NullText = ""; nameValuePair11.Name = "@LocationID"; nameValuePair11.Value = null; this.CDataCenter.Parameters = new KabMan.Controls.NameValuePair[] { nameValuePair11}; this.CDataCenter.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.CDataCenter.Properties.NullText = ""; this.CDataCenter.RefreshButtonVisible = true; this.CDataCenter.Size = new System.Drawing.Size(354, 20); this.CDataCenter.StoredProcedure = null; this.CDataCenter.StyleController = this.layoutControl1; this.CDataCenter.TabIndex = 1; this.CDataCenter.TriggerControl = this.CLocation; conditionValidationRule14.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule14.ErrorText = "This value is not valid"; conditionValidationRule14.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CDataCenter, conditionValidationRule14); this.CDataCenter.EditValueChanged += new System.EventHandler(this.CDataCenter_EditValueChanged); // // repositoryItemLookUpEdit11 // this.repositoryItemLookUpEdit11.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit11.Name = "repositoryItemLookUpEdit11"; this.repositoryItemLookUpEdit11.NullText = "Select Data Center!"; // // CLocation // this.CLocation.AddButtonEnabled = true; this.CLocation.Columns = this.repositoryItemLookUpEdit12.Columns; this.CLocation.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CLocation.FormParameters"))); this.CLocation.Location = new System.Drawing.Point(81, 176); this.CLocation.Name = "CLocation"; this.CLocation.NullText = ""; this.CLocation.Parameters = new KabMan.Controls.NameValuePair[0]; this.CLocation.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CLocation.Properties.NullText = ""; this.CLocation.RefreshButtonVisible = true; this.CLocation.Size = new System.Drawing.Size(354, 20); this.CLocation.StoredProcedure = null; this.CLocation.StyleController = this.layoutControl1; this.CLocation.TabIndex = 1; this.CLocation.TriggerControl = null; conditionValidationRule13.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank; conditionValidationRule13.ErrorText = "This value is not valid"; conditionValidationRule13.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning; this.CManagerValidator.SetValidationRule(this.CLocation, conditionValidationRule13); this.CLocation.EditValueChanged += new System.EventHandler(this.CLocation_EditValueChanged); // // repositoryItemLookUpEdit12 // this.repositoryItemLookUpEdit12.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.repositoryItemLookUpEdit12.Name = "repositoryItemLookUpEdit12"; this.repositoryItemLookUpEdit12.NullText = "Select Location!"; // // layoutControlGroup1 // this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1"; this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlGroup2, this.layoutControlGroup3, this.layoutControlGroup4, this.layoutControlGroup6, this.layoutControlGroup7, this.layoutControlGroup5, this.layoutControlItem18}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(444, 615); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.Text = "layoutControlGroup1"; this.layoutControlGroup1.TextVisible = false; // // layoutControlGroup2 // this.layoutControlGroup2.CustomizationFormText = "Location"; this.layoutControlGroup2.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem2, this.layoutControlItem3}); this.layoutControlGroup2.Location = new System.Drawing.Point(0, 148); this.layoutControlGroup2.Name = "layoutControlGroup2"; this.layoutControlGroup2.Size = new System.Drawing.Size(442, 86); this.layoutControlGroup2.Text = "Location"; // // layoutControlItem2 // this.layoutControlItem2.Control = this.CLocation; this.layoutControlItem2.CustomizationFormText = "Location"; this.layoutControlItem2.Location = new System.Drawing.Point(0, 0); this.layoutControlItem2.Name = "layoutControlItem2"; this.layoutControlItem2.Size = new System.Drawing.Size(436, 31); this.layoutControlItem2.Text = "Location"; this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem2.TextSize = new System.Drawing.Size(66, 13); // // layoutControlItem3 // this.layoutControlItem3.Control = this.CDataCenter; this.layoutControlItem3.CustomizationFormText = "DataCenter"; this.layoutControlItem3.Location = new System.Drawing.Point(0, 31); this.layoutControlItem3.Name = "layoutControlItem3"; this.layoutControlItem3.Size = new System.Drawing.Size(436, 31); this.layoutControlItem3.Text = "DataCenter"; this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem3.TextSize = new System.Drawing.Size(66, 13); // // layoutControlGroup3 // this.layoutControlGroup3.CustomizationFormText = "SAN"; this.layoutControlGroup3.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem1, this.layoutControlItem5}); this.layoutControlGroup3.Location = new System.Drawing.Point(0, 234); this.layoutControlGroup3.Name = "layoutControlGroup3"; this.layoutControlGroup3.Size = new System.Drawing.Size(442, 86); this.layoutControlGroup3.Text = "SAN"; // // layoutControlItem1 // this.layoutControlItem1.Control = this.CSanGroup; this.layoutControlItem1.CustomizationFormText = "Group"; this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(436, 31); this.layoutControlItem1.Text = "Group"; this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(66, 13); // // layoutControlItem5 // this.layoutControlItem5.Control = this.CSan; this.layoutControlItem5.CustomizationFormText = "SAN"; this.layoutControlItem5.Location = new System.Drawing.Point(0, 31); this.layoutControlItem5.Name = "layoutControlItem5"; this.layoutControlItem5.Size = new System.Drawing.Size(436, 31); this.layoutControlItem5.Text = "SAN"; this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem5.TextSize = new System.Drawing.Size(66, 13); // // layoutControlGroup4 // this.layoutControlGroup4.CustomizationFormText = "VTPort"; this.layoutControlGroup4.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem4}); this.layoutControlGroup4.Location = new System.Drawing.Point(0, 351); this.layoutControlGroup4.Name = "layoutControlGroup4"; this.layoutControlGroup4.Size = new System.Drawing.Size(442, 55); this.layoutControlGroup4.Text = "VTPort"; // // layoutControlItem4 // this.layoutControlItem4.Control = this.CVtPort; this.layoutControlItem4.CustomizationFormText = "VTPort"; this.layoutControlItem4.Location = new System.Drawing.Point(0, 0); this.layoutControlItem4.Name = "layoutControlItem4"; this.layoutControlItem4.Size = new System.Drawing.Size(436, 31); this.layoutControlItem4.Text = "VTPort"; this.layoutControlItem4.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem4.TextSize = new System.Drawing.Size(66, 13); // // layoutControlGroup6 // this.layoutControlGroup6.CustomizationFormText = "Blech"; this.layoutControlGroup6.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem10, this.layoutControlItem8}); this.layoutControlGroup6.Location = new System.Drawing.Point(0, 406); this.layoutControlGroup6.Name = "layoutControlGroup6"; this.layoutControlGroup6.Size = new System.Drawing.Size(442, 86); this.layoutControlGroup6.Text = "Blech"; // // layoutControlItem10 // this.layoutControlItem10.Control = this.CBlech; this.layoutControlItem10.CustomizationFormText = "Blech"; this.layoutControlItem10.Location = new System.Drawing.Point(0, 31); this.layoutControlItem10.Name = "layoutControlItem10"; this.layoutControlItem10.Size = new System.Drawing.Size(436, 31); this.layoutControlItem10.Text = "Blech"; this.layoutControlItem10.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem10.TextSize = new System.Drawing.Size(66, 13); // // layoutControlItem8 // this.layoutControlItem8.Control = this.CBlechType; this.layoutControlItem8.CustomizationFormText = "Blech Type"; this.layoutControlItem8.Location = new System.Drawing.Point(0, 0); this.layoutControlItem8.Name = "layoutControlItem8"; this.layoutControlItem8.Size = new System.Drawing.Size(436, 31); this.layoutControlItem8.Text = "Blech Type"; this.layoutControlItem8.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem8.TextSize = new System.Drawing.Size(66, 13); // // layoutControlGroup7 // this.layoutControlGroup7.CustomizationFormText = "LC URM"; this.layoutControlGroup7.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem15, this.layoutControlItem13, this.layoutControlItem14, this.emptySpaceItem1, this.layoutControlItem16, this.layoutControlItem17, this.layoutControlItem19}); this.layoutControlGroup7.Location = new System.Drawing.Point(0, 492); this.layoutControlGroup7.Name = "layoutControlGroup7"; this.layoutControlGroup7.Size = new System.Drawing.Size(442, 121); this.layoutControlGroup7.Text = "LC URM"; // // layoutControlItem15 // this.layoutControlItem15.Control = this.CLcLength; this.layoutControlItem15.CustomizationFormText = "Length"; this.layoutControlItem15.Location = new System.Drawing.Point(0, 0); this.layoutControlItem15.Name = "layoutControlItem15"; this.layoutControlItem15.Size = new System.Drawing.Size(264, 31); this.layoutControlItem15.Text = "Length"; this.layoutControlItem15.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem15.TextSize = new System.Drawing.Size(66, 13); // // layoutControlItem13 // this.layoutControlItem13.Control = this.CLcCount; this.layoutControlItem13.CustomizationFormText = "Count"; this.layoutControlItem13.Location = new System.Drawing.Point(264, 0); this.layoutControlItem13.Name = "layoutControlItem13"; this.layoutControlItem13.Size = new System.Drawing.Size(172, 31); this.layoutControlItem13.Text = "Count"; this.layoutControlItem13.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem13.TextSize = new System.Drawing.Size(66, 13); // // layoutControlItem14 // this.layoutControlItem14.Control = this.CLcCable; this.layoutControlItem14.CustomizationFormText = "Cable"; this.layoutControlItem14.Location = new System.Drawing.Point(0, 31); this.layoutControlItem14.Name = "layoutControlItem14"; this.layoutControlItem14.Size = new System.Drawing.Size(436, 31); this.layoutControlItem14.Text = "Cable"; this.layoutControlItem14.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem14.TextSize = new System.Drawing.Size(66, 13); // // emptySpaceItem1 // this.emptySpaceItem1.CustomizationFormText = "emptySpaceItem1"; this.emptySpaceItem1.Location = new System.Drawing.Point(0, 62); this.emptySpaceItem1.Name = "emptySpaceItem1"; this.emptySpaceItem1.Size = new System.Drawing.Size(163, 35); this.emptySpaceItem1.Text = "emptySpaceItem1"; this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0); // // layoutControlItem16 // this.layoutControlItem16.Control = this.btnSave; this.layoutControlItem16.CustomizationFormText = "layoutControlItem16"; this.layoutControlItem16.Location = new System.Drawing.Point(163, 62); this.layoutControlItem16.MaxSize = new System.Drawing.Size(91, 33); this.layoutControlItem16.MinSize = new System.Drawing.Size(91, 33); this.layoutControlItem16.Name = "layoutControlItem16"; this.layoutControlItem16.Size = new System.Drawing.Size(91, 35); this.layoutControlItem16.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom; this.layoutControlItem16.Text = "layoutControlItem16"; this.layoutControlItem16.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem16.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem16.TextToControlDistance = 0; this.layoutControlItem16.TextVisible = false; // // layoutControlItem17 // this.layoutControlItem17.Control = this.btnClose; this.layoutControlItem17.CustomizationFormText = "layoutControlItem17"; this.layoutControlItem17.Location = new System.Drawing.Point(345, 62); this.layoutControlItem17.MaxSize = new System.Drawing.Size(91, 33); this.layoutControlItem17.MinSize = new System.Drawing.Size(91, 33); this.layoutControlItem17.Name = "layoutControlItem17"; this.layoutControlItem17.Size = new System.Drawing.Size(91, 35); this.layoutControlItem17.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom; this.layoutControlItem17.Text = "layoutControlItem17"; this.layoutControlItem17.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem17.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem17.TextToControlDistance = 0; this.layoutControlItem17.TextVisible = false; // // layoutControlItem19 // this.layoutControlItem19.Control = this.btnSaveClose; this.layoutControlItem19.CustomizationFormText = "layoutControlItem19"; this.layoutControlItem19.Location = new System.Drawing.Point(254, 62); this.layoutControlItem19.MaxSize = new System.Drawing.Size(91, 33); this.layoutControlItem19.MinSize = new System.Drawing.Size(91, 33); this.layoutControlItem19.Name = "layoutControlItem19"; this.layoutControlItem19.Size = new System.Drawing.Size(91, 35); this.layoutControlItem19.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom; this.layoutControlItem19.Text = "layoutControlItem19"; this.layoutControlItem19.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem19.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem19.TextToControlDistance = 0; this.layoutControlItem19.TextVisible = false; // // layoutControlGroup5 // this.layoutControlGroup5.CustomizationFormText = "Switch"; this.layoutControlGroup5.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem6, this.layoutControlItem9, this.layoutControlItem7, this.layoutControlItem11, this.layoutControlItem12}); this.layoutControlGroup5.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup5.Name = "layoutControlGroup5"; this.layoutControlGroup5.Size = new System.Drawing.Size(442, 148); this.layoutControlGroup5.Text = "Switch"; // // layoutControlItem6 // this.layoutControlItem6.Control = this.CSwitchType; this.layoutControlItem6.CustomizationFormText = "Type"; this.layoutControlItem6.Location = new System.Drawing.Point(0, 0); this.layoutControlItem6.Name = "layoutControlItem6"; this.layoutControlItem6.Size = new System.Drawing.Size(436, 31); this.layoutControlItem6.Text = "Type"; this.layoutControlItem6.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem6.TextSize = new System.Drawing.Size(66, 13); // // layoutControlItem9 // this.layoutControlItem9.Control = this.CSwitchModel; this.layoutControlItem9.CustomizationFormText = "Model"; this.layoutControlItem9.Location = new System.Drawing.Point(0, 62); this.layoutControlItem9.Name = "layoutControlItem9"; this.layoutControlItem9.Size = new System.Drawing.Size(436, 31); this.layoutControlItem9.Text = "Model"; this.layoutControlItem9.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem9.TextSize = new System.Drawing.Size(66, 13); // // layoutControlItem7 // this.layoutControlItem7.Control = this.CCoreSwitch; this.layoutControlItem7.CustomizationFormText = "Core Switch"; this.layoutControlItem7.Location = new System.Drawing.Point(0, 31); this.layoutControlItem7.Name = "layoutControlItem7"; this.layoutControlItem7.Size = new System.Drawing.Size(436, 31); this.layoutControlItem7.Text = "Core Switch"; this.layoutControlItem7.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem7.TextSize = new System.Drawing.Size(66, 13); // // layoutControlItem11 // this.layoutControlItem11.Control = this.CSwitchSerial; this.layoutControlItem11.CustomizationFormText = "Serial Number"; this.layoutControlItem11.Location = new System.Drawing.Point(0, 93); this.layoutControlItem11.Name = "layoutControlItem11"; this.layoutControlItem11.Size = new System.Drawing.Size(218, 31); this.layoutControlItem11.Text = "Serial Number"; this.layoutControlItem11.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem11.TextSize = new System.Drawing.Size(66, 13); // // layoutControlItem12 // this.layoutControlItem12.Control = this.CSwitchIP; this.layoutControlItem12.CustomizationFormText = "IP Number"; this.layoutControlItem12.Location = new System.Drawing.Point(218, 93); this.layoutControlItem12.Name = "layoutControlItem12"; this.layoutControlItem12.Size = new System.Drawing.Size(218, 31); this.layoutControlItem12.Text = "IP Number"; this.layoutControlItem12.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem12.TextSize = new System.Drawing.Size(66, 13); // // layoutControlItem18 // this.layoutControlItem18.Control = this.CFirstTrunk; this.layoutControlItem18.CustomizationFormText = "Trunk Cable"; this.layoutControlItem18.Location = new System.Drawing.Point(0, 320); this.layoutControlItem18.Name = "layoutControlItem18"; this.layoutControlItem18.Size = new System.Drawing.Size(442, 31); this.layoutControlItem18.Text = "Trunk Cable"; this.layoutControlItem18.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem18.TextSize = new System.Drawing.Size(66, 13); // // NewSwitchForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(444, 615); this.Controls.Add(this.layoutControl1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "NewSwitchForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "New Switch"; ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit13)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.CFirstTrunk.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CSan.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit8)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CSanGroup.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit9)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CLcLength.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CLcCable.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CLcCount.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CSwitchIP.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CSwitchSerial.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CBlech.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CBlechType.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit5)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CSwitchModel.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CCoreSwitch.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit6)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CSwitchType.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit7)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CVtPort.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit10)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CDataCenter.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit11)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CLocation.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit12)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup6)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem10)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem8)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup7)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem15)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem13)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem14)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem16)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem17)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem19)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup5)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem11)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem12)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem18)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CManagerValidator)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private KabMan.Controls.C_LookUpControl CDataCenter; private KabMan.Controls.C_LookUpControl CLocation; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3; private KabMan.Controls.C_LookUpControl CSan; private KabMan.Controls.C_LookUpControl CVtPort; private KabMan.Controls.C_LookUpControl CSanGroup; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup2; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup3; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5; private KabMan.Controls.C_LookUpControl CSwitchType; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup4; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4; private KabMan.Controls.C_LookUpControl CSwitchModel; private KabMan.Controls.C_LookUpControl CBlechType; private KabMan.Controls.C_LookUpControl CCoreSwitch; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem7; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem8; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem9; private KabMan.Controls.C_LookUpControl CBlech; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup5; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem10; private DevExpress.XtraEditors.TextEdit CSwitchIP; private DevExpress.XtraEditors.TextEdit CSwitchSerial; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem11; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup6; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem12; private KabMan.Controls.C_LookUpControl CLcLength; private KabMan.Controls.C_LookUpControl CLcCable; private DevExpress.XtraEditors.SpinEdit CLcCount; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem13; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem14; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem15; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup7; private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1; private DevExpress.XtraEditors.DXErrorProvider.DXValidationProvider CManagerValidator; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit2; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit3; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit1; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit5; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit4; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit6; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit7; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit8; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit9; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit10; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit11; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit12; private KabMan.Controls.C_LookUpControl CFirstTrunk; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem18; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit13; private DevExpress.XtraEditors.SimpleButton btnSave; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem16; private DevExpress.XtraEditors.SimpleButton btnClose; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem17; private DevExpress.XtraEditors.SimpleButton btnSaveClose; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem19; } }
using System; using AnotherNamespace; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.ConsoleArguments; using BenchmarkDotNet.Tests; using NamespaceB; using NamespaceB.NamespaceC; using Xunit; using MyClassA = NamespaceB.MyClassA; namespace BenchmarkDotNet.Tests { public class CorrectionsSuggesterTests { [Fact] public void CheckNullArgument() { Assert.Throws<ArgumentNullException>(() => new CorrectionsSuggester(new[] { typeof(NamespaceB.NamespaceC.MyClassC) }).SuggestFor(null)); } [Fact] public void CheckLexicographicalOrder() { var suggestedNames = new CorrectionsSuggester(new[] { typeof(AnotherNamespace.MyClassZ), typeof(NamespaceA.MyClassA), typeof(NamespaceB.MyClassB), typeof(NamespaceB.NamespaceC.MyClassC) }).GetAllBenchmarkNames(); Assert.Equal(new[] { "AnotherNamespace.MyClassZ.MethodZ", "NamespaceA.MyClassA.MethodA", "NamespaceA.MyClassA.MethodB", "NamespaceB.MyClassB.MethodB", "NamespaceB.MyClassB.MethodC", "NamespaceB.NamespaceC.MyClassC.MethodC" }, suggestedNames); } [Fact] public void FilterUnknownBenchmark_CollectionIsEmpty() { var suggestedNames = new CorrectionsSuggester(new[] { typeof(NamespaceA.MyClassA), typeof(NamespaceB.MyClassB), typeof(AnotherNamespace.MyClassZ), typeof(NamespaceB.NamespaceC.MyClassC) }).SuggestFor("Anything"); Assert.Empty(suggestedNames); } [Fact] public void FilterByCompositeNamespace_LevenshteinOrdering() { var suggestedNames = new CorrectionsSuggester(new[] { typeof(NamespaceA.NamespaceC.MyClassA), typeof(NamespaceB.NamespaceC.MyClassC), typeof(AnotherNamespace.InnerNamespaceA.MyClassA) }).SuggestFor("NmespaceB.NamespaceC"); Assert.Equal(new[] { "NamespaceB.NamespaceC*", "NamespaceA.NamespaceC*" }, suggestedNames); } [Fact] public void FilterByNamespace_LevenshteinOrdering() { var suggestedNames = new CorrectionsSuggester(new[] { typeof(NamespaceA.MyClassA), typeof(NamespaceB.MyClassB), typeof(AnotherNamespace.MyClassZ), typeof(NamespaceB.NamespaceC.MyClassC) }).SuggestFor("Nmespace"); Assert.Equal(new[] { "NamespaceA*", "NamespaceB*" }, suggestedNames); } [Fact] public void FilterByInnerNamespace_LevenshteinOrdering() { var suggestedNames = new CorrectionsSuggester(new[] { typeof(AnotherNamespace.InnerNamespaceA.MyClassA), typeof(AnotherNamespace.InnerNamespaceB.MyClassA), typeof(Lexicographical.MyClassLexicAACDE) }).SuggestFor("InerNamespaceB"); Assert.Equal(new[] { "*InnerNamespaceB*" }, suggestedNames); } [Fact] public void FilterByClassFromDifferentNamespaces() { var suggestedNames = new CorrectionsSuggester(new[] { typeof(MyClassA), typeof(NamespaceA.MyClassA) }) .SuggestFor("MyClasA"); Assert.Equal(new[] { "*MyClassA*" }, suggestedNames); } [Fact] public void FilterByClass_LevenshteinOrdering() { var suggestedNames = new CorrectionsSuggester(new[] { typeof(MyClassA), typeof(MyClassB), typeof(MyClassC), typeof(MyClassZ), typeof(NamespaceB.NamespaceC.MyClassA), typeof(MyClassZ.MyClassY) }).SuggestFor("MyClasZ"); Assert.Equal(new[] { "*MyClassZ*" }, suggestedNames); } [Fact] public void FilterByNamespaceClassMethod_LevenshteinOrdering() { var suggestedNames = new CorrectionsSuggester(new[] { typeof(NamespaceB.MyClassA), typeof(NamespaceA.MyClassA), typeof(NamespaceB.NamespaceC.MyClassA) }).SuggestFor("NamespaceA.MyClasA.MethodA"); Assert.Equal(new[] { "NamespaceA.MyClassA.MethodA", "NamespaceA.MyClassA.MethodB", "NamespaceB.MyClassA.MethodA", }, suggestedNames); } [Fact] public void FilterGeneric_LevenshteinOrdering() { var suggestedNames = new CorrectionsSuggester(new[] { typeof(Generics.GenericA<int>), typeof(Generics.GenericB<int>) }).SuggestFor("GeneriA<Int32>"); Assert.Equal(new[] { "*GenericA<Int32>*" }, suggestedNames); } } } namespace Generics { [DontRun] public class GenericA<T> { [Benchmark] public void MethodG1() { } } [DontRun] public class GenericB<T> { [Benchmark] public void MethodG1() { } } } namespace NamespaceA { [DontRun] public class MyClassA { [Benchmark] public void MethodA() { } [Benchmark] public void MethodB() { } } namespace NamespaceC { [DontRun] public class MyClassA { [Benchmark] public void MethodA() { } } } } namespace NamespaceB { [DontRun] public class MyClassA { [Benchmark] public void MethodA() { } } [DontRun] public class MyClassB { [Benchmark] public void MethodB() { } [Benchmark] public void MethodC() { } } namespace NamespaceC { [DontRun] public class MyClassA { [Benchmark] public void MethodA() { } [Benchmark] public void MethodB() { } } [DontRun] public class MyClassC { [Benchmark] public void MethodC() { } } } } namespace AnotherNamespace { [DontRun] public class MyClassZ { [Benchmark] public void MethodZ() { } [DontRun] public class MyClassY { [Benchmark] public void MethodY() { } } } namespace InnerNamespaceA { [DontRun] public class MyClassA { [Benchmark] public void MethodA() { } } } namespace InnerNamespaceB { [DontRun] public class MyClassA { [Benchmark] public void MethodA() { } } } } namespace Lexicographical { [DontRun] public class MyClassLexicABCDE { [Benchmark] public void MethodA() { } } [DontRun] public class MyClassLexicAACDE { [Benchmark] public void MethodA() { } } [DontRun] public class MyClassLexicAACDZ { [Benchmark] public void MethodA() { } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System.Collections.Generic; using System; using NPOI.XSSF.Util; using System.IO; using NPOI.OpenXml4Net.OPC; using System.Text.RegularExpressions; using NPOI.OpenXmlFormats.Vml; using System.Xml.Serialization; using System.Xml; using System.Collections; using NPOI.OpenXmlFormats.Vml.Office; using NPOI.OpenXmlFormats.Vml.Spreadsheet; using System.Text; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; namespace NPOI.XSSF.UserModel { /** * Represents a SpreadsheetML VML Drawing. * * <p> * In Excel 2007 VML Drawings are used to describe properties of cell comments, * although the spec says that VML is deprecated: * </p> * <p> * The VML format is a legacy format originally introduced with Office 2000 and is included and fully defined * in this Standard for backwards compatibility reasons. The DrawingML format is a newer and richer format * Created with the goal of eventually replacing any uses of VML in the Office Open XML formats. VML should be * considered a deprecated format included in Office Open XML for legacy reasons only and new applications that * need a file format for Drawings are strongly encouraged to use preferentially DrawingML * </p> * * <p> * Warning - Excel is known to Put invalid XML into these files! * For example, &gt;br&lt; without being closed or escaped crops up. * </p> * * See 6.4 VML - SpreadsheetML Drawing in Office Open XML Part 4 - Markup Language Reference.pdf * * @author Yegor Kozlov */ public class XSSFVMLDrawing : POIXMLDocumentPart { private static XmlQualifiedName QNAME_SHAPE_LAYOUT = new XmlQualifiedName("shapelayout", "urn:schemas-microsoft-com:office:office"); private static XmlQualifiedName QNAME_SHAPE_TYPE = new XmlQualifiedName("shapetype", "urn:schemas-microsoft-com:vml"); private static XmlQualifiedName QNAME_SHAPE = new XmlQualifiedName("shape", "urn:schemas-microsoft-com:vml"); /** * regexp to parse shape ids, in VML they have weird form of id="_x0000_s1026" */ private static Regex ptrn_shapeId = new Regex("_x0000_s(\\d+)"); private static Regex ptrn_shapeTypeId = new Regex("_x0000_[tm](\\d+)"); private ArrayList _items = new ArrayList(); private int _shapeTypeId=202; private int _shapeId = 1024; /** * Create a new SpreadsheetML Drawing * * @see XSSFSheet#CreateDrawingPatriarch() */ public XSSFVMLDrawing() : base() { newDrawing(); } /** * Construct a SpreadsheetML Drawing from a namespace part * * @param part the namespace part holding the Drawing data, * the content type must be <code>application/vnd.Openxmlformats-officedocument.Drawing+xml</code> * @param rel the namespace relationship holding this Drawing, * the relationship type must be http://schemas.Openxmlformats.org/officeDocument/2006/relationships/drawing */ protected XSSFVMLDrawing(PackagePart part, PackageRelationship rel) : base(part, rel) { Read(GetPackagePart().GetInputStream()); } internal void Read(Stream is1) { XmlDocument doc = new XmlDocument(); //InflaterInputStream iis = (InflaterInputStream)is1; StreamReader sr = new StreamReader(is1); string data = sr.ReadToEnd(); //Stream vmlsm = new EvilUnclosedBRFixingInputStream(is1); --TODO:: add later doc.LoadXml( data.Replace("<br>","") ); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("o", "urn:schemas-microsoft-com:office:office"); nsmgr.AddNamespace("x", "urn:schemas-microsoft-com:office:excel"); nsmgr.AddNamespace("v", "urn:schemas-microsoft-com:vml"); _items = new ArrayList(); XmlNodeList nodes=doc.SelectNodes("/xml/*",nsmgr); foreach (XmlNode nd in nodes) { string xmltext = nd.OuterXml; if (nd.LocalName == QNAME_SHAPE_LAYOUT.Name) { CT_ShapeLayout sl=CT_ShapeLayout.Parse(nd, nsmgr); _items.Add(sl); } else if (nd.LocalName == QNAME_SHAPE_TYPE.Name) { CT_Shapetype st = CT_Shapetype.Parse(nd, nsmgr); String typeid = st.id; if (typeid != null) { MatchCollection m = ptrn_shapeTypeId.Matches(typeid); if (m.Count>0) _shapeTypeId = Math.Max(_shapeTypeId, int.Parse(m[0].Groups[1].Value)); } _items.Add(st); } else if (nd.LocalName == QNAME_SHAPE.Name) { CT_Shape shape = CT_Shape.Parse(nd, nsmgr); String id = shape.id; if (id != null) { MatchCollection m = ptrn_shapeId.Matches(id); if (m.Count>0) _shapeId = Math.Max(_shapeId, int.Parse(m[0].Groups[1].Value)); } _items.Add(shape); } else { _items.Add(nd); } } } internal ArrayList GetItems() { return _items; } internal void Write(Stream out1) { using (StreamWriter sw = new StreamWriter(out1)) { sw.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sw.Write("<xml"); sw.Write(" xmlns:v=\"urn:schemas-microsoft-com:vml\""); sw.Write(" xmlns:o=\"urn:schemas-microsoft-com:office:office\""); sw.Write(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\""); sw.Write(" xmlns:w=\"urn:schemas-microsoft-com:office:word\""); sw.Write(" xmlns:p=\"urn:schemas-microsoft-com:office:powerpoint\""); sw.Write(">"); for (int i = 0; i < _items.Count; i++) { object xc = _items[i]; if (xc is XmlNode) { sw.Write(((XmlNode)xc).OuterXml.Replace(" xmlns:v=\"urn:schemas-microsoft-com:vml\"", "").Replace(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"", "").Replace(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"", "").Replace("&#xD;&#xA;", "")); } else if (xc is CT_Shapetype) { ((CT_Shapetype)xc).Write(sw, "shapetype"); } else if (xc is CT_ShapeLayout) { ((CT_ShapeLayout)xc).Write(sw, "shapelayout"); } else if (xc is CT_Shape) { ((CT_Shape)xc).Write(sw, "shape"); } else { sw.Write(xc.ToString().Replace(" xmlns:v=\"urn:schemas-microsoft-com:vml\"", "").Replace(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"", "").Replace(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"", "").Replace("&#xD;&#xA;", "")); } } sw.Write("</xml>"); } //rootObject.save(out1); } protected override void Commit() { PackagePart part = GetPackagePart(); Stream out1 = part.GetOutputStream(); Write(out1); out1.Close(); } /** * Initialize a new Speadsheet VML Drawing */ private void newDrawing() { CT_ShapeLayout layout = new CT_ShapeLayout(); layout.ext = (ST_Ext.edit); CT_IdMap idmap = layout.AddNewIdmap(); idmap.ext = (ST_Ext.edit); idmap.data = ("1"); _items.Add(layout); CT_Shapetype shapetype = new CT_Shapetype(); shapetype.id= "_x0000_t" + _shapeTypeId; shapetype.coordsize="21600,21600"; shapetype.spt=202; //_shapeTypeId = 202; shapetype.path2 = ("m,l,21600r21600,l21600,xe"); shapetype.AddNewStroke().joinstyle = (ST_StrokeJoinStyle.miter); CT_Path path = shapetype.AddNewPath(); path.gradientshapeok = NPOI.OpenXmlFormats.Vml.ST_TrueFalse.t; path.connecttype=(ST_ConnectType.rect); _items.Add(shapetype); } internal CT_Shape newCommentShape() { CT_Shape shape = new CT_Shape(); shape.id = "_x0000_s" + (++_shapeId); shape.type ="#_x0000_t" + _shapeTypeId; shape.style="position:absolute; visibility:hidden"; shape.fillcolor = ("#ffffe1"); shape.insetmode = (ST_InsetMode.auto); shape.AddNewFill().color=("#ffffe1"); CT_Shadow shadow = shape.AddNewShadow(); shadow.on= NPOI.OpenXmlFormats.Vml.ST_TrueFalse.t; shadow.color = "black"; shadow.obscured = NPOI.OpenXmlFormats.Vml.ST_TrueFalse.t; shape.AddNewPath().connecttype = (ST_ConnectType.none); shape.AddNewTextbox().style = ("mso-direction-alt:auto"); CT_ClientData cldata = shape.AddNewClientData(); cldata.ObjectType=ST_ObjectType.Note; cldata.AddNewMoveWithCells(); cldata.AddNewSizeWithCells(); cldata.AddNewAnchor("1, 15, 0, 2, 3, 15, 3, 16"); cldata.AddNewAutoFill(ST_TrueFalseBlank.@false); cldata.AddNewRow(0); cldata.AddNewColumn(0); _items.Add(shape); return shape; } /** * Find a shape with ClientData of type "NOTE" and the specified row and column * * @return the comment shape or <code>null</code> */ internal CT_Shape FindCommentShape(int row, int col) { foreach (object itm in _items) { if (itm is CT_Shape) { CT_Shape sh = (CT_Shape)itm; if (sh.sizeOfClientDataArray() > 0) { CT_ClientData cldata = sh.GetClientDataArray(0); if (cldata.ObjectType == ST_ObjectType.Note) { int crow = cldata.GetRowArray(0); int ccol = cldata.GetColumnArray(0); if (crow == row && ccol == col) { return sh; } } } } } return null; } internal bool RemoveCommentShape(int row, int col) { CT_Shape shape = FindCommentShape(row, col); if(shape == null) return false; _items.Remove(shape); return true; } } }
//--------------------------------------------------------------------------- // // <copyright file="ClickablePoint.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Class to get a point that some can click on // // History: // 06/03/2003 : preid Created // //--------------------------------------------------------------------------- using System.Windows.Automation; using MS.Internal.Automation; using MS.Win32; using System; namespace System.Windows.Automation { static internal class ClickablePoint { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods // We will not always find the clickable point. There are times when it would take so long // to locate the point that it is just not worth it, so make a reason effort than quit. public static bool HitTestForClickablePoint(AutomationElement el, out Point pt) { Rect rect = el.Current.BoundingRectangle; pt = new Point(0, 0); if (rect.Left >= rect.Right || rect.Top >= rect.Bottom) return false; // if this is not on any monitor than there is no point in going on. If the element is // off the screen hit testing actually works and would end up returning a point offscreen. NativeMethods.RECT winRect = new NativeMethods.RECT((int)rect.Left, (int)rect.Top, (int)rect.Height, (int)rect.Bottom); if (SafeNativeMethods.MonitorFromRect( ref winRect, SafeNativeMethods.MONITOR_DEFAULTTONULL ) == IntPtr.Zero) return false; // try the center point first pt = new Point((rect.Left + rect.Right) / 2, (rect.Top + rect.Bottom) / 2); AutomationElement hitElement; if ( TryPoint( ref pt, el, out hitElement ) ) return true; if ( IsTopLevelWindowObscuring( el, rect, hitElement ) ) return false; // before we start hit testing more there are some control types that we know where the // clickable point is or we know does not have a clickable point so take care of those here. if ( el.Current.ControlType == ControlType.ScrollBar ) return false; // Try the mid point of all four sides pt = new Point(rect.Left + (rect.Width /2), rect.Top + 1); if ( TryPoint( ref pt, el ) ) return true; pt = new Point(rect.Left + (rect.Width /2), rect.Bottom - 1); if ( TryPoint( ref pt, el ) ) return true; pt = new Point( rect.Left + 1, rect.Top + (rect.Height /2) ); if ( TryPoint( ref pt, el) ) return true; pt = new Point( rect.Right - 1, rect.Top + (rect.Height /2) ); if ( TryPoint( ref pt, el ) ) return true; if ( TrySparsePattern( out pt, ref rect, el ) ) return true; if ( TryLinePattern( out pt, ref rect, el ) ) return true; return false; } #endregion Public Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // Go from the top left on a diagonal the lower right but don't do more than 25 hits private static bool TryLinePattern( out Point pt, ref Rect rect, AutomationElement el) { double x = rect.Left + 1; double y = rect.Top + 1; int hits; // Adjust the number of hits we do based on how big something is Double size = rect.Width * rect.Height; if ( size < 2500 ) hits = 10; else if ( size < 20000 ) hits = 18; else hits = 25; double xIncr = rect.Width / hits; double yIncr = rect.Height / hits; for ( int i = 0; i < hits; i++) { pt = new Point(x, y); if ( TryPoint( ref pt, el ) ) return true; x += xIncr; y += yIncr; } pt = new Point(0, 0); return false; } // Hit test in a fairly uniform pattern like a grid adjusting the spacing based on the // size of element. Don't more than about 25 hits. private static bool TrySparsePattern( out Point pt, ref Rect rect, AutomationElement el) { int hits; // Adjust the number of hits we do based on how big somting is Double size = rect.Width * rect.Height; if ( size < 2500 ) hits = 3; else if ( size < 20000 ) hits = 4; else hits = 5; // make the scatter pattern fit the proportions of the rect double xHits = hits * (rect.Width / rect.Height); double yHits = hits * (rect.Height / rect.Width); double xMovePixels = rect.Width / xHits; double yMovePixels = rect.Height / yHits; return TryPattern( xMovePixels, yMovePixels, out pt, ref rect, el ); } // this goes across the rect in icrements of x pixels and the down y pixels and across again... private static bool TryPattern(double x, double y, out Point pt, ref Rect rect, AutomationElement el ) { for ( double down = rect.Top + y; down < rect.Bottom; down += y ) { for ( double across = rect.Left + x; across < rect.Right; across += x ) { pt = new Point(across, down); if ( TryPoint(ref pt, el) ) return true; } } pt = new Point(0, 0); return false; } private static bool TryPoint( ref Point pt, AutomationElement el ) { AutomationElement hitEl; return TryPoint( ref pt, el, out hitEl ); } private static bool TryPoint( ref Point pt, AutomationElement el, out AutomationElement hitEl ) { // If the element is obscured by another window or hidden somehow when we try to hit test we don't get back // the same element. We want to make sure if someone clicks they click on what they expected to click on. hitEl = AutomationElement.FromPoint(pt); return hitEl == el; } // figure out if there is a top level window totally obscuring the element. If that is the case // there is not point in going on. This code assumes that toplevel windows are rects and that // everything in that rect covers up what is underneath. private static bool IsTopLevelWindowObscuring( AutomationElement target, Rect targetRect, AutomationElement hitTarget) { // get the toplevel window for the element that we hit on our first try and the element the we are // trying to find a clickable point for. If they are part of the same top level hwnd than there is // no toplevel window obscuring this element. // There is a rather strange case that can occur with apps like media player where the // hitTarget could be something underneth the element. In this case zorder might be something to // check but this is hwnd specific it may be better for the provider to provide a clickable point. AutomationElement hitTargetAncestor = GetTopLevelAncestor(hitTarget); if ( GetTopLevelAncestor(target) == hitTargetAncestor || hitTargetAncestor == null ) return false; // If this toplevel widow completely covers the element than we are obscured. Rect hitTargetAncestorRect = hitTargetAncestor.Current.BoundingRectangle; if (hitTargetAncestorRect.Contains( targetRect ) ) return true; return false; } private static AutomationElement GetTopLevelAncestor( AutomationElement target ) { AutomationElement root = AutomationElement.RootElement; AutomationElement targetAncestor = null; while (target != root) { targetAncestor = target; target = TreeWalker.ControlViewWalker.GetParent( target ); } return targetAncestor; } } #endregion Private Methods }